instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void extractLibrary(File librarySystemPath, InputStream input) throws IOException { if (input != null) { try (FileOutputStream output = new FileOutputStream(librarySystemPath)) { byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } output.close(); } catch (IOException e) { /* Extracting the library may fail, for example because 'nativeFile' already exists and is in use by another process. In this case, we fail silently and just try to load the existing file. */ if (!librarySystemPath.exists()) { throw e; } } finally { input.close(); } } else { throw new IOException("Failed to read input stream for " + librarySystemPath.getCanonicalPath()); } }
#vulnerable code private static void extractLibrary(File librarySystemPath, InputStream input) throws IOException { if (input != null) { try { FileOutputStream output = new FileOutputStream(librarySystemPath); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } output.close(); } catch (IOException e) { /* Extracting the library may fail, for example because 'nativeFile' already exists and is in use by another process. In this case, we fail silently and just try to load the existing file. */ if (!librarySystemPath.exists()) { throw e; } } finally { input.close(); } } else { throw new IOException("Failed to read input stream for " + librarySystemPath.getCanonicalPath()); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void processInput(String input) throws SteamException { if (input.equals("stats request")) { userStats.requestCurrentStats(); } else if (input.equals("stats store")) { userStats.storeStats(); } else if (input.startsWith("achievement set ")) { String achievementName = input.substring("achievement set ".length()); System.out.println("- setting " + achievementName + " to 'achieved'"); userStats.setAchievement(achievementName); } else if (input.startsWith("achievement clear ")) { String achievementName = input.substring("achievement clear ".length()); System.out.println("- clearing " + achievementName); userStats.clearAchievement(achievementName); } else if (input.equals("file list")) { int numFiles = remoteStorage.getFileCount(); System.out.println("Num of files: " + numFiles); for (int i = 0; i < numFiles; i++) { int[] sizes = new int[1]; String name = remoteStorage.getFileNameAndSize(i, sizes); boolean exists = remoteStorage.fileExists(name); System.out.println("# " + i + " : name=" + name + ", size=" + sizes[0] + ", exists=" + (exists ? "yes" : "no")); } } else if (input.startsWith("file write ")) { String path = input.substring("file write ".length()); File file = new File(path); try { FileInputStream in = new FileInputStream(file); SteamUGCFileWriteStreamHandle remoteFile = remoteStorage.fileWriteStreamOpen(path); if (remoteFile != null) { byte[] bytes = new byte[1024]; int bytesRead; while((bytesRead = in.read(bytes, 0, bytes.length)) > 0) { ByteBuffer buffer = ByteBuffer.allocateDirect(bytesRead); buffer.put(bytes, 0, bytesRead); remoteStorage.fileWriteStreamWriteChunk(remoteFile, buffer, buffer.limit()); } remoteStorage.fileWriteStreamClose(remoteFile); } } catch (IOException e) { e.printStackTrace(); } } else if (input.startsWith("file delete ")) { String path = input.substring("file delete ".length()); if (remoteStorage.fileDelete(path)) { System.out.println("deleted file '" + path + "'"); } } else if (input.startsWith("file share ")) { remoteStorage.fileShare(input.substring("file share ".length())); } else if (input.startsWith("file publish ")) { String[] paths = input.substring("file publish ".length()).split(" "); if (paths.length >= 2) { System.out.println("publishing file: " + paths[0] + ", preview file: " + paths[1]); remoteStorage.publishWorkshopFile(paths[0], paths[1], utils.getAppID(), "Test UGC!", "Dummy UGC file published by test application.", SteamRemoteStorage.PublishedFileVisibility.Private, null, SteamRemoteStorage.WorkshopFileType.Community); } } else if (input.startsWith("file republish ")) { String[] paths = input.substring("file republish ".length()).split(" "); if (paths.length >= 3) { System.out.println("republishing id: " + paths[0] + ", file: " + paths[1] + ", preview file: " + paths[2]); SteamPublishedFileID fileID = new SteamPublishedFileID(Long.parseLong(paths[0])); SteamPublishedFileUpdateHandle updateHandle = remoteStorage.createPublishedFileUpdateRequest(fileID); if (updateHandle != null) { remoteStorage.updatePublishedFileFile(updateHandle, paths[1]); remoteStorage.updatePublishedFilePreviewFile(updateHandle, paths[2]); remoteStorage.updatePublishedFileTitle(updateHandle, "Updated Test UGC!"); remoteStorage.updatePublishedFileDescription(updateHandle, "Dummy UGC file *updated* by test application."); remoteStorage.commitPublishedFileUpdate(updateHandle); } } } else if (input.equals("ugc query")) { SteamUGCQuery query = ugc.createQueryUserUGCRequest(user.getSteamID().getAccountID(), SteamUGC.UserUGCList.Subscribed, SteamUGC.MatchingUGCType.UsableInGame, SteamUGC.UserUGCListSortOrder.TitleAsc, utils.getAppID(), utils.getAppID(), 1); if (query.isValid()) { System.out.println("sending UGC query: " + query.toString()); //ugc.setReturnTotalOnly(query, true); ugc.sendQueryUGCRequest(query); } } else if (input.startsWith("ugc download ")) { String name = input.substring("ugc download ".length()); SteamUGCHandle handle = new SteamUGCHandle(Long.parseLong(name, 16)); remoteStorage.ugcDownload(handle, 0); } else if (input.startsWith("ugc subscribe ")) { Long id = Long.parseLong(input.substring("ugc subscribe ".length()), 16); ugc.subscribeItem(new SteamPublishedFileID(id)); } else if (input.startsWith("ugc unsubscribe ")) { Long id = Long.parseLong(input.substring("ugc unsubscribe ".length()), 16); ugc.unsubscribeItem(new SteamPublishedFileID(id)); } else if (input.startsWith("ugc state ")) { Long id = Long.parseLong(input.substring("ugc state ".length()), 16); Collection<SteamUGC.ItemState> itemStates = ugc.getItemState(new SteamPublishedFileID(id)); System.out.println("UGC item states: " + itemStates.size()); for (SteamUGC.ItemState itemState : itemStates) { System.out.println(" " + itemState.name()); } } else if (input.startsWith("ugc details ")) { System.out.println("requesting UGC details (deprecated API call)"); Long id = Long.parseLong(input.substring("ugc details ".length()), 16); ugc.requestUGCDetails(new SteamPublishedFileID(id), 0); SteamUGCQuery query = ugc.createQueryUGCDetailsRequest(new SteamPublishedFileID(id)); if (query.isValid()) { System.out.println("sending UGC details query: " + query.toString()); ugc.sendQueryUGCRequest(query); } } else if (input.startsWith("ugc info ")) { Long id = Long.parseLong(input.substring("ugc info ".length()), 16); SteamUGC.ItemInstallInfo installInfo = new SteamUGC.ItemInstallInfo(); if (ugc.getItemInstallInfo(new SteamPublishedFileID(id), installInfo)) { System.out.println(" folder: " + installInfo.getFolder()); System.out.println(" size on disk: " + installInfo.getSizeOnDisk()); } SteamUGC.ItemDownloadInfo downloadInfo = new SteamUGC.ItemDownloadInfo(); if (ugc.getItemDownloadInfo(new SteamPublishedFileID(id), downloadInfo)) { System.out.println(" bytes downloaded: " + downloadInfo.getBytesDownloaded()); System.out.println(" bytes total: " + downloadInfo.getBytesTotal()); } } else if (input.startsWith("leaderboard find ")) { String name = input.substring("leaderboard find ".length()); userStats.findLeaderboard(name); } else if (input.startsWith("leaderboard list ")) { String[] params = input.substring("leaderboard list ".length()).split(" "); if (currentLeaderboard != null && params.length >= 2) { userStats.downloadLeaderboardEntries(currentLeaderboard, SteamUserStats.LeaderboardDataRequest.Global, Integer.valueOf(params[0]), Integer.valueOf(params[1])); } } else if (input.startsWith("leaderboard score ")) { String score = input.substring("leaderboard score ".length()); if (currentLeaderboard != null) { System.out.println("uploading score " + score + " to leaderboard " + currentLeaderboard.toString()); userStats.uploadLeaderboardScore(currentLeaderboard, SteamUserStats.LeaderboardUploadScoreMethod.KeepBest, Integer.valueOf(score)); } } else if (input.startsWith("apps subscribed ")) { String appId = input.substring("apps subscribed ".length()); boolean subscribed = apps.isSubscribedApp(Long.parseLong(appId)); System.out.println("user described to app #" + appId + ": " + (subscribed ? "yes" : "no")); } }
#vulnerable code @Override protected void processInput(String input) throws SteamException { if (input.equals("stats request")) { userStats.requestCurrentStats(); } else if (input.equals("stats store")) { userStats.storeStats(); } else if (input.equals("file list")) { int numFiles = remoteStorage.getFileCount(); System.out.println("Num of files: " + numFiles); for (int i = 0; i < numFiles; i++) { int[] sizes = new int[1]; String name = remoteStorage.getFileNameAndSize(i, sizes); boolean exists = remoteStorage.fileExists(name); System.out.println("# " + i + " : name=" + name + ", size=" + sizes[0] + ", exists=" + (exists ? "yes" : "no")); } } else if (input.startsWith("file write ")) { String path = input.substring("file write ".length()); File file = new File(path); try { FileInputStream in = new FileInputStream(file); SteamUGCFileWriteStreamHandle remoteFile = remoteStorage.fileWriteStreamOpen(path); if (remoteFile != null) { byte[] bytes = new byte[1024]; int bytesRead; while((bytesRead = in.read(bytes, 0, bytes.length)) > 0) { ByteBuffer buffer = ByteBuffer.allocateDirect(bytesRead); buffer.put(bytes, 0, bytesRead); remoteStorage.fileWriteStreamWriteChunk(remoteFile, buffer, buffer.limit()); } remoteStorage.fileWriteStreamClose(remoteFile); } } catch (IOException e) { e.printStackTrace(); } } else if (input.startsWith("file delete ")) { String path = input.substring("file delete ".length()); if (remoteStorage.fileDelete(path)) { System.out.println("deleted file '" + path + "'"); } } else if (input.startsWith("file share ")) { remoteStorage.fileShare(input.substring("file share ".length())); } else if (input.startsWith("file publish ")) { String[] paths = input.substring("file publish ".length()).split(" "); if (paths.length >= 2) { System.out.println("publishing file: " + paths[0] + ", preview file: " + paths[1]); remoteStorage.publishWorkshopFile(paths[0], paths[1], utils.getAppID(), "Test UGC!", "Dummy UGC file published by test application.", SteamRemoteStorage.PublishedFileVisibility.Private, null, SteamRemoteStorage.WorkshopFileType.Community); } } else if (input.startsWith("file republish ")) { String[] paths = input.substring("file republish ".length()).split(" "); if (paths.length >= 3) { System.out.println("republishing id: " + paths[0] + ", file: " + paths[1] + ", preview file: " + paths[2]); SteamPublishedFileID fileID = new SteamPublishedFileID(Long.parseLong(paths[0])); SteamPublishedFileUpdateHandle updateHandle = remoteStorage.createPublishedFileUpdateRequest(fileID); if (updateHandle != null) { remoteStorage.updatePublishedFileFile(updateHandle, paths[1]); remoteStorage.updatePublishedFilePreviewFile(updateHandle, paths[2]); remoteStorage.updatePublishedFileTitle(updateHandle, "Updated Test UGC!"); remoteStorage.updatePublishedFileDescription(updateHandle, "Dummy UGC file *updated* by test application."); remoteStorage.commitPublishedFileUpdate(updateHandle); } } } else if (input.equals("ugc query")) { SteamUGCQuery query = ugc.createQueryUserUGCRequest(user.getSteamID().getAccountID(), SteamUGC.UserUGCList.Subscribed, SteamUGC.MatchingUGCType.UsableInGame, SteamUGC.UserUGCListSortOrder.TitleAsc, utils.getAppID(), utils.getAppID(), 1); if (query.isValid()) { System.out.println("sending UGC query: " + query.toString()); //ugc.setReturnTotalOnly(query, true); ugc.sendQueryUGCRequest(query); } } else if (input.startsWith("ugc download ")) { String name = input.substring("ugc download ".length()); SteamUGCHandle handle = new SteamUGCHandle(Long.parseLong(name, 16)); remoteStorage.ugcDownload(handle, 0); } else if (input.startsWith("ugc subscribe ")) { Long id = Long.parseLong(input.substring("ugc subscribe ".length()), 16); ugc.subscribeItem(new SteamPublishedFileID(id)); } else if (input.startsWith("ugc unsubscribe ")) { Long id = Long.parseLong(input.substring("ugc unsubscribe ".length()), 16); ugc.unsubscribeItem(new SteamPublishedFileID(id)); } else if (input.startsWith("ugc state ")) { Long id = Long.parseLong(input.substring("ugc state ".length()), 16); Collection<SteamUGC.ItemState> itemStates = ugc.getItemState(new SteamPublishedFileID(id)); System.out.println("UGC item states: " + itemStates.size()); for (SteamUGC.ItemState itemState : itemStates) { System.out.println(" " + itemState.name()); } } else if (input.startsWith("ugc details ")) { System.out.println("requesting UGC details (deprecated API call)"); Long id = Long.parseLong(input.substring("ugc details ".length()), 16); ugc.requestUGCDetails(new SteamPublishedFileID(id), 0); SteamUGCQuery query = ugc.createQueryUGCDetailsRequest(new SteamPublishedFileID(id)); if (query.isValid()) { System.out.println("sending UGC details query: " + query.toString()); ugc.sendQueryUGCRequest(query); } } else if (input.startsWith("ugc info ")) { Long id = Long.parseLong(input.substring("ugc info ".length()), 16); SteamUGC.ItemInstallInfo installInfo = new SteamUGC.ItemInstallInfo(); if (ugc.getItemInstallInfo(new SteamPublishedFileID(id), installInfo)) { System.out.println(" folder: " + installInfo.getFolder()); System.out.println(" size on disk: " + installInfo.getSizeOnDisk()); } SteamUGC.ItemDownloadInfo downloadInfo = new SteamUGC.ItemDownloadInfo(); if (ugc.getItemDownloadInfo(new SteamPublishedFileID(id), downloadInfo)) { System.out.println(" bytes downloaded: " + downloadInfo.getBytesDownloaded()); System.out.println(" bytes total: " + downloadInfo.getBytesTotal()); } } else if (input.startsWith("leaderboard find ")) { String name = input.substring("leaderboard find ".length()); userStats.findLeaderboard(name); } else if (input.startsWith("leaderboard list ")) { String[] params = input.substring("leaderboard list ".length()).split(" "); if (currentLeaderboard != null && params.length >= 2) { userStats.downloadLeaderboardEntries(currentLeaderboard, SteamUserStats.LeaderboardDataRequest.Global, Integer.valueOf(params[0]), Integer.valueOf(params[1])); } } else if (input.startsWith("leaderboard score ")) { String score = input.substring("leaderboard score ".length()); if (currentLeaderboard != null) { System.out.println("uploading score " + score + " to leaderboard " + currentLeaderboard.toString()); userStats.uploadLeaderboardScore(currentLeaderboard, SteamUserStats.LeaderboardUploadScoreMethod.KeepBest, Integer.valueOf(score)); } } else if (input.startsWith("apps subscribed ")) { String appId = input.substring("apps subscribed ".length()); boolean subscribed = apps.isSubscribedApp(Long.parseLong(appId)); System.out.println("user described to app #" + appId + ": " + (subscribed ? "yes" : "no")); } } #location 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void incrementalCompile( Set<Object> drivers ) { for( Object driver: drivers ) { //noinspection unchecked Set<IFile> files = ((Collection<File>)ReflectUtil.method( driver, "getResourceFiles" ).invoke() ).stream().map( (File f) -> ManifoldHost.getFileSystem().getIFile( f ) ) .collect( Collectors.toSet() ); for( ITypeManifold tm : ManifoldHost.instance().getCurrentModule().getTypeManifolds() ) { for( IFile file: files ) { Set<String> types = Arrays.stream( tm.getTypesForFile( file ) ).collect( Collectors.toSet() ); if( types.size() > 0 ) { ReflectUtil.method( driver, "mapTypesToFile", Set.class, File.class ).invoke( types, file.toJavaFile() ); for( String fqn : types ) { // This call surfaces the type in the compiler. If compiling in "static" mode, this means // the type will be compiled to disk. IDynamicJdk.instance().getTypeElement( _tp.getContext(), (JCTree.JCCompilationUnit)_tp.getCompilationUnit(), fqn ); } } } } } }
#vulnerable code private void incrementalCompile( Set<Object> drivers ) { JavacElements elementUtils = JavacElements.instance( _tp.getContext() ); for( Object driver: drivers ) { //noinspection unchecked Set<IFile> files = ((Collection<File>)ReflectUtil.method( driver, "getResourceFiles" ).invoke() ).stream().map( (File f) -> ManifoldHost.getFileSystem().getIFile( f ) ) .collect( Collectors.toSet() ); for( ITypeManifold tm : ManifoldHost.instance().getCurrentModule().getTypeManifolds() ) { for( IFile file: files ) { Set<String> types = Arrays.stream( tm.getTypesForFile( file ) ).collect( Collectors.toSet() ); if( types.size() > 0 ) { ReflectUtil.method( driver, "mapTypesToFile", Set.class, File.class ).invoke( types, file.toJavaFile() ); for( String fqn : types ) { // This call surfaces the type in the compiler. If compiling in "static" mode, this means // the type will be compiled to disk. elementUtils.getTypeElement( fqn ); } } } } } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("WeakerAccess") public String findTopLevelFqn( String fqn ) { FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get(); if( fqnCache.isEmpty() ) { return null; } while( true ) { LocklessLazyVar<M> lazyModel = fqnCache.get( fqn ); if( lazyModel != null ) { return fqn; } int iDot = fqn.lastIndexOf( '.' ); if( iDot <= 0 ) { return null; } fqn = fqn.substring( 0, iDot ); } }
#vulnerable code @SuppressWarnings("WeakerAccess") public String findTopLevelFqn( String fqn ) { while( true ) { LocklessLazyVar<M> lazyModel = _fqnToModel.get().get( fqn ); if( lazyModel != null ) { return fqn; } int iDot = fqn.lastIndexOf( '.' ); if( iDot <= 0 ) { return null; } fqn = fqn.substring( 0, iDot ); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Collection<String> getAllTypeNames() { FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get(); if( fqnCache.isEmpty() ) { return Collections.emptySet(); } return fqnCache.getFqns(); }
#vulnerable code @Override public Collection<String> getAllTypeNames() { return _fqnToModel.get().getFqns(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static boolean hasCallHandlerMethod( Class rootClass ) { if( ICallHandler.class.isAssignableFrom( rootClass ) ) { // Nominally implements ICallHandler return true; } if( ReflectUtil.method( rootClass, "call", Class.class, String.class, String.class, Class.class, Class[].class, Object[].class ) != null ) { // Structurally implements ICallHandler return true; } // maybe has an extension satisfying ICallHandler return hasCallHandlerFromExtension( rootClass ); }
#vulnerable code private static boolean hasCallHandlerMethod( Class rootClass ) { String fqn = rootClass.getCanonicalName(); BasicJavacTask javacTask = RuntimeManifoldHost.get().getJavaParser().getJavacTask(); Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> classSymbol = ClassSymbols.instance( RuntimeManifoldHost.get().getSingleModule() ).getClassSymbol( javacTask, fqn ); Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> callHandlerSymbol = ClassSymbols.instance( RuntimeManifoldHost.get().getSingleModule() ).getClassSymbol( javacTask, ICallHandler.class.getCanonicalName() ); if( Types.instance( javacTask.getContext() ).isAssignable( classSymbol.getFirst().asType(), callHandlerSymbol.getFirst().asType() ) ) { // Nominally implements ICallHandler return true; } return hasCallMethod( javacTask, classSymbol.getFirst() ); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean isTopLevelType( String fqn ) { FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get(); if( fqnCache.isEmpty() ) { return false; } return fqnCache.get( fqn ) != null; }
#vulnerable code @Override public boolean isTopLevelType( String fqn ) { return _fqnToModel.get().get( fqn ) != null; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Tree getParent( Tree node ) { return _parents.getParent( node ); }
#vulnerable code public Tree getParent( Tree node ) { TreePath2 path = TreePath2.getPath( getCompilationUnit(), node ); if( path == null ) { // null is indiciative of Generation phase where trees are no longer attached to symobls so the comp unit is detached // use the root tree instead, which is mostly ok, mostly path = TreePath2.getPath( _tree, node ); } TreePath2 parentPath = path.getParentPath(); return parentPath == null ? null : parentPath.getLeaf(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Rune getDataRune(int id) throws RiotApiException { return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, (RuneData) null); }
#vulnerable code public Rune getDataRune(int id) throws RiotApiException { return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, (ChampData) null); }
#vulnerable code public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ItemList getDataItemList(Region region) throws RiotApiException { return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, (ItemListData) null); }
#vulnerable code public ItemList getDataItemList(Region region) throws RiotApiException { return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ChampionList getDataChampionList(Region region) throws RiotApiException { return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, (ChampData) null); }
#vulnerable code public ChampionList getDataChampionList(Region region) throws RiotApiException { return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Rune getDataRune(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, (RuneData) null); }
#vulnerable code public Rune getDataRune(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean cancel() { synchronized (signal) { boolean cancelled = super.cancel(); if (!cancelled) { return false; } signal.notifyAll(); // Try to force-quit the connection if (connection != null) { setTimeout(1); connection.disconnect(); } } return true; }
#vulnerable code @Override public boolean cancel() { boolean cancelled = super.cancel(); if (!cancelled) { return false; } synchronized (signal) { signal.notifyAll(); } // Try to force-quit the connection if (connection != null) { setTimeout(1); connection.disconnect(); } return true; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void await(long timeout, TimeUnit unit, boolean cancelOnTimeout) throws InterruptedException, TimeoutException { final long end = System.currentTimeMillis() + unit.toMillis(timeout); if (!isDone() && System.currentTimeMillis() < end) { synchronized (signal) { while (!isDone() && System.currentTimeMillis() < end) { signal.wait(end - System.currentTimeMillis()); } } } if (!isDone()) { if (cancelOnTimeout) { cancel(); } throw new TimeoutException(); } }
#vulnerable code public void await(long timeout, TimeUnit unit, boolean cancelOnTimeout) throws InterruptedException, TimeoutException { final long end = System.currentTimeMillis() + unit.toMillis(timeout); while (!isDone() && System.currentTimeMillis() < end) { synchronized (signal) { signal.wait(end - System.currentTimeMillis()); } } if (!isDone()) { if (cancelOnTimeout) { cancel(); } throw new TimeoutException(); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RuneList getDataRuneList() throws RiotApiException { return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, (RuneListData) null); }
#vulnerable code public RuneList getDataRuneList() throws RiotApiException { return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, (SpellData) null); }
#vulnerable code public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean cancel() { synchronized (signal) { boolean cancelled = super.cancel(); if (!cancelled) { return false; } signal.notifyAll(); // Try to force-quit the connection if (connection != null) { setTimeout(1); connection.disconnect(); } } return true; }
#vulnerable code @Override public boolean cancel() { boolean cancelled = super.cancel(); if (!cancelled) { return false; } synchronized (signal) { signal.notifyAll(); } // Try to force-quit the connection if (connection != null) { setTimeout(1); connection.disconnect(); } return true; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public MasteryList getDataMasteryList(Region region) throws RiotApiException { return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, (MasteryListData) null); }
#vulnerable code public MasteryList getDataMasteryList(Region region) throws RiotApiException { return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void init(ApiConfig config, ApiMethod method) { this.config = config; this.method = method; }
#vulnerable code protected void init(ApiConfig config, ApiMethod method) { this.config = config; this.method = method; setTimeout(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T> T getDto(Class<T> desiredDto) throws RiotApiException, RateLimitException { requireSucceededRequestState(); if (responseCode == CODE_SUCCESS_NOCONTENT) { // The Riot Api is fine with the request, and explicitly sends no content return null; } T dto = null; try { dto = new Gson().fromJson(responseBody, desiredDto); } catch (JsonSyntaxException e) { throw new RiotApiException(RiotApiException.PARSE_FAILURE); } if (dto == null) { throw new RiotApiException(RiotApiException.PARSE_FAILURE); } return dto; }
#vulnerable code public <T> T getDto(Class<T> desiredDto) throws RiotApiException, RateLimitException { if (!response.isSuccessful()) { // I think we can never get here. Let's make sure though throw new RiotApiException(RiotApiException.IOEXCEPTION); } if (response.getCode() == RequestResponse.CODE_SUCCESS_NOCONTENT) { // The Riot Api is fine with the request, and explicitly sends no content return null; } T dto = null; try { dto = new Gson().fromJson(response.getBody(), desiredDto); } catch (JsonSyntaxException e) { throw new RiotApiException(RiotApiException.PARSE_FAILURE); } if (dto == null) { throw new RiotApiException(RiotApiException.PARSE_FAILURE); } return dto; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Item getDataItem(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, (ItemData) null); }
#vulnerable code public Item getDataItem(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int getResponseCode() { requireSucceededRequestState(); return responseCode; }
#vulnerable code public int getResponseCode() { if (response == null) { throw new IllegalStateException("The request must first be executed"); } return response.getCode(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public MasteryList getDataMasteryList() throws RiotApiException { return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, (MasteryListData) null); }
#vulnerable code public MasteryList getDataMasteryList() throws RiotApiException { return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testJoinString() throws RiotApiException { // Valid Usage for Strings assertEquals("abc", Convert.joinString(",", "abc")); assertEquals("abc,def,ghi", Convert.joinString(",", "abc", "def", "ghi")); // Valid Usage for other objects assertEquals("RANKED_SOLO_5x5,TEAM_BUILDER_DRAFT_RANKED_5x5", Convert.joinString(",", QueueType.RANKED_SOLO_5x5, QueueType.TEAM_BUILDER_DRAFT_RANKED_5x5)); assertEquals("info,lore", Convert.joinString(",", ChampData.INFO, ChampData.LORE)); // NullPointerException thrown.expect(NullPointerException.class); Convert.joinString(null, (CharSequence[]) null); }
#vulnerable code @Test public void testJoinString() throws RiotApiException { // Valid Usage assertEquals("abc", Convert.joinString(",", "abc")); assertEquals("abc,def,ghi", Convert.joinString(",", "abc", "def", "ghi")); // NullPointerException thrown.expect(NullPointerException.class); Convert.joinString(null, (CharSequence[]) null); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RuneList getDataRuneList(Region region) throws RiotApiException { return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, (RuneListData) null); }
#vulnerable code public RuneList getDataRuneList(Region region) throws RiotApiException { return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected boolean setState(RequestState state) { boolean success = super.setState(state); if (!success) { return false; } if (!listeners.isEmpty()) { if (state == RequestState.Succeeded) { for (RequestListener listener : listeners) { listener.onRequestSucceeded(this); } } else if (state == RequestState.Failed) { for (RequestListener listener : listeners) { listener.onRequestFailed(getException()); } } else if (state == RequestState.TimeOut) { for (RequestListener listener : listeners) { listener.onRequestTimeout(this); } } } if (state == RequestState.Succeeded || state == RequestState.Failed || state == RequestState.TimeOut) { synchronized (signal) { signal.notifyAll(); } } return true; }
#vulnerable code @Override protected boolean setState(RequestState state) { boolean success = super.setState(state); if (!success) { return false; } if (listener != null) { if (state == RequestState.Succeeded) { listener.onRequestSucceeded(this); } else if (state == RequestState.Failed) { listener.onRequestFailed(getException()); } else if (state == RequestState.TimeOut) { listener.onRequestTimeout(this); } } if (state == RequestState.Succeeded || state == RequestState.Failed || state == RequestState.TimeOut) { synchronized (signal) { signal.notifyAll(); } } return true; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, (SpellData) null); }
#vulnerable code public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Mastery getDataMastery(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, (MasteryData) null); }
#vulnerable code public Mastery getDataMastery(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, (SpellData) null); }
#vulnerable code public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ChampionList getDataChampionList() throws RiotApiException { return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, (ChampData) null); }
#vulnerable code public ChampionList getDataChampionList() throws RiotApiException { return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for(int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int)c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5*3); outBuf.append(in,0,i); try { formatter = new Formatter(outBuf); } finally { if (formatter != null) { formatter.flush(); formatter.close(); } } } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X",(int)c);//TODO } } return outBuf != null ? outBuf : in; }
#vulnerable code protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for(int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int)c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5*3); outBuf.append(in,0,i); formatter = new Formatter(outBuf); } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X",(int)c);//TODO } } return outBuf != null ? outBuf : in; } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void changeRole(Role new_role) { final RaftImpl new_impl=new_role == Role.Follower? new Follower(this) : new_role == Role.Candidate? new Candidate(this) : new Leader(this); withLockDo(impl_lock, new Callable<Void>() { public Void call() throws Exception { if(!impl.getClass().equals(new_impl.getClass())) { impl.destroy(); new_impl.init(); impl=new_impl; } return null; } }); }
#vulnerable code protected void changeRole(Role new_role) { RaftImpl new_impl=null; switch(new_role) { case Follower: new_impl=new Follower(this); break; case Candidate: new_impl=new Follower(this); break; case Leader: new_impl=new Leader(this); break; } impl_lock.lock(); try { if(!impl.getClass().equals(new_impl.getClass())) { impl.destroy(); new_impl.init(); impl=new_impl; } } finally { impl_lock.unlock(); } } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String readResource(final String name) { final StringBuilder ret = new StringBuilder(); InputStream is = null; InputStreamReader reader = null; try { is = UrlRegularExpressions.class.getClassLoader().getResourceAsStream(name); reader = new InputStreamReader(is, ASCII); int read = 0; final char[] buf = new char[1024]; do { read = reader.read(buf, 0, buf.length); if (read > 0) { ret.append(buf, 0, read); } } while (read >= 0); } catch (final IOException ex) { throw new RuntimeException(ex); } finally { closeQuietly(is); closeQuietly(reader); } return ret.toString(); }
#vulnerable code private static String readResource(final String name) { final StringBuilder ret = new StringBuilder(); InputStream is = null; try { is = UrlRegularExpressions.class.getClassLoader().getResourceAsStream(name); final InputStreamReader reader = new InputStreamReader(is, ASCII); int read = 0; final char[] buf = new char[1024]; do { read = reader.read(buf, 0, buf.length); if (read > 0) { ret.append(buf, 0, read); } } while (read >= 0); } catch (final IOException ex) { throw new RuntimeException(ex); } finally { closeQuietly(is); } return ret.toString(); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ClassName get(Class<?> clazz) { checkNotNull(clazz, "clazz == null"); checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName"); checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName"); checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName"); String anonymousSuffix = ""; while (clazz.isAnonymousClass()) { int lastDollar = clazz.getName().lastIndexOf('$'); anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix; clazz = clazz.getEnclosingClass(); } String name = clazz.getSimpleName() + anonymousSuffix; if (clazz.getEnclosingClass() == null) { // Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295 int lastDot = clazz.getName().lastIndexOf('.'); String packageName = (lastDot != -1) ? clazz.getName().substring(0, lastDot) : NO_PACKAGE; return new ClassName(packageName, null, name); } return ClassName.get(clazz.getEnclosingClass()).nestedClass(name); }
#vulnerable code public static ClassName get(Class<?> clazz) { checkNotNull(clazz, "clazz == null"); checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName"); checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName"); checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName"); String anonymousSuffix = ""; while (clazz.isAnonymousClass()) { int lastDollar = clazz.getName().lastIndexOf('$'); anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix; clazz = clazz.getEnclosingClass(); } String name = clazz.getSimpleName() + anonymousSuffix; if (clazz.getEnclosingClass() == null) { // Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295 int lastDot = clazz.getName().lastIndexOf('.'); String packageName = (lastDot != -1) ? clazz.getName().substring(0, lastDot) : null; return new ClassName(packageName, null, name); } return ClassName.get(clazz.getEnclosingClass()).nestedClass(name); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void populateJMeterDirectoryTree() throws MojoExecutionException { for (Artifact artifact : pluginArtifacts) { try { if (artifact.getArtifactId().startsWith("ApacheJMeter_")) { if (artifact.getArtifactId().startsWith("ApacheJMeter_config")) { JarFile configSettings = new JarFile(artifact.getFile()); Enumeration<JarEntry> entries = configSettings.entries(); while (entries.hasMoreElements()) { JarEntry jarFileEntry = entries.nextElement(); // Only interested in files in the /bin directory that are not properties files if (jarFileEntry.getName().startsWith("bin") && !jarFileEntry.getName().endsWith(".properties")) { if (!jarFileEntry.isDirectory()) { copyInputStreamToFile(configSettings.getInputStream(jarFileEntry), new File(workDir.getCanonicalPath() + File.separator + jarFileEntry.getName())); } } } configSettings.close(); } else { copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName())); } } else { /** * TODO: exclude jars that maven put in #pluginArtifacts for maven run? (e.g. plexus jars, the plugin artifact itself) * Need more info on above, how do we know which ones to exclude?? * Most of the files pulled down by maven are required in /lib to match standard JMeter install */ if (Artifact.SCOPE_RUNTIME.equals(artifact.getScope())) { copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName())); } else { copyFile(artifact.getFile(), new File(libDir + File.separator + artifact.getFile().getName())); } } } catch (IOException e) { throw new MojoExecutionException("Unable to populate the JMeter directory tree: " + e); } } //TODO Check if we really need to do this //empty classpath, JMeter will automatically assemble and add all JARs in #libDir and #libExtDir and add them to the classpath. Otherwise all jars will be in the classpath twice. System.setProperty("java.class.path", ""); }
#vulnerable code protected void populateJMeterDirectoryTree() throws MojoExecutionException { for (Artifact artifact : pluginArtifacts) { try { if (artifact.getArtifactId().startsWith("ApacheJMeter_")) { if (artifact.getArtifactId().startsWith("ApacheJMeter_config")) { JarFile configSettings = new JarFile(artifact.getFile()); Enumeration<JarEntry> entries = configSettings.entries(); while (entries.hasMoreElements()) { JarEntry jarFileEntry = entries.nextElement(); // Only interested in files in the /bin directory that are not properties files if (jarFileEntry.getName().startsWith("bin") && !jarFileEntry.getName().endsWith(".properties")) { if (!jarFileEntry.isDirectory()) { InputStream is = configSettings.getInputStream(jarFileEntry); // get the input stream OutputStream os = new FileOutputStream(new File(workDir.getCanonicalPath() + File.separator + jarFileEntry.getName())); while (is.available() > 0) { os.write(is.read()); } os.close(); is.close(); } } } configSettings.close(); } else { FileUtils.copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName())); } } else { /** * TODO: exclude jars that maven put in #pluginArtifacts for maven run? (e.g. plexus jars, the plugin artifact itself) * Need more info on above, how do we know which ones to exclude?? * Most of the files pulled down by maven are required in /lib to match standard JMeter install */ if (Artifact.SCOPE_RUNTIME.equals(artifact.getScope())) { FileUtils.copyFile(artifact.getFile(), new File(libExtDir + File.separator + artifact.getFile().getName())); } else { FileUtils.copyFile(artifact.getFile(), new File(libDir + File.separator + artifact.getFile().getName())); } } } catch (IOException e) { throw new MojoExecutionException("Unable to populate the JMeter directory tree: " + e); } } //TODO Check if we really need to do this //empty classpath, JMeter will automatically assemble and add all JARs in #libDir and #libExtDir and add them to the classpath. Otherwise all jars will be in the classpath twice. System.setProperty("java.class.path", ""); } #location 39 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int blockSize() { return blockSize; }
#vulnerable code @Override public int blockSize() { return BLOCK_SIZE; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static void setBlockSize(int blockSize) { synchronized (BlocksPool.class) { // can be easily changed to lock-free instance = new BlocksPool(blockSize); } }
#vulnerable code static void setBlockSize(int blockSize) { BLOCK_SIZE = blockSize; synchronized (BlocksPool.class) { // can be easily changed to lock-free instance = new BlocksPool(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code InternalOakMap(K minKey, OakSerializer<K> keySerializer, OakSerializer<V> valueSerializer, OakComparator<K> oakComparator, MemoryManager memoryManager, int chunkMaxItems) { this.size = new AtomicInteger(0); this.memoryManager = memoryManager; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; this.comparator = oakComparator; this.minKey = ByteBuffer.allocate(this.keySerializer.calculateSize(minKey)); this.minKey.position(0); this.keySerializer.serialize(minKey, this.minKey); // This is a trick for letting us search through the skiplist using both serialized and unserialized keys. // Might be nicer to replace it with a proper visitor Comparator<Object> mixedKeyComparator = (o1, o2) -> { if (o1 instanceof ByteBuffer) { if (o2 instanceof ByteBuffer) { return oakComparator.compareSerializedKeys((ByteBuffer) o1, (ByteBuffer) o2); } else { // Note the inversion of arguments, hence sign flip return (-1) * oakComparator.compareKeyAndSerializedKey((K) o2, (ByteBuffer) o1); } } else { if (o2 instanceof ByteBuffer) { return oakComparator.compareKeyAndSerializedKey((K) o1, (ByteBuffer) o2); } else { return oakComparator.compareKeys((K) o1, (K) o2); } } }; this.skiplist = new ConcurrentSkipListMap<>(mixedKeyComparator); Chunk<K, V> head = new Chunk<>(this.minKey, null, this.comparator, memoryManager, chunkMaxItems, this.size, keySerializer, valueSerializer); this.skiplist.put(head.minKey, head); // add first chunk (head) into skiplist this.head = new AtomicReference<>(head); }
#vulnerable code Result<V> putIfAbsent(K key, V value, Function<ByteBuffer, V> transformer) { if (key == null || value == null) { throw new NullPointerException(); } Chunk<K, V> c = findChunk(key); // find chunk matching key Chunk.LookUp lookUp = c.lookUp(key); if (lookUp != null && lookUp.valueSlice != null) { if (transformer == null) { return Result.withFlag(false); } AbstractMap.SimpleEntry<ValueUtils.ValueResult, V> res = ValueUtils.transform(lookUp.valueSlice, transformer); if (res.getKey() == SUCCESS) { return Result.withValue(res.getValue()); } return putIfAbsent(key, value, transformer); } // if chunk is frozen or infant, we can't add to it // we need to help rebalancer first, then proceed Chunk.State state = c.state(); if (state == Chunk.State.INFANT) { // the infant is already connected so rebalancer won't add this put rebalance(c.creator()); return putIfAbsent(key, value, transformer); } if (state == Chunk.State.FROZEN || state == Chunk.State.RELEASED) { rebalance(c); return putIfAbsent(key, value, transformer); } int ei; long oldReference = DELETED_VALUE; // Is there already an entry associated with this key? if (lookUp != null) { // There's an entry for this key, but it isn't linked to any value (in which case valueReference is // DELETED_VALUE) // or it's linked to a deleted value that is referenced by valueReference (a valid one) ei = lookUp.entryIndex; assert ei > 0; oldReference = lookUp.valueReference; } else { ei = c.allocateEntryAndKey(key); if (ei == -1) { rebalance(c); return putIfAbsent(key, value, transformer); } int prevEi = c.linkEntry(ei, key); if (prevEi != ei) { // some other thread linked its entry with the same key. oldReference = c.getValueReference(prevEi); if (oldReference != DELETED_VALUE) { if (transformer == null) { return Result.withFlag(false); } AbstractMap.SimpleEntry<ValueUtils.ValueResult, V> res = ValueUtils.transform(c.buildValueSlice(oldReference), transformer); if (res.getKey() == SUCCESS) { return Result.withValue(res.getValue()); } return putIfAbsent(key, value, transformer); } else { // both threads compete for the put ei = prevEi; } } } long newValueReference = c.writeValue(value); // write value in place Chunk.OpData opData = new Chunk.OpData(Operation.PUT_IF_ABSENT, ei, newValueReference, oldReference, null); // publish put if (!c.publish()) { c.releaseValue(newValueReference); rebalance(c); return putIfAbsent(key, value, transformer); } if (!finishAfterPublishing(opData, c)) { c.releaseValue(newValueReference); return putIfAbsent(key, value, transformer); } return transformer != null ? Result.withValue(null) : Result.withFlag(true); } #location 83 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testUnsafeCopy() { IntHolder minKey = new IntHolder(0, new int[0]); OakMapBuilder<IntHolder, IntHolder> builder = new OakMapBuilder<IntHolder, IntHolder>( new UnsafeTestComparator(), new UnsafeTestSerializer(),new UnsafeTestSerializer(), minKey); OakMap<IntHolder, IntHolder> oak = builder.build(); IntHolder key1 = new IntHolder(5, new int[]{1, 2, 3, 4, 5}); IntHolder value1 = new IntHolder(5, new int[]{1, 2, 3, 4, 5}); IntHolder key2 = new IntHolder(6, new int[]{10, 20, 30, 40, 50, 60}); IntHolder value2 = new IntHolder(6, new int[]{10, 20, 30, 40, 50, 60}); oak.put(key1, value1); oak.put(key2, value2); IntHolder resValue1 = oak.get(key1); assertEquals(value1.size, resValue1.size); for (int i = 0; i < value1.size; ++i) { assertEquals(value1.array[i], resValue1.array[i]); } IntHolder resValue2 = oak.get(key2); assertEquals(value2.size, resValue2.size); for (int i = 0; i < value2.size; ++i) { assertEquals(value2.array[i], resValue2.array[i]); } Iterator<Map.Entry<OakRBuffer, OakRBuffer>> iter = oak.zc().entrySet().iterator(); while (iter.hasNext()) { Map.Entry<OakRBuffer, OakRBuffer> entry = iter.next(); int size = entry.getKey().getInt(0); int[] dstArrayValue = new int[size]; int[] dstArrayKey = new int[size]; entry.getKey().unsafeCopyBufferToIntArray(Integer.BYTES, dstArrayKey, size); entry.getValue().unsafeCopyBufferToIntArray(Integer.BYTES, dstArrayValue, size); if (size == 5) { //value1 assertArrayEquals(value1.array, dstArrayKey); assertArrayEquals(value1.array, dstArrayValue); } else if (size == 6) { //value2 assertArrayEquals(value2.array, dstArrayKey); assertArrayEquals(value2.array, dstArrayValue); } else { fail(); } } }
#vulnerable code @Test public void testUnsafeCopy() { IntHolder minKey = new IntHolder(0, new int[0]); OakMapBuilder<IntHolder, IntHolder> builder = new OakMapBuilder<IntHolder, IntHolder>( new UnsafeTestComparator(),new UnsafeTestSerializer(),new UnsafeTestSerializer()) .setMinKey(minKey) ; OakMap<IntHolder, IntHolder> oak = builder.build(); IntHolder key1 = new IntHolder(5, new int[]{1, 2, 3, 4, 5}); IntHolder value1 = new IntHolder(5, new int[]{1, 2, 3, 4, 5}); IntHolder key2 = new IntHolder(6, new int[]{10, 20, 30, 40, 50, 60}); IntHolder value2 = new IntHolder(6, new int[]{10, 20, 30, 40, 50, 60}); oak.put(key1, value1); oak.put(key2, value2); IntHolder resValue1 = oak.get(key1); assertEquals(value1.size, resValue1.size); for (int i = 0; i < value1.size; ++i) { assertEquals(value1.array[i], resValue1.array[i]); } IntHolder resValue2 = oak.get(key2); assertEquals(value2.size, resValue2.size); for (int i = 0; i < value2.size; ++i) { assertEquals(value2.array[i], resValue2.array[i]); } Iterator<Map.Entry<OakRBuffer, OakRBuffer>> iter = oak.zc().entrySet().iterator(); while (iter.hasNext()) { Map.Entry<OakRBuffer, OakRBuffer> entry = iter.next(); int size = entry.getKey().getInt(0); int[] dstArrayValue = new int[size]; int[] dstArrayKey = new int[size]; entry.getKey().unsafeCopyBufferToIntArray(Integer.BYTES, dstArrayKey, size); entry.getValue().unsafeCopyBufferToIntArray(Integer.BYTES, dstArrayValue, size); if (size == 5) { //value1 assertArrayEquals(value1.array, dstArrayKey); assertArrayEquals(value1.array, dstArrayValue); } else if (size == 6) { //value2 assertArrayEquals(value2.array, dstArrayKey); assertArrayEquals(value2.array, dstArrayValue); } else { fail(); } } } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code XSSFUnmarshaller(PoijiOptions options) { this.options = options; }
#vulnerable code <T> void unmarshal0(Class<T> type, Consumer<? super T> consumer, OPCPackage open) throws IOException, SAXException, OpenXML4JException { //ISSUE #55 XSSFWorkbook wb = new XSSFWorkbook(open); Workbook workbook = new SXSSFWorkbook(wb); //work out which sheet must process int processIndex = PoijiOptions.getSheetIndexToProcess(workbook, options); ReadOnlySharedStringsTable readOnlySharedStringsTable = new ReadOnlySharedStringsTable(open); XSSFReader xssfReader = new XSSFReader(open); StylesTable styles = xssfReader.getStylesTable(); SheetIterator iter = (SheetIterator) xssfReader.getSheetsData(); int index = 0; while (iter.hasNext()) { try (InputStream stream = iter.next()) { //if (index == options.sheetIndex()) { if (index == processIndex) { processSheet(styles, readOnlySharedStringsTable, type, stream, consumer); return; } } ++index; } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ZipInputStream createZipInputStream(ZipModel zipModel, FileHeader fileHeader, char[] password) throws IOException { SplitInputStream splitInputStream = null; try { splitInputStream = new SplitInputStream(zipModel.getZipFile(), zipModel.isSplitArchive(), zipModel.getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); ZipInputStream zipInputStream = new ZipInputStream(splitInputStream, password); if (zipInputStream.getNextEntry(fileHeader) == null) { throw new ZipException("Could not locate local file header for corresponding file header"); } return zipInputStream; } catch (IOException e) { if (splitInputStream != null) { splitInputStream.close(); } throw e; } }
#vulnerable code public static ZipInputStream createZipInputStream(ZipModel zipModel, FileHeader fileHeader, char[] password) throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(zipModel.getZipFile(), zipModel.isSplitArchive(), zipModel.getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); ZipInputStream zipInputStream = new ZipInputStream(splitInputStream, password); if (zipInputStream.getNextEntry(fileHeader) == null) { throw new ZipException("Could not locate local file header for corresponding file header"); } return zipInputStream; } catch (IOException e) { throw new ZipException(e); } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private ZipInputStream prepareZipInputStream() throws ZipException { try { splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } }
#vulnerable code private ZipInputStream prepareZipInputStream() throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private ZipInputStream prepareZipInputStream() throws ZipException { try { splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } }
#vulnerable code private ZipInputStream prepareZipInputStream() throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private ZipInputStream prepareZipInputStream() throws ZipException { try { splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } }
#vulnerable code private ZipInputStream prepareZipInputStream() throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); FileHeader fileHeader = getFirstFileHeader(getZipModel()); if (fileHeader != null) { splitInputStream.prepareExtractionForFileHeader(fileHeader); } return new ZipInputStream(splitInputStream, password); } catch (IOException e) { throw new ZipException(e); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ZipInputStream createZipInputStream(ZipModel zipModel, FileHeader fileHeader, char[] password) throws IOException { SplitInputStream splitInputStream = null; try { splitInputStream = new SplitInputStream(zipModel.getZipFile(), zipModel.isSplitArchive(), zipModel.getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); ZipInputStream zipInputStream = new ZipInputStream(splitInputStream, password); if (zipInputStream.getNextEntry(fileHeader) == null) { throw new ZipException("Could not locate local file header for corresponding file header"); } return zipInputStream; } catch (IOException e) { if (splitInputStream != null) { splitInputStream.close(); } throw e; } }
#vulnerable code public static ZipInputStream createZipInputStream(ZipModel zipModel, FileHeader fileHeader, char[] password) throws ZipException { try { SplitInputStream splitInputStream = new SplitInputStream(zipModel.getZipFile(), zipModel.isSplitArchive(), zipModel.getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); ZipInputStream zipInputStream = new ZipInputStream(splitInputStream, password); if (zipInputStream.getNextEntry(fileHeader) == null) { throw new ZipException("Could not locate local file header for corresponding file header"); } return zipInputStream; } catch (IOException e) { throw new ZipException(e); } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setFileAttributes(Path file, byte[] fileAttributes) { if (fileAttributes == null || fileAttributes.length == 0) { return; } if (isWindows()) { applyWindowsFileAttributes(file, fileAttributes); } else if (isMac() || isUnix()) { applyPosixFileAttributes(file, fileAttributes); } }
#vulnerable code public static void setFileAttributes(Path file, byte[] fileAttributes) { if (fileAttributes == null || fileAttributes.length == 0) { return; } String os = System.getProperty("os.name").toLowerCase(); if (isWindows(os)) { applyWindowsFileAttributes(file, fileAttributes); } else if (isMac(os) || isUnix(os)) { applyPosixFileAttributes(file, fileAttributes); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected ZipInputStream createZipInputStream(FileHeader fileHeader) throws IOException { splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); return new ZipInputStream(splitInputStream, password); }
#vulnerable code protected ZipInputStream createZipInputStream(FileHeader fileHeader) throws IOException { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); return new ZipInputStream(splitInputStream, password); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void clientToServerBackpressure() throws InterruptedException { ReactorNumbersGrpc.ReactorNumbersStub stub = ReactorNumbersGrpc.newReactorStub(channel); Flux<NumberProto.Number> reactorRequest = Flux .fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator) .doOnNext(i -> System.out.println(i + " --> ")) .doOnNext(i -> updateNumberOfWaits(lastValueTime, numberOfWaits)) .map(BackpressureIntegrationTest::protoNum); Mono<NumberProto.Number> reactorResponse = stub.requestPressure(reactorRequest); StepVerifier.create(reactorResponse) .expectNextMatches(v -> v.getNumber(0) == NUMBER_OF_STREAM_ELEMENTS - 1) .expectComplete() .verify(Duration.ofSeconds(5)); assertThat(numberOfWaits.get()).isEqualTo(1); }
#vulnerable code @Test public void clientToServerBackpressure() throws InterruptedException { Object lock = new Object(); ReactorNumbersGrpc.ReactorNumbersStub stub = ReactorNumbersGrpc.newReactorStub(channel); BackpressureDetector clientBackpressureDetector = new BackpressureDetector(madMultipleCutoff); Sequence seq = new Sequence(200, clientBackpressureDetector); Flux<NumberProto.Number> reactorRequest = Flux .fromIterable(seq) .doOnNext(i -> System.out.println(i + " -->")) .map(BackpressureIntegrationTest::protoNum); Mono<NumberProto.Number> reactorResponse = stub.requestPressure(reactorRequest); reactorResponse.subscribe( n -> { System.out.println("Client done. " + n.getNumber(0)); synchronized (lock) { lock.notify(); } }, t -> { t.printStackTrace(); synchronized (lock) { lock.notify(); } }); synchronized (lock) { lock.wait(TimeUnit.SECONDS.toMillis(20)); } assertThat(clientBackpressureDetector.backpressureDelayOcurred()).isTrue(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void serverToClientBackpressure() throws InterruptedException { RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Single<Empty> rxRequest = Single.just(Empty.getDefaultInstance()); TestSubscriber<NumberProto.Number> rxResponse = stub.responsePressure(rxRequest) .doOnNext(n -> System.out.println(n.getNumber(0) + " <--")) .doOnNext(n -> waitIfValuesAreEqual(n.getNumber(0), 3)) .test(); rxResponse.awaitTerminalEvent(5, TimeUnit.SECONDS); rxResponse.assertComplete() .assertValueCount(NUMBER_OF_STREAM_ELEMENTS); assertThat(serverNumberOfWaits.get()).isEqualTo(1); }
#vulnerable code @Test public void serverToClientBackpressure() throws InterruptedException { Object lock = new Object(); BackpressureDetector clientBackpressureDetector = new BackpressureDetector(madMultipleCutoff); RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Single<Empty> rxRequest = Single.just(Empty.getDefaultInstance()); Flowable<NumberProto.Number> rxResponse = stub.responsePressure(rxRequest); rxResponse.subscribe( n -> { clientBackpressureDetector.tick(); System.out.println(n.getNumber(0) + " <--"); try { Thread.sleep(50); } catch (InterruptedException e) {} }, t -> { t.printStackTrace(); synchronized (lock) { lock.notify(); } }, () -> { System.out.println("Client done."); synchronized (lock) { lock.notify(); } }); synchronized (lock) { lock.wait(TimeUnit.SECONDS.toMillis(20)); } assertThat(serverRespBPDetector.backpressureDelayOcurred()).isTrue(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { final Set<String> artifacts = new HashSet<>(); installNodeModules(artifacts); final File base = new File(cwd, "node_modules"); final File libs = new File(base, ".lib"); if (force || libs.exists()) { final double version = Double.parseDouble(System.getProperty("java.specification.version")); final String vm = System.getProperty("java.vm.name"); // from graal 20.0.0 the vm name doesn't contain graalvm in the name // but it is now part of the vendor version final String vendor = System.getProperty("java.vendor.version"); if (!vm.toLowerCase().contains("graalvm") && vendor != null && !vendor.toLowerCase().contains("graalvm")) { // not on graal, install graaljs and dependencies warn("Installing GraalJS..."); // graaljs + dependencies installGraalJS(artifacts); if (version >= 11) { // verify if the current JDK contains the jdk.internal.vm.ci module try { String modules = exec(javaHomePrefix() + "java", "--list-modules"); if (modules.contains("jdk.internal.vm.ci")) { warn("Installing JVMCI Compiler..."); // jvmci compiler + dependencies installGraalJMVCICompiler(); } } catch (IOException | InterruptedException e) { err(e.getMessage()); } } else { warn("Current JDK only supports GraalJS in Interpreted mode!"); } } } // always create a launcher even if no dependencies are needed createLauncher(artifacts); // always install the es4x type definitions installTypeDefinitions(); }
#vulnerable code @Override public void run() { final Set<String> artifacts = new HashSet<>(); installNodeModules(artifacts); final File base = new File(cwd, "node_modules"); final File libs = new File(base, ".lib"); if (force || libs.exists()) { final double version = Double.parseDouble(System.getProperty("java.specification.version")); final String vm = System.getProperty("java.vm.name"); // from graal 20.0.0 the vm name doesn't contain graalvm in the name // but it is now part of the vendor version final String vendor = System.getProperty("java.vendor.version"); if (!vm.toLowerCase().contains("graalvm") || !vendor.toLowerCase().contains("graalvm")) { // not on graal, install graaljs and dependencies warn("Installing GraalJS..."); // graaljs + dependencies installGraalJS(artifacts); if (version >= 11) { // verify if the current JDK contains the jdk.internal.vm.ci module try { String modules = exec(javaHomePrefix() + "java", "--list-modules"); if (modules.contains("jdk.internal.vm.ci")) { warn("Installing JVMCI Compiler..."); // jvmci compiler + dependencies installGraalJMVCICompiler(); } } catch (IOException | InterruptedException e) { err(e.getMessage()); } } else { warn("Current JDK only supports GraalJS in Interpreted mode!"); } } } // always create a launcher even if no dependencies are needed createLauncher(artifacts); // always install the es4x type definitions installTypeDefinitions(); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String injectVersion(String resourcePath) { String version = getResourceVersion(resourcePath); if (StringUtils.isNullOrEmpty(version)) { // unversioned, pass-through resource path return resourcePath; } // check for extension int extensionAt = resourcePath.lastIndexOf('.'); StringBuilder versionedResourcePath = new StringBuilder(); if (extensionAt == -1) { versionedResourcePath.append(resourcePath); versionedResourcePath.append("-ver-").append(version); } else { versionedResourcePath.append(resourcePath.substring(0, extensionAt)); versionedResourcePath.append("-ver-").append(version); versionedResourcePath.append(resourcePath.substring(extensionAt, resourcePath.length())); } log.trace("Inject version in resource path: '{}' => '{}'", resourcePath, versionedResourcePath); return versionedResourcePath.toString(); }
#vulnerable code public String injectVersion(String resourcePath) { URL resourceUrl = getResourceUrl(resourcePath); try { long lastModified = resourceUrl.openConnection().getLastModified(); // check for extension int extensionAt = resourcePath.lastIndexOf('.'); StringBuilder versionedResourcePath = new StringBuilder(); if (extensionAt == -1) { versionedResourcePath.append(resourcePath); versionedResourcePath.append("-ver-").append(lastModified); } else { versionedResourcePath.append(resourcePath.substring(0, extensionAt)); versionedResourcePath.append("-ver-").append(lastModified); versionedResourcePath.append(resourcePath.substring(extensionAt, resourcePath.length())); } log.trace("Inject version in resource path: '{}' => '{}'", resourcePath, versionedResourcePath); return versionedResourcePath.toString(); } catch (IOException e) { throw new PippoRuntimeException("Failed to read lastModified property for {}", e, resourceUrl); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @BeforeClass public static void setUpClass() throws IOException { MemcachedStarter runtime = MemcachedStarter.getDefaultInstance(); memcachedExe = runtime.prepare( new MemcachedConfig(Version.Main.PRODUCTION, PORT)); memcached = memcachedExe.start(); client = new XMemcachedClient(new InetSocketAddress(HOST, PORT)); }
#vulnerable code @BeforeClass public static void setUpClass() { application = new Application(); client = XmemcachedFactory.create(application.getPippoSettings()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public TemplateEngine getTemplateEngine() { return templateEngine; }
#vulnerable code public TemplateEngine getTemplateEngine() { if (templateEngine == null) { TemplateEngine engine = ServiceLocator.locate(TemplateEngine.class); setTemplateEngine(engine); } return templateEngine; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void classpathResourceHandlerTest() throws URISyntaxException { ClasspathResourceHandler handler = new ClasspathResourceHandler("/", "/public"); URL resourceUrl = handler.getResourceUrl("VISIBLE"); assertNotNull(resourceUrl); Path visibleFile = Paths.get(resourceUrl.toURI()); assertNotNull(visibleFile); URL url = handler.getResourceUrl("../HIDDEN"); assertNull(url); }
#vulnerable code @Test public void classpathResourceHandlerTest() throws URISyntaxException { ClasspathResourceHandler handler = new ClasspathResourceHandler("/", "/public"); URL resourceUrl = handler.getResourceUrl("VISIBLE"); assertNotNull(resourceUrl); Path visibleFile = Paths.get(resourceUrl.toURI()); assertNotNull(visibleFile); Path basePath = visibleFile.getParent(); URL url = handler.getResourceUrl("../HIDDEN"); assertNotNull(url); assertTrue("Path traversal security issue", Paths.get(url.toURI()).startsWith(basePath)); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code String buildRealData(final ConditionZkDTO condition, final ServerWebExchange exchange) { String realData = ""; if (condition.getParamType().equals(ParamTypeEnum.QUERY.getName())) { final MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); realData = queryParams.getFirst(condition.getParamName()); } else if (Objects.equals(ParamTypeEnum.HOST.getName(), condition.getParamType())) { realData = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostString(); } else if (Objects.equals(ParamTypeEnum.IP.getName(), condition.getParamType())) { realData = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress(); } else if (Objects.equals(ParamTypeEnum.HEADER.getName(), condition.getParamType())) { final HttpHeaders headers = exchange.getRequest().getHeaders(); final List<String> list = headers.get(condition.getParamName()); if (CollectionUtils.isEmpty(list)) { return realData; } realData = Objects.requireNonNull(headers.get(condition.getParamName())).stream().findFirst().orElse(""); } return realData; }
#vulnerable code String buildRealData(final ConditionZkDTO condition, final ServerWebExchange exchange) { String realData = ""; if (condition.getParamType().equals(ParamTypeEnum.QUERY.getName())) { final MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); realData = queryParams.getFirst(condition.getParamName()); } else if (Objects.equals(ParamTypeEnum.HOST.getName(), condition.getParamType())) { realData = exchange.getRequest().getRemoteAddress().getHostString(); } else if (Objects.equals(ParamTypeEnum.IP.getName(), condition.getParamType())) { realData = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress(); } else if (Objects.equals(ParamTypeEnum.HEADER.getName(), condition.getParamType())) { final HttpHeaders headers = exchange.getRequest().getHeaders(); final List<String> list = headers.get(condition.getParamName()); if (CollectionUtils.isEmpty(list)) { return realData; } realData = headers.get(condition.getParamName()).stream().findFirst().orElse(""); } return realData; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = getClass().getClassLoader().getResource("test.yml").getFile(); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); URL uri = new URL("http://localhost:" + port + "/metrics"); HttpURLConnection cnx = (HttpURLConnection) uri.openConnection(); InputStream stream = cnx.getInputStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop cnx.disconnect(); app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } catch (Throwable ex) { assertThat("Expection caught during scraping", false); ex.printStackTrace(); } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } }
#vulnerable code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = getClass().getClassLoader().getResource("test.yml").getFile(); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } } #location 47 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: WebServer <port> <yaml configuration file>"); System.exit(1); } JmxCollector jc = new JmxCollector(new File(args[1])).register(); int port = Integer.parseInt(args[0]); Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); server.join(); }
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println("Usage: WebServer <port> <yaml configuration file>"); System.exit(1); } JmxCollector jc = new JmxCollector(new FileReader(args[1])).register(); int port = Integer.parseInt(args[0]); Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); server.join(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = resolveRelativePathToResource("test.yml"); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String java = buildJavaPath(System.getenv("JAVA_HOME")); final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } }
#vulnerable code @Test public void agentLoads() throws IOException, InterruptedException { // If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually. final String buildDirectory = (String) System.getProperties().get("buildDirectory"); final String finalName = (String) System.getProperties().get("finalName"); final int port = Integer.parseInt((String) System.getProperties().get("it.port")); final String config = resolveRelativePathToResource("test.yml"); final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config; final String javaHome = System.getenv("JAVA_HOME"); final String java; if (javaHome != null && javaHome.equals("")) { java = javaHome + "/bin/java"; } else { java = "java"; } final Process app = new ProcessBuilder() .command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication") .start(); try { // Wait for application to start app.getInputStream().read(); InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream(); BufferedReader contents = new BufferedReader(new InputStreamReader(stream)); boolean found = false; while (!found) { String line = contents.readLine(); if (line == null) { break; } if (line.contains("jmx_scrape_duration_seconds")) { found = true; } } assertThat("Expected metric not found", found); // Tell application to stop app.getOutputStream().write('\n'); try { app.getOutputStream().flush(); } catch (IOException ignored) { } } finally { final int exitcode = app.waitFor(); // Log any errors printed int len; byte[] buffer = new byte[100]; while ((len = app.getErrorStream().read(buffer)) != -1) { System.out.write(buffer, 0, len); } assertThat("Application did not exit cleanly", exitcode == 0); } } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); server = new Server(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setMaxQueued(10); pool.setName("jmx_exporter"); server.setThreadPool(pool); SelectChannelConnector connector = new SelectChannelConnector(); connector.setHost(socket.getHostName()); connector.setPort(socket.getPort()); connector.setAcceptors(1); server.addConnector(connector); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
#vulnerable code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } String host; int port; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); host = args[0]; file = args[2]; } else { port = Integer.parseInt(args[0]); host = "0.0.0.0"; file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); pool.setMaxThreads(10); pool.setName("jmx_exporter"); server = new Server(pool); ServerConnector connector = new ServerConnector(server); connector.setReuseAddress(true); connector.setHost(host); connector.setPort(port); server.setConnectors(new Connector[]{connector}); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addFilter(GzipFilter.class, "/*", null); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); server = new Server(socket); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); server.setThreadPool(pool); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
#vulnerable code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new FileReader(file)).register(); DefaultExports.initialize(); server = new Server(socket); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); server.setThreadPool(pool); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @BeforeClass public static void beforeClass() { File[] traceFiles = customFileLog("").listFiles(); if (traceFiles == null) { return; } for (File file : traceFiles) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { continue; } FileUtils.deleteQuietly(file); } }
#vulnerable code @BeforeClass public static void beforeClass() { for (File file : customFileLog("").listFiles()) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { continue; } FileUtils.deleteQuietly(file); } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public GraphEdge<V,E> connect(V v1, V v2, E value){ // Check non-null arguments if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); // Ensure that the vertices are in the graph add(v1); add(v2); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> reversedEdge = new GraphEdge<V, E>(v2, v1, value); // Add edges to the graph connected.get(v1).add(edge); connected.get(v2).add(reversedEdge); return edge; }
#vulnerable code public GraphEdge<V,E> connect(V v1, V v2, E value){ //check input if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> edgeReverse = new GraphEdge<V, E>(v2, v1, value); //add edges to the graph (if not present before) connected.get(v1).add(edge); connected.get(v2).add(edgeReverse); return edge; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() { String[] testMaze = { "XX@XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "XX XXXXXXXXXXXXX XXXXXXXXXXX", "XX XXXXXXXXXX XXX XX XXXX", "XXXXX XXXXXX XXX XX XXX XXXX", "XXX XX XXXXXX XX XXX XX XX XXXX", "XXX XXXXX XXXXXX XXXXXX XXXX", "XXXXXXX XXXXXX XXXX", "XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX", "XXXXXXXXXX XX XXXXX XXXX", "XXXXXXXXXX XXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXX XXXX", "XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX", "XXXXXX XXXX XX XXXX", "XXXXXX XXXXXXXXXXXX XX XXXX", "XXXXXX XXO XXXXXX XXXX XXXXXXX", "XXXXXX XXXXX XXX XX", "XXXXXX XXXXXXX XXXXXXXXXXX XXXXX", "XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX", "XXXXXX XXXXXXXXXXXXXX"}; StringMaze maze = new StringMaze(testMaze); // Valid cells assertTrue(maze.validLocation(new Point(2,1))); assertTrue(maze.validLocation(new Point(2,0))); assertTrue(maze.validLocation(new Point(4,5))); // Invalid cells assertTrue(!maze.validLocation(new Point(0,0))); assertTrue(!maze.validLocation(new Point(1,1))); assertTrue(!maze.validLocation(new Point(12,5))); // Initial loc assertEquals(maze.getInitialLoc(), new Point(2, 0)); assertEquals(maze.getGoalLoc(), new Point(9, 15)); // Print valid moves from initial and goal System.out.println(maze.validLocationsFrom(maze.getInitialLoc())); System.out.println(maze.validLocationsFrom(maze.getGoalLoc())); System.out.println(maze.validLocationsFrom(new Point(14, 3))); }
#vulnerable code @Test public void test() { String[] testMaze = { "XX@XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "XX XXXXXXXXXXXXX XXXXXXXXXXX", "XX XXXXXXXXXX XXX XX XXXX", "XXXXX XXXXXX XXX XX XXX XXXX", "XXX XX XXXXXX XX XXX XX XX XXXX", "XXX XXXXX XXXXXX XXXXXX XXXX", "XXXXXXX XXXXXX XXXX", "XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX", "XXXXXXXXXX XX XXXXX XXXX", "XXXXXXXXXX XXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXX XXXX", "XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX", "XXXXXX XXXX XX XXXX", "XXXXXX XXXXXXXXXXXX XX XXXX", "XXXXXX XXO XXXXXX XXXX XXXXXXX", "XXXXXX XXXXX XXX XX", "XXXXXX XXXXXXX XXXXXXXXXXX XXXXX", "XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX", "XXXXXX XXXXXXXXXXXXXX"}; StringMaze maze = new StringMaze(testMaze); // Valid cells assertTrue(maze.getMaze()[1][2]); assertTrue(maze.getMaze()[0][2]); assertTrue(maze.getMaze()[5][4]); // Invalid cells assertFalse(maze.getMaze()[0][0]); assertFalse(maze.getMaze()[1][1]); assertFalse(maze.getMaze()[5][12]); // Initial loc assertEquals(maze.getInitialLoc(), new Point(2, 0)); assertEquals(maze.getGoalLoc(), new Point(9, 15)); // Print valid moves from initial and goal System.out.println(maze.validLocationsFrom(maze.getInitialLoc())); System.out.println(maze.validLocationsFrom(maze.getGoalLoc())); System.out.println(maze.validLocationsFrom(new Point(14, 3))); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public GraphEdge<V,E> connect(V v1, V v2, E value){ // Check non-null arguments if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); // Ensure that the vertices are in the graph add(v1); add(v2); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> reversedEdge = new GraphEdge<V, E>(v2, v1, value); // Add edges to the graph connected.get(v1).add(edge); connected.get(v2).add(reversedEdge); return edge; }
#vulnerable code public GraphEdge<V,E> connect(V v1, V v2, E value){ //check input if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> edgeReverse = new GraphEdge<V, E>(v2, v1, value); //add edges to the graph (if not present before) connected.get(v1).add(edge); connected.get(v2).add(edgeReverse); return edge; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRestartAuditorBookieAfterCrashing() throws Exception { BookieServer auditor = verifyAuditor(); shudownBookie(auditor); // restarting Bookie with same configurations. int indexOfDownBookie = bs.indexOf(auditor); ServerConfiguration serverConfiguration = bsConfs .get(indexOfDownBookie); bs.remove(indexOfDownBookie); bsConfs.remove(indexOfDownBookie); tmpDirs.remove(indexOfDownBookie); startBookie(serverConfiguration); // starting corresponding auditor elector String addr = StringUtils.addrToString(auditor.getLocalAddress()); LOG.debug("Performing Auditor Election:" + addr); auditorElectors.get(addr).doElection(); // waiting for new auditor to come BookieServer newAuditor = waitForNewAuditor(auditor); Assert.assertNotSame( "Auditor re-election is not happened for auditor failure!", auditor, newAuditor); Assert.assertFalse("No relection after old auditor rejoins", auditor .getLocalAddress().getPort() == newAuditor.getLocalAddress() .getPort()); }
#vulnerable code @Test public void testRestartAuditorBookieAfterCrashing() throws Exception { BookieServer auditor = verifyAuditor(); shudownBookie(auditor); // restarting Bookie with same configurations. int indexOfDownBookie = bs.indexOf(auditor); ServerConfiguration serverConfiguration = bsConfs .get(indexOfDownBookie); bs.remove(indexOfDownBookie); bsConfs.remove(indexOfDownBookie); tmpDirs.remove(indexOfDownBookie); startBookie(serverConfiguration); // starting corresponding auditor elector StringBuilder sb = new StringBuilder(); StringUtils.addrToString(sb, auditor.getLocalAddress()); LOG.debug("Performing Auditor Election:" + sb.toString()); auditorElectors.get(sb.toString()).doElection(); // waiting for new auditor to come BookieServer newAuditor = waitForNewAuditor(auditor); Assert.assertNotSame( "Auditor re-election is not happened for auditor failure!", auditor, newAuditor); Assert.assertFalse("No relection after old auditor rejoins", auditor .getLocalAddress().getPort() == newAuditor.getLocalAddress() .getPort()); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleSubscribeMessage(PubSubResponse response) { if (logger.isDebugEnabled()) { logger.debug("Handling a Subscribe message in response: {}, topic: {}, subscriberId: {}", new Object[] { response, getOrigSubData().topic.toStringUtf8(), getOrigSubData().subscriberId.toStringUtf8() }); } Message message = response.getMessage(); synchronized (this) { // Consume the message asynchronously that the client is subscribed // to. Do this only if delivery for the subscription has started and // a MessageHandler has been registered for the TopicSubscriber. if (messageHandler != null) { asyncMessageConsume(message); } else { // MessageHandler has not yet been registered so queue up these // messages for the Topic Subscription. Make the initial lazy // creation of the message queue thread safe just so we don't // run into a race condition where two simultaneous threads process // a received message and both try to create a new instance of // the message queue. Performance overhead should be okay // because the delivery of the topic has not even started yet // so these messages are not consumed and just buffered up here. if (subscribeMsgQueue == null) subscribeMsgQueue = new LinkedList<Message>(); if (logger.isDebugEnabled()) logger .debug("Message has arrived but Subscribe channel does not have a registered MessageHandler yet so queueing up the message: " + message); subscribeMsgQueue.add(message); } } }
#vulnerable code public void handleSubscribeMessage(PubSubResponse response) { if (logger.isDebugEnabled()) logger.debug("Handling a Subscribe message in response: " + response + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); Message message = response.getMessage(); synchronized (this) { // Consume the message asynchronously that the client is subscribed // to. Do this only if delivery for the subscription has started and // a MessageHandler has been registered for the TopicSubscriber. if (messageHandler != null) { asyncMessageConsume(message); } else { // MessageHandler has not yet been registered so queue up these // messages for the Topic Subscription. Make the initial lazy // creation of the message queue thread safe just so we don't // run into a race condition where two simultaneous threads process // a received message and both try to create a new instance of // the message queue. Performance overhead should be okay // because the delivery of the topic has not even started yet // so these messages are not consumed and just buffered up here. if (subscribeMsgQueue == null) subscribeMsgQueue = new LinkedList<Message>(); if (logger.isDebugEnabled()) logger .debug("Message has arrived but Subscribe channel does not have a registered MessageHandler yet so queueing up the message: " + message); subscribeMsgQueue.add(message); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { closeInternal(true); }
#vulnerable code public void close() { synchronized (this) { state = ConnectionState.DISCONNECTED; } if (channel != null) { channel.close().awaitUninterruptibly(); } if (readTimeoutTimer != null) { readTimeoutTimer.stop(); readTimeoutTimer = null; } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public byte[] readMasterKey(long ledgerId) throws IOException, BookieException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledgerId); if (fi == null) { File lf = findIndexFile(ledgerId); if (lf == null) { throw new Bookie.NoLedgerException(ledgerId); } evictFileInfoIfNecessary(); fi = new FileInfo(lf, null); byte[] key = fi.getMasterKey(); fileInfoCache.put(ledgerId, fi); openLedgers.add(ledgerId); return key; } return fi.getMasterKey(); } }
#vulnerable code @Override public byte[] readMasterKey(long ledgerId) throws IOException, BookieException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledgerId); if (fi == null) { File lf = findIndexFile(ledgerId); if (lf == null) { throw new Bookie.NoLedgerException(ledgerId); } if (openLedgers.size() > openFileLimit) { fileInfoCache.remove(openLedgers.removeFirst()).close(); } fi = new FileInfo(lf, null); byte[] key = fi.getMasterKey(); fileInfoCache.put(ledgerId, fi); openLedgers.add(ledgerId); return key; } return fi.getMasterKey(); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.info("Disconnected from bookie: " + addr); errorOutOutstandingEntries(); channel.close(); synchronized (this) { state = ConnectionState.DISCONNECTED; } // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. }
#vulnerable code @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.info("Disconnected from bookie: " + addr); errorOutOutstandingEntries(); channel.close(); state = ConnectionState.DISCONNECTED; // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteSyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); } lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); Integer origEntry = origbb.getInt(); ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteSyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); } lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); Integer origEntry = origbb.getInt(); ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 48 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { closeInternal(true); }
#vulnerable code public void close() { synchronized (this) { state = ConnectionState.DISCONNECTED; } if (channel != null) { channel.close().awaitUninterruptibly(); } if (readTimeoutTimer != null) { readTimeoutTimer.stop(); readTimeoutTimer = null; } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj sync = (SyncObj) ctx; sync.setLedgerEntries(seq); sync.setReturnCode(rc); synchronized (sync) { sync.value = true; sync.notify(); } }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public StatsLogger getStatsLogger(String name) { initIfNecessary(); return new CodahaleStatsLogger(getMetrics(), name); }
#vulnerable code @Override public StatsLogger getStatsLogger(String name) { initIfNecessary(); return new CodahaleStatsLogger(metrics, name); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code FileInfo getFileInfo(Long ledger, byte masterKey[]) throws IOException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledger); if (fi == null) { File lf = findIndexFile(ledger); if (lf == null) { if (masterKey == null) { throw new Bookie.NoLedgerException(ledger); } File dir = pickDirs(ledgerDirectories); String ledgerName = getLedgerName(ledger); lf = new File(dir, ledgerName); // A new ledger index file has been created for this Bookie. // Add this new ledger to the set of active ledgers. if (LOG.isDebugEnabled()) { LOG.debug("New ledger index file created for ledgerId: " + ledger); } activeLedgerManager.addActiveLedger(ledger, true); } evictFileInfoIfNecessary(); fi = new FileInfo(lf, masterKey); fileInfoCache.put(ledger, fi); openLedgers.add(ledger); } if (fi != null) { fi.use(); } return fi; } }
#vulnerable code FileInfo getFileInfo(Long ledger, byte masterKey[]) throws IOException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledger); if (fi == null) { File lf = findIndexFile(ledger); if (lf == null) { if (masterKey == null) { throw new Bookie.NoLedgerException(ledger); } File dir = pickDirs(ledgerDirectories); String ledgerName = getLedgerName(ledger); lf = new File(dir, ledgerName); // A new ledger index file has been created for this Bookie. // Add this new ledger to the set of active ledgers. if (LOG.isDebugEnabled()) { LOG.debug("New ledger index file created for ledgerId: " + ledger); } activeLedgerManager.addActiveLedger(ledger, true); } if (openLedgers.size() > openFileLimit) { fileInfoCache.remove(openLedgers.removeFirst()).close(); } fi = new FileInfo(lf, masterKey); fileInfoCache.put(ledger, fi); openLedgers.add(ledger); } if (fi != null) { fi.use(); } return fi; } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSimpleBookieLedgerMapping() throws Exception { for (int i = 0; i < numberOfLedgers; i++) { createAndAddEntriesToLedger().close(); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 3, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3, ledgers.size()); for (Long ledgerId : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerId)); } } }
#vulnerable code @Test public void testSimpleBookieLedgerMapping() throws Exception { LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory .newLedgerManagerFactory(baseConf, zkc); LedgerManager ledgerManager = newLedgerManagerFactory .newLedgerManager(); List<Long> ledgerList = new ArrayList<Long>(3); LedgerHandle lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 3, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3, ledgers.size()); for (Long ledgerId : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerId)); } } } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteZero() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); } /* * Write a non-zero entry */ ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteZero() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); } /* * Write a non-zero entry */ ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGarbageCollectLedgers() throws Exception { int numLedgers = 100; int numRemovedLedgers = 10; final Set<Long> createdLedgers = new HashSet<Long>(); final Set<Long> removedLedgers = new HashSet<Long>(); // create 100 ledgers createLedgers(numLedgers, createdLedgers); Random r = new Random(System.currentTimeMillis()); final List<Long> tmpList = new ArrayList<Long>(); tmpList.addAll(createdLedgers); Collections.shuffle(tmpList, r); // random remove several ledgers for (int i=0; i<numRemovedLedgers; i++) { long ledgerId = tmpList.get(i); synchronized (removedLedgers) { getLedgerManager().deleteLedger(ledgerId, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { synchronized (removedLedgers) { removedLedgers.notify(); } } }); removedLedgers.wait(); } removedLedgers.add(ledgerId); createdLedgers.remove(ledgerId); } final CountDownLatch inGcProgress = new CountDownLatch(1); final CountDownLatch createLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(2); Thread gcThread = new Thread() { @Override public void run() { getActiveLedgerManager().garbageCollectLedgers(new GarbageCollector() { boolean paused = false; @Override public void gc(long ledgerId) { if (!paused) { inGcProgress.countDown(); try { createLatch.await(); } catch (InterruptedException ie) { } paused = true; } LOG.info("Garbage Collected ledger {}", ledgerId); } }); LOG.info("Gc Thread quits."); endLatch.countDown(); } }; Thread createThread = new Thread() { @Override public void run() { try { inGcProgress.await(); // create 10 more ledgers createLedgers(10, createdLedgers); LOG.info("Finished creating 10 more ledgers."); createLatch.countDown(); } catch (Exception e) { } LOG.info("Create Thread quits."); endLatch.countDown(); } }; createThread.start(); gcThread.start(); endLatch.await(); // test ledgers for (Long ledger : removedLedgers) { assertFalse(getActiveLedgerManager().containsActiveLedger(ledger)); } for (Long ledger : createdLedgers) { assertTrue(getActiveLedgerManager().containsActiveLedger(ledger)); } }
#vulnerable code @Test public void testGarbageCollectLedgers() throws Exception { int numLedgers = 100; int numRemovedLedgers = 10; final Set<Long> createdLedgers = new HashSet<Long>(); final Set<Long> removedLedgers = new HashSet<Long>(); // create 100 ledgers createLedgers(numLedgers, createdLedgers); Random r = new Random(System.currentTimeMillis()); final List<Long> tmpList = new ArrayList<Long>(); tmpList.addAll(createdLedgers); Collections.shuffle(tmpList, r); // random remove several ledgers for (int i=0; i<numRemovedLedgers; i++) { long ledgerId = tmpList.get(i); getLedgerManager().deleteLedger(ledgerId, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { synchronized (removedLedgers) { removedLedgers.notify(); } } }); synchronized (removedLedgers) { removedLedgers.wait(); } removedLedgers.add(ledgerId); createdLedgers.remove(ledgerId); } final CountDownLatch inGcProgress = new CountDownLatch(1); final CountDownLatch createLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(2); Thread gcThread = new Thread() { @Override public void run() { getActiveLedgerManager().garbageCollectLedgers(new GarbageCollector() { boolean paused = false; @Override public void gc(long ledgerId) { if (!paused) { inGcProgress.countDown(); try { createLatch.await(); } catch (InterruptedException ie) { } paused = true; } LOG.info("Garbage Collected ledger {}", ledgerId); } }); LOG.info("Gc Thread quits."); endLatch.countDown(); } }; Thread createThread = new Thread() { @Override public void run() { try { inGcProgress.await(); // create 10 more ledgers createLedgers(10, createdLedgers); LOG.info("Finished creating 10 more ledgers."); createLatch.countDown(); } catch (Exception e) { } LOG.info("Create Thread quits."); endLatch.countDown(); } }; createThread.start(); gcThread.start(); endLatch.await(); // test ledgers for (Long ledger : removedLedgers) { assertFalse(getActiveLedgerManager().containsActiveLedger(ledger)); } for (Long ledger : createdLedgers) { assertTrue(getActiveLedgerManager().containsActiveLedger(ledger)); } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void start(Configuration conf) { initIfNecessary(); int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); String prefix = conf.getString("codahaleStatsPrefix", ""); String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); String csvDir = conf.getString("codahaleStatsCSVEndpoint"); String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); if (!Strings.isNullOrEmpty(graphiteHost)) { LOG.info("Configuring stats with graphite"); HostAndPort addr = HostAndPort.fromString(graphiteHost); final Graphite graphite = new Graphite( new InetSocketAddress(addr.getHostText(), addr.getPort())); reporters.add(GraphiteReporter.forRegistry(getMetrics()) .prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite)); } if (!Strings.isNullOrEmpty(csvDir)) { // NOTE: 1/ metrics output files are exclusive to a given process // 2/ the output directory must exist // 3/ if output files already exist they are not overwritten and there is no metrics output File outdir; if (Strings.isNullOrEmpty(prefix)) { outdir = new File(csvDir, prefix); } else { outdir = new File(csvDir); } LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); reporters.add(CsvReporter.forRegistry(getMetrics()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(outdir)); } if (!Strings.isNullOrEmpty(slf4jCat)) { LOG.info("Configuring stats with slf4j"); reporters.add(Slf4jReporter.forRegistry(getMetrics()) .outputTo(LoggerFactory.getLogger(slf4jCat)) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build()); } for (ScheduledReporter r : reporters) { r.start(metricsOutputFrequency, TimeUnit.SECONDS); } }
#vulnerable code @Override public void start(Configuration conf) { initIfNecessary(); int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); String prefix = conf.getString("codahaleStatsPrefix", ""); String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); String csvDir = conf.getString("codahaleStatsCSVEndpoint"); String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); if (!Strings.isNullOrEmpty(graphiteHost)) { LOG.info("Configuring stats with graphite"); HostAndPort addr = HostAndPort.fromString(graphiteHost); final Graphite graphite = new Graphite( new InetSocketAddress(addr.getHostText(), addr.getPort())); reporters.add(GraphiteReporter.forRegistry(metrics) .prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite)); } if (!Strings.isNullOrEmpty(csvDir)) { // NOTE: 1/ metrics output files are exclusive to a given process // 2/ the output directory must exist // 3/ if output files already exist they are not overwritten and there is no metrics output File outdir; if (Strings.isNullOrEmpty(prefix)) { outdir = new File(csvDir, prefix); } else { outdir = new File(csvDir); } LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); reporters.add(CsvReporter.forRegistry(metrics) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(outdir)); } if (!Strings.isNullOrEmpty(slf4jCat)) { LOG.info("Configuring stats with slf4j"); reporters.add(Slf4jReporter.forRegistry(metrics) .outputTo(LoggerFactory.getLogger(slf4jCat)) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build()); } for (ScheduledReporter r : reporters) { r.start(metricsOutputFrequency, TimeUnit.SECONDS); } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. try { HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); } catch (NoResponseHandlerException e) { logger.error("No response handler found while storing the publish callback."); // Callback on pubsubdata indicating failure. pubSubData.getCallback().operationFailed(pubSubData.context, new CouldNotConnectException("No response " + "handler found while attempting to publish. So could not connect.")); return; } // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); }
#vulnerable code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { bw.close(); } catch (IOException e) { } } }
#vulnerable code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { fos.close(); } catch (IOException e) { } } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj x = (SyncObj) ctx; if (rc != 0) { LOG.error("Failure during add {}", rc); x.failureOccurred = true; } synchronized (x) { x.value = true; x.ls = seq; x.notify(); } }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc != 0) fail("Failed to write entry"); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout=60000) public void testReadFromOpenLedger() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); long lac = writeNEntriesLastWriteSync(lh, numEntriesToWrite); LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); // no recovery opened ledger 's last confirmed entry id is less than written // and it just can read until (i-1) long toRead = lac - 1; Enumeration<LedgerEntry> readEntry = lhOpen.readEntries(toRead, toRead); assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); LedgerEntry e = readEntry.nextElement(); assertEquals(toRead, e.getEntryId()); Assert.assertArrayEquals(entries.get((int)toRead), e.getEntry()); // should not written to a read only ledger try { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); lhOpen.addEntry(entry.array()); fail("Should have thrown an exception here"); } catch (BKException.BKIllegalOpException bkioe) { // this is the correct response } catch (Exception ex) { LOG.error("Unexpected exception", ex); fail("Unexpected exception"); } // close read only ledger should not change metadata lhOpen.close(); lac = writeNEntriesLastWriteSync(lh, numEntriesToWrite); assertEquals("Last confirmed add: ", lac, (numEntriesToWrite * 2) - 1); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == -1) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertEquals("Last confirmed add", sync.lastConfirmed, (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test(timeout=60000) public void testReadFromOpenLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); if(i == numEntriesToWrite/2) { LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); // no recovery opened ledger 's last confirmed entry id is less than written // and it just can read until (i-1) int toRead = i - 1; Enumeration<LedgerEntry> readEntry = lhOpen.readEntries(toRead, toRead); assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); LedgerEntry e = readEntry.nextElement(); assertEquals(toRead, e.getEntryId()); Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); // should not written to a read only ledger try { lhOpen.addEntry(entry.array()); fail("Should have thrown an exception here"); } catch (BKException.BKIllegalOpException bkioe) { // this is the correct response } catch (Exception ex) { LOG.error("Unexpected exception", ex); fail("Unexpected exception"); } // close read only ledger should not change metadata lhOpen.close(); } } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == -1) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION

No dataset card yet

Downloads last month
7