input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code private String extractLibrary(String sharedLibName) throws IOException { File nativesPath = new File(System.getProperty("java.io.tmpdir") + "/steamworks4j/" + libraryCrc); File nativeFile = new File(nativesPath, sharedLibName); if (!nativesPath.exists()) { if (!nativesPath.mkdirs()) { throw new IOException("Error creating temp folder: " + nativesPath.getCanonicalPath()); } } ZipFile zip = new ZipFile(libraryPath); ZipEntry entry = zip.getEntry(sharedLibName); InputStream input = zip.getInputStream(entry); if (input == null) { throw new IOException("Error extracting " + sharedLibName + " from " + libraryPath); } FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } input.close(); output.close(); return nativeFile.getAbsolutePath(); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code private String extractLibrary(String sharedLibName) throws IOException { File nativesPath = new File(System.getProperty("java.io.tmpdir") + "/steamworks4j/" + libraryCrc); File nativeFile = new File(nativesPath, sharedLibName); if (!nativesPath.exists()) { if (!nativesPath.mkdirs()) { throw new IOException("Error creating temp folder: " + nativesPath.getCanonicalPath()); } } ZipFile zip = new ZipFile(libraryPath); ZipEntry entry = zip.getEntry(sharedLibName); InputStream input = zip.getInputStream(entry); if (input == null) { throw new IOException("Error extracting " + sharedLibName + " from " + libraryPath); } FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } output.close(); zip.close(); return nativeFile.getAbsolutePath(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 32 #vulnerability type RESOURCE_LEAK
#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")); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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")); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void precompile( Map<String, Set<String>> typeNames ) { for( ITypeManifold tm: ManifoldHost.instance().getCurrentModule().getTypeManifolds() ) { for( Map.Entry<String, Set<String>> entry: typeNames.entrySet() ) { String typeManifoldClassName = entry.getKey(); if( tm.getClass().getName().equals( typeManifoldClassName ) ) { Collection<String> namesToPrecompile = computeNamesToPrecompile( tm.getAllTypeNames(), entry.getValue() ); for( String fqn : namesToPrecompile ) { JavacElements elementUtils = JavacElements.instance( _tp.getContext() ); // 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 3 #vulnerability type NULL_DEREFERENCE
#fixed code private void precompile( Map<String, Set<String>> typeNames ) { for( ITypeManifold tm: ManifoldHost.instance().getCurrentModule().getTypeManifolds() ) { for( Map.Entry<String, Set<String>> entry: typeNames.entrySet() ) { String typeManifoldClassName = entry.getKey(); if( tm.getClass().getName().equals( typeManifoldClassName ) ) { Collection<String> namesToPrecompile = computeNamesToPrecompile( tm.getAllTypeNames(), entry.getValue() ); for( String fqn : namesToPrecompile ) { // 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 ); } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> getClassSymbolForProducedClass( String fqn, BasicJavacTask[] task ) { init(); Pair<JavaFileObject, String> fileObj = JavaParser.instance().findJavaSource( fqn, null ); if( fileObj == null ) { return null; } StringWriter errors = new StringWriter(); if( _wfm == null ) { _wfm = new ManifoldJavaFileManager( _fm, null, false ); } task[0] = (BasicJavacTask)_javacTool.getTask( errors, _wfm, null, Arrays.asList( "-proc:none", "-source", "1.8", "-Xprefer:source" ), null, Collections.singleton( fileObj.getFirst() ) ); // note, ok to call getTypeElement() directly here and not via IDynamicJdk because always in context of 1.8 (no module) JavacElements elementUtils = JavacElements.instance( task[0].getContext() ); Symbol.ClassSymbol e = elementUtils.getTypeElement( fqn ); if( e != null && e.getSimpleName().contentEquals( ManClassUtil.getShortClassName( fqn ) ) ) { JavacTrees trees = JavacTrees.instance( task[0].getContext() ); TreePath path = trees.getPath( e ); if( path != null ) { return new Pair<>( e, (JCTree.JCCompilationUnit)path.getCompilationUnit() ); } else { // TreePath is only applicable to a source file; // if fqn is not a source file, there is no compilation unit available return new Pair<>( e, null ); } } StringBuffer errorText = errors.getBuffer(); if( errorText.length() > 0 ) { throw new RuntimeException( "Compile errors:\n" + errorText ); } return null; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> getClassSymbolForProducedClass( String fqn, BasicJavacTask[] task ) { StringWriter errors = new StringWriter(); // need javac with ManifoldJavaFileManager because the produced class must come from manifold task[0] = getJavacTask_ManFileMgr(); Symbol.ClassSymbol e = IDynamicJdk.instance().getTypeElement( task[0].getContext(), null, fqn ); if( e != null && e.getSimpleName().contentEquals( ManClassUtil.getShortClassName( fqn ) ) ) { JavacTrees trees = JavacTrees.instance( task[0].getContext() ); TreePath path = trees.getPath( e ); if( path != null ) { return new Pair<>( e, (JCTree.JCCompilationUnit)path.getCompilationUnit() ); } else { // TreePath is only applicable to a source file; // if fqn is not a source file, there is no compilation unit available return new Pair<>( e, null ); } } StringBuffer errorText = errors.getBuffer(); if( errorText.length() > 0 ) { throw new RuntimeException( "Compile errors:\n" + errorText ); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static SrcClass genClass(String fqn, ProgramNode programNode) { ClassNode classNode = programNode.getFirstChild(ClassNode.class); SrcClass clazz = new SrcClass(fqn, SrcClass.Kind.Class); String superClass = classNode.getSuperClass(); if (superClass != null) { clazz.superClass(superClass); } clazz.imports(JavascriptClass.class) .imports( SourcePosition.class ); clazz.addField(new SrcField("ENGINE", ScriptEngine.class) .modifiers(Modifier.STATIC) .initializer(new SrcRawExpression(("JavascriptClass.init(\"" + fqn + "\")")))); clazz.addField(new SrcField("_context", ScriptObjectMirror.class)); addConstructor(clazz, classNode); addMethods(fqn, clazz, classNode); addProperties(fqn, clazz, classNode); return clazz; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code static SrcClass genClass(String fqn, ProgramNode programNode) { ClassNode classNode = programNode.getFirstChild(ClassNode.class); SrcClass clazz = new SrcClass(fqn, SrcClass.Kind.Class); clazz.addAnnotation( new SrcAnnotationExpression( SourcePosition.class ) .addArgument( "url", String.class, programNode.getUrl().toString() ) .addArgument( "feature", String.class, ManClassUtil.getShortClassName( fqn ) ) .addArgument( "offset", int.class, classNode.getStart().getOffset() ) .addArgument( "length", int.class, classNode.getEnd().getOffset() - classNode.getStart().getOffset() ) ); String superClass = classNode.getSuperClass(); if (superClass != null) { clazz.superClass(superClass); } clazz.imports(JavascriptClass.class) .imports( SourcePosition.class ); clazz.addField(new SrcField("ENGINE", ScriptEngine.class) .modifiers(Modifier.STATIC) .initializer(new SrcRawExpression(("JavascriptClass.init(\"" + fqn + "\")")))); clazz.addField(new SrcField("_context", ScriptObjectMirror.class)); addConstructor(clazz, classNode); addMethods(fqn, clazz, classNode); addProperties(fqn, clazz, classNode); return clazz; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 ); } } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Collection<String> getAllTypeNames() { return _fqnToModel.get().getFqns(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Collection<String> getAllTypeNames() { FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get(); if( fqnCache.isEmpty() ) { return Collections.emptySet(); } return fqnCache.getFqns(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isTopLevelType( String fqn ) { return _fqnToModel.get().get( fqn ) != null; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean isTopLevelType( String fqn ) { FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get(); if( fqnCache.isEmpty() ) { return false; } return fqnCache.get( fqn ) != null; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public Tree getParent( Tree node ) { return _parents.getParent( node ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getResponseBody() { if (response == null) { throw new IllegalStateException("The request must first be executed"); } if (!response.isSuccessful()) { throw new IllegalStateException("The request threw an exception"); } return response.getBody(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String getResponseBody() { requireSucceededRequestState(); return responseBody; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Rune getDataRune(int id) throws RiotApiException { return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public Rune getDataRune(int id) throws RiotApiException { return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, (RuneData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ItemList getDataItemList(Region region) throws RiotApiException { return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public ItemList getDataItemList(Region region) throws RiotApiException { return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, (ItemListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public ChampionList getDataChampionList(Region region) throws RiotApiException { return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, (ChampData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public Rune getDataRune(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, (RuneData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public dto.Static.Champion getDataChampion(int id) throws RiotApiException { return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public dto.Static.Champion getDataChampion(int id) throws RiotApiException { return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, (ChampData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RuneList getDataRuneList() throws RiotApiException { return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public RuneList getDataRuneList() throws RiotApiException { return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, (RuneListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, (SpellData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MasteryList getDataMasteryList(Region region) throws RiotApiException { return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public MasteryList getDataMasteryList(Region region) throws RiotApiException { return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, (MasteryListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void init(ApiConfig config, ApiMethod method) { this.config = config; this.method = method; setTimeout(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void init(ApiConfig config, ApiMethod method) { this.config = config; this.method = method; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Mastery getDataMastery(int id) throws RiotApiException { return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public Mastery getDataMastery(int id) throws RiotApiException { return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, (MasteryData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public Item getDataItem(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, (ItemData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected boolean setState(RequestState state) { if (isDone()) { return false; } for (RequestListener listener : listeners) { if (state == RequestState.Succeeded) { listener.onRequestSucceeded(this); } else if (state == RequestState.Failed) { listener.onRequestFailed(getException()); } else if (state == RequestState.TimeOut) { listener.onRequestTimeout(this); } } super.setState(state); if (state == RequestState.Cancelled || state == RequestState.Succeeded || state == RequestState.Failed || state == RequestState.TimeOut) { synchronized (signal) { signal.notifyAll(); } } return true; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected boolean setState(RequestState state) { if (isDone()) { return false; } notifyListeners(state); super.setState(state); if (isDone()) { synchronized (signal) { signal.notifyAll(); } } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public int getResponseCode() { requireSucceededRequestState(); return responseCode; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MasteryList getDataMasteryList() throws RiotApiException { return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public MasteryList getDataMasteryList() throws RiotApiException { return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, (MasteryListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, (SpellData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RuneList getDataRuneList(Region region) throws RiotApiException { return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public RuneList getDataRuneList(Region region) throws RiotApiException { return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, (RuneListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void await() throws InterruptedException { while (!isDone()) { synchronized (signal) { signal.wait(); } } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void await() throws InterruptedException { if (!isDone()) { synchronized (signal) { while (!isDone()) { signal.wait(); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ItemList getDataItemList() throws RiotApiException { return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public ItemList getDataItemList() throws RiotApiException { return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, (ItemListData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, (SpellData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public Mastery getDataMastery(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, (MasteryData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Item getDataItem(int id) throws RiotApiException { return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public Item getDataItem(int id) throws RiotApiException { return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, (ItemData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void await() throws InterruptedException { if (!isDone()) { synchronized (signal) { while (!isDone()) { signal.wait(); } } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void await() throws InterruptedException { while (!isDone()) { synchronized (signal) { signal.wait(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, (SpellData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> T getDto(Type 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
#fixed code public <T> T getDto(Type 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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ChampionList getDataChampionList() throws RiotApiException { return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public ChampionList getDataChampionList() throws RiotApiException { return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, (ChampData) null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RiotApiException getException() { if (!isFailed()) { return null; } return exception; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public RiotApiException getException() { return exception; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initCommitAndTermFromLog() { DBIterator iterator = db.iterator(); try { iterator.seekToLast(); byte[] keyBytes = iterator.peekNext().getKey(); commitIndex = new Integer(asString(keyBytes)); //get the term from the serialized logentry byte[] entryBytes = iterator.peekNext().getValue(); LogEntry entry = asLogEntry(entryBytes); this.currentTerm = entry.term; } finally { try { iterator.close(); } catch (IOException e) { e.printStackTrace(); } } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private void initCommitAndTermFromLog() throws Exception { DBIterator iterator = db.iterator(); try { iterator.seekToLast(); byte[] keyBytes = iterator.peekNext().getKey(); commitIndex = new Integer(asString(keyBytes)); //get the term from the serialized logentry byte[] entryBytes = iterator.peekNext().getValue(); LogEntry entry =(LogEntry)Util.streamableFromByteBuffer(LogEntry.class, entryBytes); this.currentTerm = entry.term; } finally { try { iterator.close(); } catch (IOException e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleEvent(Message msg, RaftHeader hdr) { log.trace("%s: received %s from %s", local_addr, hdr, msg.src()); impl_lock.lock(); try { if(hdr instanceof AppendEntriesRequest) { AppendEntriesRequest req=(AppendEntriesRequest)hdr; impl.handleAppendEntriesRequest(msg.src(),req.term()); } else if(hdr instanceof AppendEntriesResponse) { AppendEntriesResponse rsp=(AppendEntriesResponse)hdr; impl.handleAppendEntriesResponse(msg.src(),rsp.term()); } else if(hdr instanceof VoteRequest) { VoteRequest header=(VoteRequest)hdr; impl.handleVoteRequest(msg.src(),header.term()); } else if(hdr instanceof VoteResponse) { VoteResponse rsp=(VoteResponse)hdr; impl.handleVoteResponse(msg.src(),rsp.term()); } else if(hdr instanceof InstallSnapshotRequest) { InstallSnapshotRequest req=(InstallSnapshotRequest)hdr; impl.handleInstallSnapshotRequest(msg.src(),req.term()); } else if(hdr instanceof InstallSnapshotResponse) { InstallSnapshotResponse rsp=(InstallSnapshotResponse)hdr; impl.handleInstallSnapshotResponse(msg.src(),rsp.term()); } else log.warn("%s: invalid header %s",local_addr,hdr.getClass().getCanonicalName()); } finally { impl_lock.unlock(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleEvent(Message msg, RaftHeader hdr) { // log.trace("%s: received %s from %s", local_addr, hdr, msg.src()); impl_lock.lock(); try { if(hdr instanceof AppendEntriesRequest) { AppendEntriesRequest req=(AppendEntriesRequest)hdr; impl.handleAppendEntriesRequest(msg.src(),req.term()); } else if(hdr instanceof AppendEntriesResponse) { AppendEntriesResponse rsp=(AppendEntriesResponse)hdr; impl.handleAppendEntriesResponse(msg.src(),rsp.term()); } else if(hdr instanceof VoteRequest) { VoteRequest header=(VoteRequest)hdr; impl.handleVoteRequest(msg.src(),header.term()); } else if(hdr instanceof VoteResponse) { VoteResponse rsp=(VoteResponse)hdr; impl.handleVoteResponse(msg.src(),rsp.term()); } else if(hdr instanceof InstallSnapshotRequest) { InstallSnapshotRequest req=(InstallSnapshotRequest)hdr; impl.handleInstallSnapshotRequest(msg.src(),req.term()); } else if(hdr instanceof InstallSnapshotResponse) { InstallSnapshotResponse rsp=(InstallSnapshotResponse)hdr; impl.handleInstallSnapshotResponse(msg.src(),rsp.term()); } else log.warn("%s: invalid header %s",local_addr,hdr.getClass().getCanonicalName()); } finally { impl_lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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 18 #vulnerability type RESOURCE_LEAK
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static UrlBuilder fromString(final String url, final Charset inputEncoding) { if (url.isEmpty()) { return new UrlBuilder(); } final Matcher m = URI_PATTERN.matcher(url); String protocol = null, hostName = null, path = null, anchor = null; Integer port = null; Map<String, List<String>> queryParameters = null; if (m.find()) { protocol = m.group(2); if (m.group(4) != null) { final Matcher n = AUTHORITY_PATTERN.matcher(m.group(4)); if (n.find()) { hostName = IDN.toUnicode(n.group(1)); if (n.group(3) != null) { port = Integer.parseInt(n.group(3)); } } } path = decodePath(m.group(5), inputEncoding); queryParameters = decodeQueryParameters(m.group(7), inputEncoding); anchor = m.group(9); } return of(inputEncoding, DEFAULT_ENCODING, protocol, hostName, port, path, queryParameters, anchor); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code public static UrlBuilder fromString(final String url, final Charset inputEncoding) { if (url.isEmpty()) { return new UrlBuilder(); } final Matcher m = URI_PATTERN.matcher(url); String protocol = null, hostName = null, path = null, anchor = null; Integer port = null; final Map<String, List<String>> queryParameters; if (m.find()) { protocol = m.group(2); if (m.group(4) != null) { final Matcher n = AUTHORITY_PATTERN.matcher(m.group(4)); if (n.find()) { hostName = IDN.toUnicode(n.group(1)); if (n.group(3) != null) { port = Integer.parseInt(n.group(3)); } } } path = decodePath(m.group(5), inputEncoding); queryParameters = decodeQueryParameters(m.group(7), inputEncoding); anchor = m.group(9); } else { queryParameters = emptyMap(); } return of(inputEncoding, DEFAULT_ENCODING, protocol, hostName, port, path, queryParameters, anchor); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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", ""); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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", ""); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int blockSize() { return BLOCK_SIZE; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int blockSize() { return blockSize; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void releaseValue(long newValueReference) { memoryManager.releaseSlice(buildValueSlice(newValueReference)); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code Chunk(ByteBuffer minKey, Chunk<K, V> creator, OakComparator<K> comparator, MemoryManager memoryManager, int maxItems, AtomicInteger externalSize, OakSerializer<K> keySerializer, OakSerializer<V> valueSerializer) { this.memoryManager = memoryManager; this.maxItems = maxItems; this.entries = new int[maxItems * FIELDS + FIRST_ITEM]; this.entryIndex = new AtomicInteger(FIRST_ITEM); this.sortedCount = new AtomicInteger(0); this.minKey = minKey; this.creator = new AtomicReference<>(creator); if (creator == null) { this.state = new AtomicReference<>(State.NORMAL); } else { this.state = new AtomicReference<>(State.INFANT); } this.next = new AtomicMarkableReference<>(null, false); this.pendingOps = new AtomicInteger(); this.rebalancer = new AtomicReference<>(null); // to be updated on rebalance this.statistics = new Statistics(); this.comparator = comparator; this.externalSize = externalSize; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code static void setBlockSize(int blockSize) { synchronized (BlocksPool.class) { // can be easily changed to lock-free instance = new BlocksPool(blockSize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testResizeWithZCGetNewBuffer() { String smallValue = ""; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.setLength((BLOCK_SIZE / Character.BYTES) / 2); String longValue = stringBuilder.toString(); oak.zc().put("A", ""); oak.zc().put("B", longValue); OakRBuffer buffer = oak.zc().get("A"); assertEquals(0, buffer.getInt(0)); oak.zc().put("A", longValue); assertEquals(longValue.length(), buffer.getInt(0)); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testResizeWithZCGetNewBuffer() { final int blockSize = BlocksPool.getInstance().blockSize(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.setLength((blockSize / Character.BYTES) / 2); String longValue = stringBuilder.toString(); String smallValue = ""; oak.zc().put("A", smallValue); oak.zc().put("B", longValue); OakRBuffer buffer = oak.zc().get("A"); assertEquals(0, buffer.getInt(0)); oak.zc().put("A", longValue); assertEquals(longValue.length(), buffer.getInt(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static void setBlockSize(int blockSize) { BLOCK_SIZE = blockSize; synchronized (BlocksPool.class) { // can be easily changed to lock-free instance = new BlocksPool(); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code static void setBlockSize(int blockSize) { synchronized (BlocksPool.class) { // can be easily changed to lock-free instance = new BlocksPool(blockSize); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code XSSFUnmarshaller(PoijiOptions options) { this.options = options; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private static Deserializer deserializer(File file) throws FileNotFoundException { final PoijiStream poiParser = new PoijiStream(fileInputStream(file)); final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser); return Unmarshaller.instance(workbook); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @SuppressWarnings("unchecked") private static Deserializer deserializer(File file) throws FileNotFoundException { final PoijiStream poiParser = new PoijiStream(fileInputStream(file)); final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser); return Deserializer.instance(workbook); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public <T> void unmarshal(Class<T> type, Consumer<? super T> consumer) { HSSFWorkbook workbook = (HSSFWorkbook) workbook(); Optional<String> maybeSheetName = this.getSheetName(type, options); hssfFormulaEvaluator = HSSFFormulaEvaluator.create(workbook, null, null); Sheet sheet = this.getSheetToProcess(workbook, options, maybeSheetName.orElse(null)); int skip = options.skip(); int maxPhysicalNumberOfRows = sheet.getPhysicalNumberOfRows() + 1 - skip; loadColumnTitles(sheet, maxPhysicalNumberOfRows); AnnotationUtil.validateMandatoryNameColumns(options, type, columnIndexPerTitle.keySet()); for (Row currentRow : sheet) { if (!skip(currentRow, skip) && !isRowEmpty(currentRow)) { internalCount += 1; if (limit != 0 && internalCount > limit) return; T instance = deserializeRowToInstance(currentRow, type); consumer.accept(instance); } } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public <T> void unmarshal(Class<T> type, Consumer<? super T> consumer) { HSSFWorkbook workbook = (HSSFWorkbook) workbook(); Optional<String> maybeSheetName = this.getSheetName(type, options); baseFormulaEvaluator = HSSFFormulaEvaluator.create(workbook, null, null); Sheet sheet = this.getSheetToProcess(workbook, options, maybeSheetName.orElse(null)); processRowsToObjects(sheet, type, consumer); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private static Deserializer deserializer(File file, PoijiOptions options) throws FileNotFoundException { final PoijiStream poiParser = new PoijiStream(fileInputStream(file)); final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser); return Deserializer.instance(workbook, options); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @SuppressWarnings("unchecked") private static Deserializer deserializer(File file, PoijiOptions options) { final PoijiStream poiParser = new PoijiStream(file); final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser); return Deserializer.instance(workbook, options); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void executeTask(RenameFilesTaskParameters taskParameters, ProgressMonitor progressMonitor) throws IOException { Map<String, String> fileNamesMap = filterNonExistingEntriesAndAddSeparatorIfNeeded(taskParameters.fileNamesMap); if (fileNamesMap.size() == 0) { return; } File temporaryFile = getTemporaryFile(zipModel.getZipFile().getPath()); boolean successFlag = false; try(RandomAccessFile inputStream = new RandomAccessFile(zipModel.getZipFile(), RandomAccessFileMode.WRITE.getValue()); OutputStream outputStream = new CountingOutputStream(new SplitOutputStream(temporaryFile))) { long currentFileCopyPointer = 0; // Maintain a different list to iterate, so that when the file name is changed in the central directory // we still have access to the original file names. If iterating on the original list from central directory, // it might be that a file name has changed because of other file name, ex: if a directory name has to be changed // and the file is part of that directory, by the time the file has to be changed, its name might have changed // when changing the name of the directory. There is some overhead with this approach, but is safer. List<FileHeader> allUnchangedFileHeaders = new ArrayList<>(zipModel.getCentralDirectory().getFileHeaders()); for (FileHeader fileHeader : allUnchangedFileHeaders) { Map.Entry<String, String> fileNameMapForThisEntry = getCorrespondingEntryFromMap(fileHeader, fileNamesMap); progressMonitor.setFileName(fileHeader.getFileName()); if (fileNameMapForThisEntry == null) { // copy complete entry without any changes long lengthToCopy = getLocalFileHeaderSize(fileHeader) + fileHeader.getCompressedSize() + getDataDescriptorSize(zipModel, fileHeader); currentFileCopyPointer += copyFile(inputStream, outputStream, currentFileCopyPointer, lengthToCopy, progressMonitor); } else { String newFileName = getNewFileName(fileNameMapForThisEntry.getValue(), fileNameMapForThisEntry.getKey(), fileHeader.getFileName()); byte[] newFileNameBytes = newFileName.getBytes(charset); int headersOffset = newFileNameBytes.length - fileHeader.getFileNameLength(); currentFileCopyPointer = copyEntryAndChangeFileName(newFileNameBytes, fileHeader, currentFileCopyPointer, inputStream, outputStream, progressMonitor); updateHeadersInZipModel(fileHeader, newFileName, newFileNameBytes, headersOffset); } verifyIfTaskIsCancelled(); } headerWriter.finalizeZipFile(zipModel, outputStream, charset); successFlag = true; } finally { cleanupFile(successFlag, zipModel.getZipFile(), temporaryFile); } } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void executeTask(RenameFilesTaskParameters taskParameters, ProgressMonitor progressMonitor) throws IOException { Map<String, String> fileNamesMap = filterNonExistingEntriesAndAddSeparatorIfNeeded(taskParameters.fileNamesMap); if (fileNamesMap.size() == 0) { return; } File temporaryFile = getTemporaryFile(zipModel.getZipFile().getPath()); boolean successFlag = false; try(RandomAccessFile inputStream = new RandomAccessFile(zipModel.getZipFile(), RandomAccessFileMode.WRITE.getValue()); SplitOutputStream outputStream = new SplitOutputStream(temporaryFile)) { long currentFileCopyPointer = 0; // Maintain a different list to iterate, so that when the file name is changed in the central directory // we still have access to the original file names. If iterating on the original list from central directory, // it might be that a file name has changed because of other file name, ex: if a directory name has to be changed // and the file is part of that directory, by the time the file has to be changed, its name might have changed // when changing the name of the directory. There is some overhead with this approach, but is safer. List<FileHeader> allUnchangedFileHeaders = new ArrayList<>(zipModel.getCentralDirectory().getFileHeaders()); for (FileHeader fileHeader : allUnchangedFileHeaders) { Map.Entry<String, String> fileNameMapForThisEntry = getCorrespondingEntryFromMap(fileHeader, fileNamesMap); progressMonitor.setFileName(fileHeader.getFileName()); long lengthToCopy = HeaderUtil.getOffsetOfNextEntry(zipModel, fileHeader) - outputStream.getFilePointer(); if (fileNameMapForThisEntry == null) { // copy complete entry without any changes currentFileCopyPointer += copyFile(inputStream, outputStream, currentFileCopyPointer, lengthToCopy, progressMonitor); } else { String newFileName = getNewFileName(fileNameMapForThisEntry.getValue(), fileNameMapForThisEntry.getKey(), fileHeader.getFileName()); byte[] newFileNameBytes = newFileName.getBytes(charset); int headersOffset = newFileNameBytes.length - fileHeader.getFileNameLength(); currentFileCopyPointer = copyEntryAndChangeFileName(newFileNameBytes, fileHeader, currentFileCopyPointer, lengthToCopy, inputStream, outputStream, progressMonitor); updateHeadersInZipModel(fileHeader, newFileName, newFileNameBytes, headersOffset); } verifyIfTaskIsCancelled(); } headerWriter.finalizeZipFile(zipModel, outputStream, charset); successFlag = true; } finally { cleanupFile(successFlag, zipModel.getZipFile(), temporaryFile); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] getFileAttributes(File file) { try { if (file == null || (!Files.isSymbolicLink(file.toPath()) && !file.exists())) { return new byte[4]; } Path path = file.toPath(); String os = System.getProperty("os.name").toLowerCase(); if (isWindows(os)) { return getWindowsFileAttributes(path); } else if (isMac(os) || isUnix(os)) { return getPosixFileAttributes(path); } else { return new byte[4]; } } catch (NoSuchMethodError e) { return new byte[4]; } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static byte[] getFileAttributes(File file) { try { if (file == null || (!Files.isSymbolicLink(file.toPath()) && !file.exists())) { return new byte[4]; } Path path = file.toPath(); if (isWindows()) { return getWindowsFileAttributes(path); } else if (isMac() || isUnix()) { return getPosixFileAttributes(path); } else { return new byte[4]; } } catch (NoSuchMethodError e) { return new byte[4]; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void executeTask(RenameFilesTaskParameters taskParameters, ProgressMonitor progressMonitor) throws IOException { Map<String, String> fileNamesMap = filterNonExistingEntriesAndAddSeparatorIfNeeded(taskParameters.fileNamesMap); if (fileNamesMap.size() == 0) { return; } File temporaryFile = getTemporaryFile(zipModel.getZipFile().getPath()); boolean successFlag = false; try(RandomAccessFile inputStream = new RandomAccessFile(zipModel.getZipFile(), RandomAccessFileMode.WRITE.getValue()); CountingOutputStream outputStream = new CountingOutputStream(new SplitOutputStream(temporaryFile))) { long currentFileCopyPointer = 0; // Maintain a different list to iterate, so that when the file name is changed in the central directory // we still have access to the original file names. If iterating on the original list from central directory, // it might be that a file name has changed because of other file name, ex: if a directory name has to be changed // and the file is part of that directory, by the time the file has to be changed, its name might have changed // when changing the name of the directory. There is some overhead with this approach, but is safer. List<FileHeader> allUnchangedFileHeaders = new ArrayList<>(zipModel.getCentralDirectory().getFileHeaders()); for (FileHeader fileHeader : allUnchangedFileHeaders) { Map.Entry<String, String> fileNameMapForThisEntry = getCorrespondingEntryFromMap(fileHeader, fileNamesMap); progressMonitor.setFileName(fileHeader.getFileName()); long lengthToCopy = HeaderUtil.getOffsetOfNextEntry(zipModel, fileHeader) - outputStream.getFilePointer(); if (fileNameMapForThisEntry == null) { // copy complete entry without any changes currentFileCopyPointer += copyFile(inputStream, outputStream, currentFileCopyPointer, lengthToCopy, progressMonitor); } else { String newFileName = getNewFileName(fileNameMapForThisEntry.getValue(), fileNameMapForThisEntry.getKey(), fileHeader.getFileName()); byte[] newFileNameBytes = newFileName.getBytes(charset); int headersOffset = newFileNameBytes.length - fileHeader.getFileNameLength(); currentFileCopyPointer = copyEntryAndChangeFileName(newFileNameBytes, fileHeader, currentFileCopyPointer, lengthToCopy, inputStream, outputStream, progressMonitor); updateHeadersInZipModel(fileHeader, newFileName, newFileNameBytes, headersOffset); } verifyIfTaskIsCancelled(); } headerWriter.finalizeZipFile(zipModel, outputStream, charset); successFlag = true; } finally { cleanupFile(successFlag, zipModel.getZipFile(), temporaryFile); } } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void executeTask(RenameFilesTaskParameters taskParameters, ProgressMonitor progressMonitor) throws IOException { Map<String, String> fileNamesMap = filterNonExistingEntriesAndAddSeparatorIfNeeded(taskParameters.fileNamesMap); if (fileNamesMap.size() == 0) { return; } File temporaryFile = getTemporaryFile(zipModel.getZipFile().getPath()); boolean successFlag = false; try(RandomAccessFile inputStream = new RandomAccessFile(zipModel.getZipFile(), RandomAccessFileMode.WRITE.getValue()); SplitOutputStream outputStream = new SplitOutputStream(temporaryFile)) { long currentFileCopyPointer = 0; // Maintain a different list to iterate, so that when the file name is changed in the central directory // we still have access to the original file names. If iterating on the original list from central directory, // it might be that a file name has changed because of other file name, ex: if a directory name has to be changed // and the file is part of that directory, by the time the file has to be changed, its name might have changed // when changing the name of the directory. There is some overhead with this approach, but is safer. List<FileHeader> allUnchangedFileHeaders = new ArrayList<>(zipModel.getCentralDirectory().getFileHeaders()); for (FileHeader fileHeader : allUnchangedFileHeaders) { Map.Entry<String, String> fileNameMapForThisEntry = getCorrespondingEntryFromMap(fileHeader, fileNamesMap); progressMonitor.setFileName(fileHeader.getFileName()); long lengthToCopy = HeaderUtil.getOffsetOfNextEntry(zipModel, fileHeader) - outputStream.getFilePointer(); if (fileNameMapForThisEntry == null) { // copy complete entry without any changes currentFileCopyPointer += copyFile(inputStream, outputStream, currentFileCopyPointer, lengthToCopy, progressMonitor); } else { String newFileName = getNewFileName(fileNameMapForThisEntry.getValue(), fileNameMapForThisEntry.getKey(), fileHeader.getFileName()); byte[] newFileNameBytes = newFileName.getBytes(charset); int headersOffset = newFileNameBytes.length - fileHeader.getFileNameLength(); currentFileCopyPointer = copyEntryAndChangeFileName(newFileNameBytes, fileHeader, currentFileCopyPointer, lengthToCopy, inputStream, outputStream, progressMonitor); updateHeadersInZipModel(fileHeader, newFileName, newFileNameBytes, headersOffset); } verifyIfTaskIsCancelled(); } headerWriter.finalizeZipFile(zipModel, outputStream, charset); successFlag = true; } finally { cleanupFile(successFlag, zipModel.getZipFile(), temporaryFile); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); return isWindows(os); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public static boolean isWindows() { return (OPERATING_SYSTEM_NAME.contains("win")); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private DecompressedInputStream initializeEntryInputStream(LocalFileHeader localFileHeader) throws IOException { ZipEntryInputStream zipEntryInputStream = new ZipEntryInputStream(inputStream); CipherInputStream cipherInputStream = initializeCipherInputStream(zipEntryInputStream, localFileHeader); return initializeDecompressorForThisEntry(cipherInputStream, localFileHeader); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private DecompressedInputStream initializeEntryInputStream(LocalFileHeader localFileHeader) throws IOException { ZipEntryInputStream zipEntryInputStream = new ZipEntryInputStream(inputStream, getCompressedSize(localFileHeader)); CipherInputStream cipherInputStream = initializeCipherInputStream(zipEntryInputStream, localFileHeader); return initializeDecompressorForThisEntry(cipherInputStream, localFileHeader); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void bidiBackpressure() throws InterruptedException { Object lock = new Object(); BackpressureDetector clientReqBPDetector = new BackpressureDetector(madMultipleCutoff); BackpressureDetector clientRespBPDetector = new BackpressureDetector(madMultipleCutoff); RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Flowable<NumberProto.Number> rxRequest = Flowable .fromIterable(new Sequence(180, clientReqBPDetector)) .doOnNext(i -> System.out.println(i + " -->")) .map(BackpressureIntegrationTest::protoNum); Flowable<NumberProto.Number> rxResponse = stub.twoWayPressure(rxRequest); rxResponse.subscribe( n -> { clientRespBPDetector.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(clientReqBPDetector.backpressureDelayOcurred()).isTrue(); assertThat(serverRespBPDetector.backpressureDelayOcurred()).isTrue(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void bidiBackpressure() throws InterruptedException { RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Flowable<NumberProto.Number> rxRequest = Flowable .fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator) .doOnNext(i -> System.out.println(i + " --> ")) .doOnNext(i -> updateNumberOfWaits(clientLastValueTime, clientNbOfWaits)) .map(BackpressureIntegrationTest::protoNum); TestSubscriber<NumberProto.Number> rxResponse = stub.twoWayPressure(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(clientNbOfWaits.get()).isEqualTo(1); assertThat(serverNumberOfWaits.get()).isEqualTo(1); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void serverToClientBackpressure() throws InterruptedException { Object lock = new Object(); BackpressureDetector clientBackpressureDetector = new BackpressureDetector(madMultipleCutoff); ReactorNumbersGrpc.ReactorNumbersStub stub = ReactorNumbersGrpc.newReactorStub(channel); Mono<Empty> reactorRequest = Mono.just(Empty.getDefaultInstance()); Flux<NumberProto.Number> reactorResponse = stub.responsePressure(reactorRequest); reactorResponse.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
#fixed code @Test public void serverToClientBackpressure() throws InterruptedException { ReactorNumbersGrpc.ReactorNumbersStub stub = ReactorNumbersGrpc.newReactorStub(channel); Mono<Empty> reactorRequest = Mono.just(Empty.getDefaultInstance()); Flux<NumberProto.Number> reactorResponse = stub.responsePressure(reactorRequest) .doOnNext(n -> System.out.println(n.getNumber(0) + " <--")) .doOnNext(n -> waitIfValuesAreEqual(n.getNumber(0), 3)); StepVerifier.create(reactorResponse) .expectNextCount(NUMBER_OF_STREAM_ELEMENTS) .expectComplete() .verify(Duration.ofSeconds(5)); assertThat(numberOfWaits.get()).isEqualTo(1); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void clientToServerBackpressure() throws InterruptedException { Object lock = new Object(); RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); BackpressureDetector clientBackpressureDetector = new BackpressureDetector(madMultipleCutoff); Sequence seq = new Sequence(200, clientBackpressureDetector); Flowable<NumberProto.Number> rxRequest = Flowable .fromIterable(seq) .doOnNext(i -> System.out.println(i + " -->")) .map(BackpressureIntegrationTest::protoNum); Single<NumberProto.Number> rxResponse = stub.requestPressure(rxRequest); rxResponse.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
#fixed code @Test public void clientToServerBackpressure() throws InterruptedException { RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel); Flowable<NumberProto.Number> rxRequest = Flowable .fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator) .doOnNext(i -> System.out.println(i + " --> ")) .doOnNext(i -> updateNumberOfWaits(clientLastValueTime, clientNbOfWaits)) .map(BackpressureIntegrationTest::protoNum); TestObserver<NumberProto.Number> rxResponse = stub.requestPressure(rxRequest).test(); rxResponse.awaitTerminalEvent(5, TimeUnit.SECONDS); rxResponse.assertComplete() .assertValue(v -> v.getNumber(0) == NUMBER_OF_STREAM_ELEMENTS - 1); assertThat(clientNbOfWaits.get()).isEqualTo(1); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String render(ClassModel model, int index, int size, Map<String, Object> session) { if (isExcludedClass(model.getType().getName())) { return null; } StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); ClassTypeInfo type = model.getType(); if (index == 0) { Util.generateLicense(writer); registerJvmClasses(); for (Object fqcn : jvmClasses()) { JVMClass.generateDTS(writer, fqcn.toString()); } // include a file if present writer.print(includeFileIfPresent("index.header.d.ts")); if (!type.getModuleName().equals("vertx")) { if (isOptionalModule("@vertx/core")) { writer.println("// @ts-ignore"); } // hard coded imports for non codegen types writer.print("import { Handler, AsyncResult } from '@vertx/core';\n\n"); } } else { writer.print("\n"); } boolean imports = false; @SuppressWarnings("unchecked") Map<String, String> aliasMap = (Map<String, String>) session.computeIfAbsent("aliasMap", (a) -> new HashMap<String, String>()); for (ApiTypeInfo referencedType : model.getReferencedTypes()) { if (!isImported(referencedType, session)) { if (!referencedType.getRaw().getModuleName().equals(type.getModuleName())) { String simpleName = referencedType.getSimpleName(); if (simpleName.equals(model.getIfaceSimpleName())) { String aliasName = simpleName + "Super"; simpleName = simpleName + " as " + aliasName; aliasMap.put(referencedType.getName(), aliasName); } // ignore missing imports if (isOptionalModule(getNPMScope(referencedType.getRaw().getModule()))) { writer.println("// @ts-ignore"); } writer.printf("import { %s } from '%s';\n", simpleName, getNPMScope(referencedType.getRaw().getModule())); imports = true; } } } for (ClassTypeInfo dataObjectType : model.getReferencedDataObjectTypes()) { if (!isImported(dataObjectType, session)) { if (dataObjectType.getRaw().getModuleName().equals(type.getModuleName())) { writer.printf("import { %s } from './options';\n", dataObjectType.getSimpleName()); imports = true; } else { writer.printf("import { %s } from '%s/options';\n", dataObjectType.getSimpleName(), getNPMScope(dataObjectType.getRaw().getModule())); imports = true; } } } for (EnumTypeInfo enumType : model.getReferencedEnumTypes()) { if (!isImported(enumType, session)) { if (enumType.getRaw().getModuleName().equals(type.getModuleName())) { writer.printf("import { %s } from './enums';\n", enumType.getSimpleName()); imports = true; } else { writer.printf("import { %s } from '%s/enums';\n", enumType.getSimpleName(), getNPMScope(enumType.getRaw().getModule())); imports = true; } } } if (imports) { writer.print("\n"); } final Set<String> superTypes = new HashSet<>(); model.getAbstractSuperTypes().forEach(ti -> superTypes.add(genType(ti))); if (model.isHandler()) { if (model.isConcrete()) { superTypes.add("Handler<" + genType(model.getHandlerArg()) + ">"); } } generateDoc(writer, model.getDoc(), ""); writer.printf("export %s %s%s", model.isConcrete() ? "abstract class" : "interface", type.getSimpleName(), genGeneric(type.getParams())); if (model.isConcrete()) { if (model.getConcreteSuperType() != null) { String simpleName = aliasMap.get(model.getConcreteSuperType().getName()); writer.printf(" extends %s", simpleName != null ? simpleName : genType(model.getConcreteSuperType())); } if (!superTypes.isEmpty()) { writer.printf(" implements %s", String.join(", ", superTypes)); } } else { if (model.isHandler()) { writer.printf(" extends Handler<%s>", genType(model.getHandlerArg())); if (!superTypes.isEmpty()) { writer.printf(", %s", String.join(", ", superTypes)); } } else { if (!superTypes.isEmpty()) { writer.printf(" extends %s", String.join(", ", superTypes)); } } } writer.print(" {\n"); boolean moreConstants = false; boolean hasConstantInInterface = !model.isConcrete() && model.getConstants().size() > 0; // this looks awkward (and it is) but TS does not allow static constants in interfaces // so they get listed on the abstract classes. if (model.isConcrete()) { for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } } boolean moreMethods = false; boolean hasStaticMethodsInInterface = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!model.isConcrete() && method.isStaticMethod()) { hasStaticMethodsInInterface = true; continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } // BEGIN of non polyglot methods... for (MethodInfo method : model.getAnyJavaTypeMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); // if the model is not concrete (interface) we need to merge types to allow declaring the constants // from the java interface if (hasConstantInInterface || hasStaticMethodsInInterface) { writer.print("\n"); writer.printf("export abstract class %s%s implements %s%s {\n", type.getSimpleName(), genGeneric(type.getParams()), type.getSimpleName(), genGeneric(type.getParams())); moreConstants = false; for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } moreMethods = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!method.isStaticMethod()) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); } if (index == size - 1) { // include a file if present writer.print(includeFileIfPresent("index.footer.d.ts")); } return sw.toString(); } #location 216 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String render(ClassModel model, int index, int size, Map<String, Object> session) { if (isExcludedClass(model.getType().getName())) { return null; } StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); ClassTypeInfo type = model.getType(); if (index == 0) { Util.generateLicense(writer); registerJvmClasses(); for (Object fqcn : jvmClasses("api")) { JVMClass.generateDTS(writer, fqcn.toString()); } // include a file if present writer.print(includeFileIfPresent("index.header.d.ts")); if (!type.getModuleName().equals("vertx")) { if (isOptionalModule("@vertx/core")) { writer.println("// @ts-ignore"); } // hard coded imports for non codegen types writer.print("import { Handler, AsyncResult } from '@vertx/core';\n\n"); } } else { writer.print("\n"); } boolean imports = false; @SuppressWarnings("unchecked") Map<String, String> aliasMap = (Map<String, String>) session.computeIfAbsent("aliasMap", (a) -> new HashMap<String, String>()); for (ApiTypeInfo referencedType : model.getReferencedTypes()) { if (!sameModule(type, referencedType.getRaw())) { String simpleName = referencedType.getSimpleName(); if (simpleName.equals(model.getIfaceSimpleName())) { String aliasName = simpleName + "Super"; simpleName = simpleName + " as " + aliasName; aliasMap.put(referencedType.getName(), aliasName); } importType(writer, session, referencedType, simpleName, getNPMScope(referencedType.getRaw().getModule())); imports = true; } } for (ClassTypeInfo dataObjectType : model.getReferencedDataObjectTypes()) { if (sameModule(type, dataObjectType.getRaw())) { importType(writer, session, dataObjectType, dataObjectType.getSimpleName(), "./options"); imports = true; } else { importType(writer, session, dataObjectType, dataObjectType.getSimpleName(), getNPMScope(dataObjectType.getRaw().getModule()) + "/options"); imports = true; } } for (EnumTypeInfo enumType : model.getReferencedEnumTypes()) { if (enumType.getRaw().getModuleName() == null) { System.err.println("@@@ Missing module for ENUM: " + enumType); continue; } if (sameModule(type, enumType.getRaw())) { importType(writer, session, enumType, enumType.getSimpleName(), "./enums"); imports = true; } else { importType(writer, session, enumType, enumType.getSimpleName(), getNPMScope(enumType.getRaw().getModule()) + "/enums"); imports = true; } } final Set<String> superTypes = new HashSet<>(); // ensure that all super types are also imported model.getAbstractSuperTypes().forEach(ti -> { if (!sameModule(type, ti.getRaw())) { importType(writer, session, ti, ti.getSimpleName(), getNPMScope(ti.getRaw().getModule())); } superTypes.add(genType(ti)); }); imports |= superTypes.size() > 0; if (model.isHandler()) { if (model.isConcrete()) { TypeInfo ti = model.getHandlerArg(); if (!sameModule(type, ti.getRaw())) { importType(writer, session, ti, ti.getSimpleName(), getNPMScope(ti.getRaw().getModule()) + (ti.isDataObjectHolder() ? "/options" : "")); imports = true; } superTypes.add("Handler<" + genType(ti) + ">"); } } if (imports) { writer.print("\n"); } generateDoc(writer, model.getDoc(), ""); writer.printf("export %s %s%s", model.isConcrete() ? "abstract class" : "interface", type.getSimpleName(), genGeneric(type.getParams())); if (model.isConcrete()) { if (model.getConcreteSuperType() != null) { String simpleName = aliasMap.get(model.getConcreteSuperType().getName()); writer.printf(" extends %s", simpleName != null ? simpleName : genType(model.getConcreteSuperType())); } if (!superTypes.isEmpty()) { writer.printf(" implements %s", String.join(", ", superTypes)); } } else { if (model.isHandler()) { writer.printf(" extends Handler<%s>", genType(model.getHandlerArg())); if (!superTypes.isEmpty()) { writer.printf(", %s", String.join(", ", superTypes)); } } else { if (!superTypes.isEmpty()) { writer.printf(" extends %s", String.join(", ", superTypes)); } } } writer.print(" {\n"); boolean moreConstants = false; boolean hasConstantInInterface = !model.isConcrete() && model.getConstants().size() > 0; // this looks awkward (and it is) but TS does not allow static constants in interfaces // so they get listed on the abstract classes. if (model.isConcrete()) { for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } } boolean moreMethods = false; boolean hasStaticMethodsInInterface = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!model.isConcrete() && method.isStaticMethod()) { hasStaticMethodsInInterface = true; continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } // BEGIN of non polyglot methods... for (MethodInfo method : model.getAnyJavaTypeMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); // if the model is not concrete (interface) we need to merge types to allow declaring the constants // from the java interface if (hasConstantInInterface || hasStaticMethodsInInterface) { writer.print("\n"); writer.printf("export abstract class %s%s implements %s%s {\n", type.getSimpleName(), genGeneric(type.getParams()), type.getSimpleName(), genGeneric(type.getParams())); moreConstants = false; for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } moreMethods = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!method.isStaticMethod()) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); } if (index == size - 1) { // include a file if present writer.print(includeFileIfPresent("index.footer.d.ts")); } return sw.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String render(ClassModel model, int index, int size, Map<String, Object> session) { if (isExcludedClass(model.getType().getName())) { return null; } StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); ClassTypeInfo type = model.getType(); if (index == 0) { Util.generateLicense(writer); registerJvmClasses(); for (Object fqcn : jvmClasses()) { JVMClass.generateDTS(writer, fqcn.toString()); } // include a file if present writer.print(includeFileIfPresent("index.header.d.ts")); if (!type.getModuleName().equals("vertx")) { if (isOptionalModule("@vertx/core")) { writer.println("// @ts-ignore"); } // hard coded imports for non codegen types writer.print("import { Handler, AsyncResult } from '@vertx/core';\n\n"); } } else { writer.print("\n"); } boolean imports = false; @SuppressWarnings("unchecked") Map<String, String> aliasMap = (Map<String, String>) session.computeIfAbsent("aliasMap", (a) -> new HashMap<String, String>()); for (ApiTypeInfo referencedType : model.getReferencedTypes()) { if (!isImported(referencedType, session)) { if (!referencedType.getRaw().getModuleName().equals(type.getModuleName())) { String simpleName = referencedType.getSimpleName(); if (simpleName.equals(model.getIfaceSimpleName())) { String aliasName = simpleName + "Super"; simpleName = simpleName + " as " + aliasName; aliasMap.put(referencedType.getName(), aliasName); } // ignore missing imports if (isOptionalModule(getNPMScope(referencedType.getRaw().getModule()))) { writer.println("// @ts-ignore"); } writer.printf("import { %s } from '%s';\n", simpleName, getNPMScope(referencedType.getRaw().getModule())); imports = true; } } } for (ClassTypeInfo dataObjectType : model.getReferencedDataObjectTypes()) { if (!isImported(dataObjectType, session)) { if (dataObjectType.getRaw().getModuleName().equals(type.getModuleName())) { writer.printf("import { %s } from './options';\n", dataObjectType.getSimpleName()); imports = true; } else { writer.printf("import { %s } from '%s/options';\n", dataObjectType.getSimpleName(), getNPMScope(dataObjectType.getRaw().getModule())); imports = true; } } } for (EnumTypeInfo enumType : model.getReferencedEnumTypes()) { if (!isImported(enumType, session)) { if (enumType.getRaw().getModuleName().equals(type.getModuleName())) { writer.printf("import { %s } from './enums';\n", enumType.getSimpleName()); imports = true; } else { writer.printf("import { %s } from '%s/enums';\n", enumType.getSimpleName(), getNPMScope(enumType.getRaw().getModule())); imports = true; } } } if (imports) { writer.print("\n"); } final Set<String> superTypes = new HashSet<>(); model.getAbstractSuperTypes().forEach(ti -> superTypes.add(genType(ti))); if (model.isHandler()) { if (model.isConcrete()) { superTypes.add("Handler<" + genType(model.getHandlerArg()) + ">"); } } generateDoc(writer, model.getDoc(), ""); writer.printf("export %s %s%s", model.isConcrete() ? "abstract class" : "interface", type.getSimpleName(), genGeneric(type.getParams())); if (model.isConcrete()) { if (model.getConcreteSuperType() != null) { String simpleName = aliasMap.get(model.getConcreteSuperType().getName()); writer.printf(" extends %s", simpleName != null ? simpleName : genType(model.getConcreteSuperType())); } if (!superTypes.isEmpty()) { writer.printf(" implements %s", String.join(", ", superTypes)); } } else { if (model.isHandler()) { writer.printf(" extends Handler<%s>", genType(model.getHandlerArg())); if (!superTypes.isEmpty()) { writer.printf(", %s", String.join(", ", superTypes)); } } else { if (!superTypes.isEmpty()) { writer.printf(" extends %s", String.join(", ", superTypes)); } } } writer.print(" {\n"); boolean moreConstants = false; boolean hasConstantInInterface = !model.isConcrete() && model.getConstants().size() > 0; // this looks awkward (and it is) but TS does not allow static constants in interfaces // so they get listed on the abstract classes. if (model.isConcrete()) { for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } } boolean moreMethods = false; boolean hasStaticMethodsInInterface = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!model.isConcrete() && method.isStaticMethod()) { hasStaticMethodsInInterface = true; continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } // BEGIN of non polyglot methods... for (MethodInfo method : model.getAnyJavaTypeMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); // if the model is not concrete (interface) we need to merge types to allow declaring the constants // from the java interface if (hasConstantInInterface || hasStaticMethodsInInterface) { writer.print("\n"); writer.printf("export abstract class %s%s implements %s%s {\n", type.getSimpleName(), genGeneric(type.getParams()), type.getSimpleName(), genGeneric(type.getParams())); moreConstants = false; for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } moreMethods = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!method.isStaticMethod()) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); } if (index == size - 1) { // include a file if present writer.print(includeFileIfPresent("index.footer.d.ts")); } return sw.toString(); } #location 218 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String render(ClassModel model, int index, int size, Map<String, Object> session) { if (isExcludedClass(model.getType().getName())) { return null; } StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); ClassTypeInfo type = model.getType(); if (index == 0) { Util.generateLicense(writer); registerJvmClasses(); for (Object fqcn : jvmClasses("api")) { JVMClass.generateDTS(writer, fqcn.toString()); } // include a file if present writer.print(includeFileIfPresent("index.header.d.ts")); if (!type.getModuleName().equals("vertx")) { if (isOptionalModule("@vertx/core")) { writer.println("// @ts-ignore"); } // hard coded imports for non codegen types writer.print("import { Handler, AsyncResult } from '@vertx/core';\n\n"); } } else { writer.print("\n"); } boolean imports = false; @SuppressWarnings("unchecked") Map<String, String> aliasMap = (Map<String, String>) session.computeIfAbsent("aliasMap", (a) -> new HashMap<String, String>()); for (ApiTypeInfo referencedType : model.getReferencedTypes()) { if (!sameModule(type, referencedType.getRaw())) { String simpleName = referencedType.getSimpleName(); if (simpleName.equals(model.getIfaceSimpleName())) { String aliasName = simpleName + "Super"; simpleName = simpleName + " as " + aliasName; aliasMap.put(referencedType.getName(), aliasName); } importType(writer, session, referencedType, simpleName, getNPMScope(referencedType.getRaw().getModule())); imports = true; } } for (ClassTypeInfo dataObjectType : model.getReferencedDataObjectTypes()) { if (sameModule(type, dataObjectType.getRaw())) { importType(writer, session, dataObjectType, dataObjectType.getSimpleName(), "./options"); imports = true; } else { importType(writer, session, dataObjectType, dataObjectType.getSimpleName(), getNPMScope(dataObjectType.getRaw().getModule()) + "/options"); imports = true; } } for (EnumTypeInfo enumType : model.getReferencedEnumTypes()) { if (enumType.getRaw().getModuleName() == null) { System.err.println("@@@ Missing module for ENUM: " + enumType); continue; } if (sameModule(type, enumType.getRaw())) { importType(writer, session, enumType, enumType.getSimpleName(), "./enums"); imports = true; } else { importType(writer, session, enumType, enumType.getSimpleName(), getNPMScope(enumType.getRaw().getModule()) + "/enums"); imports = true; } } final Set<String> superTypes = new HashSet<>(); // ensure that all super types are also imported model.getAbstractSuperTypes().forEach(ti -> { if (!sameModule(type, ti.getRaw())) { importType(writer, session, ti, ti.getSimpleName(), getNPMScope(ti.getRaw().getModule())); } superTypes.add(genType(ti)); }); imports |= superTypes.size() > 0; if (model.isHandler()) { if (model.isConcrete()) { TypeInfo ti = model.getHandlerArg(); if (!sameModule(type, ti.getRaw())) { importType(writer, session, ti, ti.getSimpleName(), getNPMScope(ti.getRaw().getModule()) + (ti.isDataObjectHolder() ? "/options" : "")); imports = true; } superTypes.add("Handler<" + genType(ti) + ">"); } } if (imports) { writer.print("\n"); } generateDoc(writer, model.getDoc(), ""); writer.printf("export %s %s%s", model.isConcrete() ? "abstract class" : "interface", type.getSimpleName(), genGeneric(type.getParams())); if (model.isConcrete()) { if (model.getConcreteSuperType() != null) { String simpleName = aliasMap.get(model.getConcreteSuperType().getName()); writer.printf(" extends %s", simpleName != null ? simpleName : genType(model.getConcreteSuperType())); } if (!superTypes.isEmpty()) { writer.printf(" implements %s", String.join(", ", superTypes)); } } else { if (model.isHandler()) { writer.printf(" extends Handler<%s>", genType(model.getHandlerArg())); if (!superTypes.isEmpty()) { writer.printf(", %s", String.join(", ", superTypes)); } } else { if (!superTypes.isEmpty()) { writer.printf(" extends %s", String.join(", ", superTypes)); } } } writer.print(" {\n"); boolean moreConstants = false; boolean hasConstantInInterface = !model.isConcrete() && model.getConstants().size() > 0; // this looks awkward (and it is) but TS does not allow static constants in interfaces // so they get listed on the abstract classes. if (model.isConcrete()) { for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } } boolean moreMethods = false; boolean hasStaticMethodsInInterface = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!model.isConcrete() && method.isStaticMethod()) { hasStaticMethodsInInterface = true; continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } // BEGIN of non polyglot methods... for (MethodInfo method : model.getAnyJavaTypeMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); // if the model is not concrete (interface) we need to merge types to allow declaring the constants // from the java interface if (hasConstantInInterface || hasStaticMethodsInInterface) { writer.print("\n"); writer.printf("export abstract class %s%s implements %s%s {\n", type.getSimpleName(), genGeneric(type.getParams()), type.getSimpleName(), genGeneric(type.getParams())); moreConstants = false; for (ConstantInfo constant : model.getConstants()) { if (moreConstants) { writer.print("\n"); } generateDoc(writer, constant.getDoc(), " "); writer.printf(" static readonly %s : %s;\n", constant.getName(), genType(constant.getType())); moreConstants = true; } moreMethods = false; for (MethodInfo method : model.getMethods()) { if (isExcluded(type.getSimpleName(), method.getName(), method.getParams())) { continue; } if (!method.isStaticMethod()) { continue; } if (moreMethods || moreConstants) { writer.print("\n"); } generateMethod(writer, type, method); moreMethods = true; } writer.print("}\n"); } if (index == size - 1) { // include a file if present writer.print(includeFileIfPresent("index.footer.d.ts")); } return sw.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 != 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(); } #location 15 #vulnerability type NULL_DEREFERENCE
#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 boolean isGraalVM = System.getProperty("java.vm.name", "").toLowerCase().contains("graalvm") || // from graal 20.0.0 the vm name doesn't contain graalvm in the name // but it is now part of the vendor version System.getProperty("java.vendor.version", "").toLowerCase().contains("graalvm"); if (!isGraalVM) { // 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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void setUpClass() { application = new Application(); client = XmemcachedFactory.create(application.getPippoSettings()); } #location 4 #vulnerability type NULL_DEREFERENCE
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public TemplateEngine getTemplateEngine() { if (templateEngine == null) { TemplateEngine engine = ServiceLocator.locate(TemplateEngine.class); setTemplateEngine(engine); } return templateEngine; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public TemplateEngine getTemplateEngine() { return templateEngine; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void setUpClass() { application = new Application(); client = SpymemcachedFactory.create(application.getPippoSettings()); } #location 4 #vulnerability type NULL_DEREFERENCE
#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 MemcachedClient(new InetSocketAddress(HOST, PORT)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> toList(List<String> defaultValue) { if (isNull() || (values.length == 1 && StringUtils.isNullOrEmpty(values[0]))) { return defaultValue; } if (values.length == 1) { String tmp = values[0]; tmp = StringUtils.removeStart(tmp, "["); tmp = StringUtils.removeEnd(tmp, "]"); return Arrays.asList(tmp.split("(,|\\|)")); } return Arrays.asList(values); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public List<String> toList(List<String> defaultValue) { if (isNull() || (values.length == 1 && StringUtils.isNullOrEmpty(values[0]))) { return defaultValue; } if (values.length == 1) { String tmp = values[0]; tmp = StringUtils.removeStart(tmp, "["); tmp = StringUtils.removeEnd(tmp, "]"); return StringUtils.getList(tmp, "(,|\\|)"); } return Arrays.asList(values); }
Below is the vulnerable code, please generate the patch based on the following information.