output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public void testTarFileSet() throws Exception { project.executeTarget("tarfileset"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar.gz")) { TarInputStream tar = new TarInputStream(new GZIPInputStream(in)); TarEntry tarentry; while ((tarentry = tar.getNextEntry()) != null) { assertTrue("prefix", tarentry.getName().startsWith("/foo/")); if (tarentry.isDirectory()) { assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode()); } else { assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode()); } assertEquals("user", "ebourg", tarentry.getUserName()); assertEquals("group", "ebourg", tarentry.getGroupName()); } tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } }
#vulnerable code public void testTarFileSet() throws Exception { project.executeTarget("tarfileset"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar.gz")) { TarInputStream tar = new TarInputStream(new GZIPInputStream(in)); TarEntry tarentry; while ((tarentry = tar.getNextEntry()) != null) { assertTrue("prefix", tarentry.getName().startsWith("/foo/")); if (tarentry.isDirectory()) { assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode()); } else { assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode()); } assertEquals("user", "ebourg", tarentry.getUserName()); assertEquals("group", "ebourg", tarentry.getGroupName()); } } else { // skip to the next entry in.skip(entry.getLength()); } } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); final AtomicBoolean found = new AtomicBoolean(false); ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() { public void visit(TarArchiveEntry entry, byte[] content) throws IOException { found.set(true); } }, Compression.NONE); assertTrue("tar file not found", found.get()); }
#vulnerable code public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar")) { found = true; TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); while ((tar.getNextEntry()) != null) { ; } tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while (skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); assertTrue("tar file not found", found); } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException { int digest = PGPUtil.SHA1; PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest)); signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey); ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output); armoredOutput.beginClearText(digest); LineIterator iterator = new LineIterator(new InputStreamReader(input)); while (iterator.hasNext()) { String line = iterator.nextLine(); // trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1) byte[] data = trim(line).getBytes("UTF-8"); armoredOutput.write(data); armoredOutput.write(EOL); signatureGenerator.update(data); if (iterator.hasNext()) { signatureGenerator.update(EOL); } } armoredOutput.endClearText(); PGPSignature signature = signatureGenerator.generate(); signature.encode(new BCPGOutputStream(armoredOutput)); armoredOutput.close(); }
#vulnerable code public void clearSign(InputStream input, OutputStream output) throws IOException, PGPException, GeneralSecurityException { int digest = PGPUtil.SHA1; PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new BcPGPContentSignerBuilder(privateKey.getPublicKeyPacket().getAlgorithm(), digest)); signatureGenerator.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, privateKey); ArmoredOutputStream armoredOutput = new ArmoredOutputStream(output); armoredOutput.beginClearText(digest); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String line; while ((line = reader.readLine()) != null) { // trailing spaces must be removed for signature calculation (see http://tools.ietf.org/html/rfc4880#section-7.1) byte[] data = trim(line).getBytes("UTF-8"); armoredOutput.write(data); armoredOutput.write(EOL); signatureGenerator.update(data); signatureGenerator.update(EOL); } armoredOutput.endClearText(); PGPSignature signature = signatureGenerator.generate(); signature.encode(new BCPGOutputStream(armoredOutput)); armoredOutput.close(); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar")) { found = true; TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); assertTrue("tar file not found", found); }
#vulnerable code public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar")) { found = true; TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); assertTrue("tar file not found", found); } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void makeDeb() throws PackagingException { if (control == null || !control.isDirectory()) { throw new PackagingException( "\"" + control + "\" is not a valid 'control' directory)"); } if (changesIn != null) { if (!changesIn.isFile() || !changesIn.canRead()) { throw new PackagingException( "The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable."); } if (changesOut == null) { throw new PackagingException( "A 'changesIn' without a 'changesOut' does not make much sense."); } if (!isPossibleOutput(changesOut)) { throw new PackagingException( "Cannot write the output for 'changesOut' to " + changesOut); } if (changesSave != null && !isPossibleOutput(changesSave)) { throw new PackagingException( "Cannot write the output for 'changesSave' to " + changesSave); } } else { if (changesOut != null || changesSave != null) { throw new PackagingException( "The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified."); } } if (!"gzip".equals(compression) && !"bzip2".equals(compression) && !"none".equals(compression)) { throw new PackagingException("The compression method '" + compression + "' is not supported"); } if (dataProducers.size() == 0) { throw new PackagingException( "You need to provide at least one reference to a tgz or directory with data."); } if (deb == null) { throw new PackagingException( "You need to specify where the deb file is supposed to be created."); } final File[] controlFiles = control.listFiles(); final DataProducer[] data = new DataProducer[dataProducers.size()]; dataProducers.toArray(data); final Processor processor = new Processor(console, variableResolver); final PackageDescriptor packageDescriptor; try { console.println("Creating debian package: " + deb); packageDescriptor = processor.createDeb(controlFiles, data, deb, compression); } catch (Exception e) { throw new PackagingException("Failed to create debian package " + deb, e); } final TextfileChangesProvider changesProvider; try { if (changesOut == null) { return; } console.println("Creating changes file: " + changesOut); // for now only support reading the changes form a textfile provider changesProvider = new TextfileChangesProvider(new FileInputStream(changesIn), packageDescriptor); processor.createChanges(packageDescriptor, changesProvider, (keyring != null) ? new FileInputStream(keyring) : null, key, passphrase, new FileOutputStream(changesOut)); } catch (Exception e) { throw new PackagingException( "Failed to create debian changes file " + changesOut, e); } try { if (changesSave == null) { return; } console.println("Saving changes to file: " + changesSave); changesProvider.save(new FileOutputStream(changesSave)); } catch (Exception e) { throw new PackagingException("Failed to save debian changes file " + changesSave, e); } }
#vulnerable code public void makeDeb() throws PackagingException { if (control == null || !control.isDirectory()) { throw new PackagingException( "\"" + control + "\" is not a valid 'control' directory)"); } if (changesIn != null) { if (!changesIn.isFile() || !changesIn.canRead()) { throw new PackagingException( "The 'changesIn' setting needs to point to a readable file. " + changesIn + " was not found/readable."); } if (changesOut == null) { throw new PackagingException( "A 'changesIn' without a 'changesOut' does not make much sense."); } if (!isPossibleOutput(changesOut)) { throw new PackagingException( "Cannot write the output for 'changesOut' to " + changesOut); } if (changesSave != null && !isPossibleOutput(changesSave)) { throw new PackagingException( "Cannot write the output for 'changesSave' to " + changesSave); } } else { if (changesOut != null || changesSave != null) { throw new PackagingException( "The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified."); } } if (!"gzip".equals(compression) && !"bzip2".equals(compression) && !"none".equals(compression)) { throw new PackagingException("The compression method '" + compression + "' is not supported"); } if (dataProducers.size() == 0) { throw new PackagingException( "You need to provide at least one reference to a tgz or directory with data."); } if (deb == null) { throw new PackagingException( "You need to specify where the deb file is supposed to be created."); } final File[] controlFiles = control.listFiles(); console.println("control dir:" + control); for(File file : controlFiles) { console.println("-" + file); } final DataProducer[] data = new DataProducer[dataProducers.size()]; dataProducers.toArray(data); final Processor processor = new Processor(console, variableResolver); final PackageDescriptor packageDescriptor; try { console.println("Creating debian package: " + deb); packageDescriptor = processor.createDeb(controlFiles, data, deb, compression); } catch (Exception e) { throw new PackagingException("Failed to create debian package " + deb, e); } final TextfileChangesProvider changesProvider; try { if (changesOut == null) { return; } console.println("Creating changes file: " + changesOut); // for now only support reading the changes form a textfile provider changesProvider = new TextfileChangesProvider(new FileInputStream( changesIn), packageDescriptor); processor.createChanges(packageDescriptor, changesProvider, (keyring != null) ? new FileInputStream(keyring) : null, key, passphrase, new FileOutputStream(changesOut)); } catch (Exception e) { throw new PackagingException( "Failed to create debian changes file " + changesOut, e); } try { if (changesSave == null) { return; } console.println("Saving changes to file: " + changesSave); changesProvider.save(new FileOutputStream(changesSave)); } catch (Exception e) { throw new PackagingException("Failed to save debian changes file " + changesSave, e); } } #location 59 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuffer pChecksums, final File pOutput ) throws FileNotFoundException, IOException, ParseException { PackageDescriptor packageDescriptor = null; final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput))); outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU); for (int i = 0; i < pControlFiles.length; i++) { final File file = pControlFiles[i]; if (file.isDirectory()) { continue; } final TarEntry entry = new TarEntry(file); final String name = file.getName(); entry.setName(name); if ("control".equals(name)) { packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver); if (packageDescriptor.get("Date") == null) { packageDescriptor.set("Date", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date())); // Mon, 26 Mar 2007 11:44:04 +0200 } if (packageDescriptor.get("Distribution") == null) { packageDescriptor.set("Distribution", "unknown"); } if (packageDescriptor.get("Urgency") == null) { packageDescriptor.set("Urgency", "low"); } if (packageDescriptor.get("Maintainer") == null) { final String debFullName = System.getenv("DEBFULLNAME"); final String debEmail = System.getenv("DEBEMAIL"); if (debFullName != null && debEmail != null) { packageDescriptor.set("Maintainer", debFullName + " <" + debEmail + ">"); } } continue; } final InputStream inputStream = new FileInputStream(file); outputStream.putNextEntry(entry); Utils.copy(inputStream, outputStream); outputStream.closeEntry(); inputStream.close(); } if (packageDescriptor == null) { throw new FileNotFoundException("No control file in " + Arrays.toString(pControlFiles)); } packageDescriptor.set("Installed-Size", pDataSize.toString()); addEntry("control", packageDescriptor.toString(), outputStream); addEntry("md5sums", pChecksums.toString(), outputStream); outputStream.close(); return packageDescriptor; }
#vulnerable code private PackageDescriptor buildControl( final File[] pControlFiles, final BigInteger pDataSize, final StringBuffer pChecksums, final File pOutput ) throws FileNotFoundException, IOException, ParseException { PackageDescriptor packageDescriptor = null; final TarOutputStream outputStream = new TarOutputStream(new GZIPOutputStream(new FileOutputStream(pOutput))); outputStream.setLongFileMode(TarOutputStream.LONGFILE_GNU); for (int i = 0; i < pControlFiles.length; i++) { final File file = pControlFiles[i]; if (file.isDirectory()) { continue; } final TarEntry entry = new TarEntry(file); final String name = file.getName(); entry.setName(name); if ("control".equals(name)) { packageDescriptor = new PackageDescriptor(new FileInputStream(file)); if (packageDescriptor.get("Date") == null) { packageDescriptor.set("Date", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").format(new Date())); // Mon, 26 Mar 2007 11:44:04 +0200 } if (packageDescriptor.get("Distribution") == null) { packageDescriptor.set("Distribution", "unknown"); } if (packageDescriptor.get("Urgency") == null) { packageDescriptor.set("Urgency", "low"); } if (packageDescriptor.get("Maintainer") == null) { final String debFullName = System.getenv("DEBFULLNAME"); final String debEmail = System.getenv("DEBEMAIL"); if (debFullName != null && debEmail != null) { packageDescriptor.set("Maintainer", debFullName + " <" + debEmail + ">"); } } continue; } final InputStream inputStream = new FileInputStream(file); outputStream.putNextEntry(entry); Utils.copy(inputStream, outputStream); outputStream.closeEntry(); inputStream.close(); } if (packageDescriptor == null) { throw new FileNotFoundException("No control file in " + Arrays.toString(pControlFiles)); } packageDescriptor.set("Installed-Size", pDataSize.toString()); addEntry("control", packageDescriptor.toString(), outputStream); addEntry("md5sums", pChecksums.toString(), outputStream); outputStream.close(); return packageDescriptor; } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCreation() throws Exception { final Processor processor = new Processor(new NullConsole(), null); final File control = new File(getClass().getResource("deb/control/control").toURI()); final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI()); final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI()); final File archive3 = new File(getClass().getResource("deb/data.zip").toURI()); final File directory = new File(getClass().getResource("deb/data").toURI()); final DataProducer[] data = new DataProducer[] { new DataProducerArchive(archive1, null, null, null), new DataProducerArchive(archive2, null, null, null), new DataProducerArchive(archive3, null, null, null), new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null), new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, Compression.GZIP); assertTrue(packageDescriptor.isValid()); final Map<String, TarArchiveEntry> filesInDeb = new HashMap<String, TarArchiveEntry>(); ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() { public void visit(TarArchiveEntry entry, byte[] content) throws IOException { filesInDeb.put(entry.getName(), entry); } }, Compression.GZIP); assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile")); assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2")); assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3")); assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4")); assertTrue("/link/path-element.ext wasn't found in the package", filesInDeb.containsKey("./link/path-element.ext")); assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext", filesInDeb.get("./link/path-element.ext").getLinkName()); assertTrue("Cannot delete the file " + deb, deb.delete()); }
#vulnerable code public void testCreation() throws Exception { final Processor processor = new Processor(new NullConsole(), null); final File control = new File(getClass().getResource("deb/control/control").toURI()); final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI()); final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI()); final File archive3 = new File(getClass().getResource("deb/data.zip").toURI()); final File directory = new File(getClass().getResource("deb/data").toURI()); final DataProducer[] data = new DataProducer[] { new DataProducerArchive(archive1, null, null, null), new DataProducerArchive(archive2, null, null, null), new DataProducerArchive(archive3, null, null, null), new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null), new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, Compression.GZIP); assertTrue(packageDescriptor.isValid()); final Map<String, TarEntry> filesInDeb = new HashMap<String, TarEntry>(); final ArArchiveInputStream ar = new ArArchiveInputStream(new FileInputStream(deb)); while (true) { final ArArchiveEntry arEntry = ar.getNextArEntry(); if (arEntry == null) { break; } if ("data.tar.gz".equals(arEntry.getName())) { final TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(ar))); while (true) { final TarEntry tarEntry = tar.getNextEntry(); if (tarEntry == null) { break; } filesInDeb.put(tarEntry.getName(), tarEntry); } tar.close(); break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } ar.close(); assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile")); assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2")); assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3")); assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4")); assertTrue("/link/path-element.ext wasn't found in the package", filesInDeb.containsKey("./link/path-element.ext")); assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext", filesInDeb.get("./link/path-element.ext").getLinkName()); assertTrue("Cannot delete the file " + deb, deb.delete()); } #location 36 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void parse( final InputStream pInput ) throws IOException, ParseException { final BufferedReader br = new BufferedReader(new InputStreamReader(pInput, "UTF-8")); StringBuilder buffer = new StringBuilder(); String key = null; int linenr = 0; while (true) { final String line = br.readLine(); if (line == null) { if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = null; } break; } linenr++; if (line.length() == 0) { throw new ParseException("Empty line", linenr); } final char first = line.charAt(0); if (Character.isLetter(first)) { // new key if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = new StringBuilder(); } final int i = line.indexOf(':'); if (i < 0) { throw new ParseException("Line misses ':' delimiter", linenr); } key = line.substring(0, i); buffer.append(line.substring(i + 1).trim()); continue; } // continuing old value buffer.append('\n').append(line.substring(1)); } br.close(); }
#vulnerable code protected void parse( final InputStream pInput ) throws IOException, ParseException { final BufferedReader br = new BufferedReader(new InputStreamReader(pInput)); StringBuilder buffer = new StringBuilder(); String key = null; int linenr = 0; while (true) { final String line = br.readLine(); if (line == null) { if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = null; } break; } linenr++; if (line.length() == 0) { throw new ParseException("Empty line", linenr); } final char first = line.charAt(0); if (Character.isLetter(first)) { // new key if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = new StringBuilder(); } final int i = line.indexOf(':'); if (i < 0) { throw new ParseException("Line misses ':' delimiter", linenr); } key = line.substring(0, i); buffer.append(line.substring(i + 1).trim()); continue; } // continuing old value buffer.append('\n').append(line.substring(1)); } br.close(); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void unpackDependencies() throws MojoExecutionException { ExecutionEnvironment executionEnvironment = executionEnvironment(mavenProject, mavenSession, buildPluginManager); // try { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("3.0.1") ), goal("unpack"), configuration( element("artifact", LOADER_JAR_GAV), element("excludes", "META-INF/**"), element("outputDirectory", "${project.build.directory}/classes") ), executionEnvironment ); // } catch (MojoExecutionException e) { // unpackDependenciesFallback(); // } }
#vulnerable code private void unpackDependencies() throws MojoExecutionException { try { // get plugin JAR String pluginJarPath = getPluginJarPath(); JarFile pluginJar = new JarFile(new File(pluginJarPath)); // extract loader JAR from plugin JAR JarEntry pluginJarloaderJarEntry = pluginJar.getJarEntry(LOADER_JAR); InputStream loaderJarInputStream = pluginJar.getInputStream(pluginJarloaderJarEntry); File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), "EeBootLoader"); if (!tmpDirectory.exists()) { tmpDirectory.mkdir(); } chmod777(tmpDirectory); File tmpLoaderJarFile = File.createTempFile(TEMP_DIR_NAME_PREFIX, null, tmpDirectory); tmpLoaderJarFile.deleteOnExit(); chmod777(tmpLoaderJarFile); FileUtils.copyInputStreamToFile(loaderJarInputStream, tmpLoaderJarFile); // extract loader JAR contents JarFile loaderJar = new JarFile(tmpLoaderJarFile); loaderJar .stream() .parallel() .filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX)) .forEach(loaderJarEntry -> { try { File file = new File(mavenProject.getBuild().getDirectory(), "classes/" + loaderJarEntry.getName()); if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } InputStream inputStream = loaderJar.getInputStream(loaderJarEntry); FileUtils.copyInputStreamToFile(inputStream, file); } catch (IOException e) { // ignore } }); loaderJar.close(); } catch (IOException e) { throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + "."); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void unpackDependencies() throws MojoExecutionException { getLog().info("Unpacking kumuluzee-loader dependency."); try { // get plugin JAR String pluginJarPath = getPluginJarPath(); Path pluginJarFile = Paths.get(pluginJarPath); FileSystem pluginJarFs = FileSystems.newFileSystem(pluginJarFile, null); Path loaderJarFile = pluginJarFs.getPath(LOADER_JAR); Path tmpJar = Files.createTempFile(TEMP_DIR_NAME_PREFIX, ".tmp"); Files.copy(loaderJarFile, tmpJar, StandardCopyOption.REPLACE_EXISTING); JarFile loaderJar = new JarFile(tmpJar.toFile()); loaderJar.stream().parallel() .filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX)) .forEach(loaderJarEntry -> { try { Path outputPath = Paths.get(outputDirectory, loaderJarEntry.getName()); Path outputPathParent = outputPath.getParent(); if (outputPathParent != null) { Files.createDirectories(outputPathParent); } InputStream inputStream = loaderJar.getInputStream(loaderJarEntry); Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING); inputStream.close(); } catch (IOException ignored) { } }); loaderJar.close(); Files.delete(tmpJar); } catch (IOException e) { throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + "."); } }
#vulnerable code private void unpackDependencies() throws MojoExecutionException { getLog().info("Unpacking kumuluzee-loader dependency."); try { // get plugin JAR String pluginJarPath = getPluginJarPath(); JarFile pluginJar = new JarFile(new File(pluginJarPath)); // extract loader JAR from plugin JAR JarEntry pluginJarloaderJarEntry = pluginJar.getJarEntry(LOADER_JAR); InputStream loaderJarInputStream = pluginJar.getInputStream(pluginJarloaderJarEntry); File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), "EeBootLoader"); if (!tmpDirectory.exists()) { tmpDirectory.mkdir(); } chmod777(tmpDirectory); File tmpLoaderJarFile = File.createTempFile(TEMP_DIR_NAME_PREFIX, null, tmpDirectory); tmpLoaderJarFile.deleteOnExit(); chmod777(tmpLoaderJarFile); FileUtils.copyInputStreamToFile(loaderJarInputStream, tmpLoaderJarFile); // extract loader JAR contents JarFile loaderJar = new JarFile(tmpLoaderJarFile); loaderJar .stream() .parallel() .filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX)) .forEach(loaderJarEntry -> { try { File file = new File(outputDirectory, "classes" + File.separator + loaderJarEntry.getName()); if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } InputStream inputStream = loaderJar.getInputStream(loaderJarEntry); FileUtils.copyInputStreamToFile(inputStream, file); } catch (IOException e) { // ignore } }); loaderJar.close(); } catch (IOException e) { throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + "."); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void sendError(final int sc, final String msg) throws IOException { if (exchange.getExchange().isResponseStarted()) { throw UndertowServletMessages.MESSAGES.responseAlreadyCommited(); } resetBuffer(); writer = null; responseState = ResponseState.NONE; exchange.getExchange().setResponseCode(sc); //todo: is this the best way to handle errors? final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc); if (location != null) { RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext); try { requestDispatcher.error(exchange.getExchange().getAttachment(HttpServletRequestImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(HttpServletResponseImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(ServletInitialHandler.CURRENT_SERVLET).getName(), msg); } catch (ServletException e) { throw new RuntimeException(e); } } else if (msg != null) { setContentType("text/html"); getWriter().write(msg); getWriter().close(); } responseDone(exchange.getCompletionHandler()); }
#vulnerable code @Override public void sendError(final int sc, final String msg) throws IOException { if (exchange.getExchange().isResponseStarted()) { throw UndertowServletMessages.MESSAGES.responseAlreadyCommited(); } if (servletOutputStream != null) { servletOutputStream.resetBuffer(); } writer = null; responseState = ResponseState.NONE; exchange.getExchange().setResponseCode(sc); //todo: is this the best way to handle errors? final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc); if (location != null) { RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext); try { requestDispatcher.error(exchange.getExchange().getAttachment(HttpServletRequestImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(HttpServletResponseImpl.ATTACHMENT_KEY), exchange.getExchange().getAttachment(ServletInitialHandler.CURRENT_SERVLET).getName(), msg); } catch (ServletException e) { throw new RuntimeException(e); } responseDone(exchange.getCompletionHandler()); } else if (msg != null) { setContentType("text/html"); getWriter().write(msg); getWriter().close(); } } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected StreamSinkFrameChannel create(StreamSinkChannel channel, WebSocketFrameType type, long payloadSize) { switch (type) { case TEXT: return new WebSocket08TextFrameSinkChannel(channel, this, payloadSize); case BINARY: return new WebSocket08BinaryFrameSinkChannel(channel, this, payloadSize); case CLOSE: return new WebSocket08CloseFrameSinkChannel(channel, this, payloadSize); case PONG: return new WebSocket08PongFrameSinkChannel(channel, this, payloadSize); case PING: return new WebSocket08PingFrameSinkChannel(channel, this, payloadSize); case CONTINUATION: return new WebSocket08ContinuationFrameSinkChannel(channel, this, payloadSize); default: throw new IllegalArgumentException("WebSocketFrameType " + type + " is not supported by this WebSocketChannel"); } }
#vulnerable code @Override protected StreamSinkFrameChannel create(StreamSinkChannel channel, WebSocketFrameType type, long payloadSize) { return new WebSocket08FrameSinkChannel(channel, this, type, payloadSize); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public HttpSession getSession(final boolean create) { return servletContext.getSession(exchange.getExchange(), create); }
#vulnerable code @Override public HttpSession getSession(final boolean create) { if (httpSession == null) { Session session = exchange.getExchange().getAttachment(Session.ATTACHMENT_KEY); if (session != null) { httpSession = new HttpSessionImpl(session, servletContext, servletContext.getDeployment().getApplicationListeners(), exchange.getExchange(), false); } else if (create) { final SessionManager sessionManager = exchange.getExchange().getAttachment(SessionManager.ATTACHMENT_KEY); try { Session newSession = sessionManager.getOrCreateSession(exchange.getExchange()).get(); httpSession = new HttpSessionImpl(newSession, servletContext, servletContext.getDeployment().getApplicationListeners(), exchange.getExchange(), true); servletContext.getDeployment().getApplicationListeners().sessionCreated(httpSession); } catch (IOException e) { throw new RuntimeException(e); } } } return httpSession; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("/start") @Metric(HTTP_STOP_OTA) public Response startOTA(@QueryParam("fileName") String filename, @QueryParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return badRequest("Invalid token."); } User user = tokenValue.user; int deviceId = tokenValue.deviceId; if (user == null) { return badRequest("Invalid auth credentials."); } Session session = sessionDao.userSession.get(new UserKey(user)); if (session == null) { log.debug("No session for user {}.", user.email); return badRequest("Device wasn't connected yet."); } String otaFile = OTA_DIR + (filename == null ? "firmware_ota.bin" : filename); String body = otaManager.buildOTAInitCommandBody(otaFile); if (session.sendMessageToHardware(BLYNK_INTERNAL, 7777, body)) { log.debug("No device in session."); return badRequest("No device in session."); } Device device = tokenValue.dash.getDeviceById(deviceId); device.updateOTAInfo(user.email); return ok(); }
#vulnerable code @GET @Path("/start") @Metric(HTTP_STOP_OTA) public Response startOTA(@QueryParam("fileName") String filename, @QueryParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return badRequest("Invalid token."); } User user = tokenValue.user; int dashId = tokenValue.dashId; int deviceId = tokenValue.deviceId; if (user == null) { return badRequest("Invalid auth credentials."); } Session session = sessionDao.userSession.get(new UserKey(user)); if (session == null) { log.debug("No session for user {}.", user.email); return badRequest("Device wasn't connected yet."); } String otaFile = OTA_DIR + (filename == null ? "firmware_ota.bin" : filename); String body = otaManager.buildOTAInitCommandBody(otaFile); if (session.sendMessageToHardware(BLYNK_INTERNAL, 7777, body)) { log.debug("No device in session."); return badRequest("No device in session."); } DashBoard dash = user.profile.getDashById(dashId); Device device = dash.getDeviceById(deviceId); device.updateOTAInfo(user.email); return ok(); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetWithFakeToken() throws Exception { String token = "4ae3851817194e2596cf1b7103603ef8"; HttpGet request = new HttpGet(httpsServerUrl + token + "/project"); InputStream is = getClass().getResourceAsStream("/profiles/[email protected]"); User user = JsonParser.mapper.readValue(is, User.class); Integer dashId = getDashIdByToken(user.dashTokens, token, 0); dashBoard = user.profile.getDashById(dashId); try (CloseableHttpResponse response = httpclient.execute(request)) { assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(dashBoard.toString(), consumeText(response)); } }
#vulnerable code @Test public void testGetWithFakeToken() throws Exception { String token = "4ae3851817194e2596cf1b7103603ef8"; HttpGet request = new HttpGet(httpsServerUrl + token + "/project"); InputStream is = getClass().getResourceAsStream("/profiles/[email protected]"); User user = JsonParser.mapper.readValue(is, User.class); Integer dashId = user.getDashIdByToken(token); dashBoard = user.profile.getDashById(dashId); try (CloseableHttpResponse response = httpclient.execute(request)) { assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(dashBoard.toString(), consumeText(response)); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void channelRead0(ChannelHandlerContext ctx, SaveProfileMessage message) throws Exception { String userProfileString = message.body; //expecting message with 2 parts if (userProfileString == null || userProfileString.equals("")) { throw new InvalidCommandFormatException("Save Profile Handler. Income profile message is empty.", message.id); } log.info("Trying to parseProfile user profile : {}", userProfileString); UserProfile userProfile = JsonParser.parseProfile(userProfileString); if (userProfile == null) { throw new InvalidCommandFormatException("Register Handler. Wrong user profile message format.", message.id); } log.info("Trying save user profile."); User authUser = Session.findUserByChannel(ctx.channel(), message.id); authUser.setUserProfile(userProfile); boolean profileSaved = fileManager.overrideUserFile(authUser); if (profileSaved) { ctx.writeAndFlush(produce(message.id, OK)); } else { ctx.writeAndFlush(produce(message.id, SERVER_ERROR)); } }
#vulnerable code @Override protected void channelRead0(ChannelHandlerContext ctx, SaveProfileMessage message) throws Exception { String userProfileString = message.body; //expecting message with 2 parts if (userProfileString == null || userProfileString.equals("")) { log.error("Save Profile Handler. Income profile message is empty."); ctx.writeAndFlush(produce(message.id, INVALID_COMMAND_FORMAT)); return; } log.info("Trying to parseProfile user profile : {}", userProfileString); UserProfile userProfile = JsonParser.parseProfile(userProfileString); if (userProfile == null) { log.error("Register Handler. Wrong user profile message format."); ctx.writeAndFlush(produce(message.id, INVALID_COMMAND_FORMAT)); return; } log.info("Trying save user profile."); User authUser = Session.findUserByChannel(ctx.channel()); authUser.setUserProfile(userProfile); boolean profileSaved = fileManager.overrideUserFile(authUser); if (profileSaved) { ctx.writeAndFlush(produce(message.id, OK)); } else { ctx.writeAndFlush(produce(message.id, SERVER_ERROR)); } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void messageReceived(ChannelHandlerContext ctx, Message message) { String token = message.body; User userThatShared = userDao.sharedTokenManager.getUserByToken(token); if (userThatShared == null) { throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id); } Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token); if (dashId == null) { throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id); } DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId, message.id); cleanPrivateData(dashBoard); ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString())); }
#vulnerable code public void messageReceived(ChannelHandlerContext ctx, Message message) { String token = message.body; User userThatShared = userDao.sharedTokenManager.getUserByToken(token); if (userThatShared == null) { throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id); } Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token); if (dashId == null) { throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id); } DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId); cleanPrivateData(dashBoard); ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString())); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void channelRead0(ChannelHandlerContext ctx, GetTokenMessage message) throws Exception { String dashBoardIdString = message.body; Long dashBoardId; try { dashBoardId = Long.parseLong(dashBoardIdString); } catch (NumberFormatException ex) { throw new InvalidCommandFormatException(String.format("Dash board id %s not valid.", dashBoardIdString), message.id); } User user = Session.findUserByChannel(ctx.channel(), message.id); String token = userRegistry.getToken(user, dashBoardId); ctx.writeAndFlush(produce(message.id, message.command, token)); }
#vulnerable code @Override protected void channelRead0(ChannelHandlerContext ctx, GetTokenMessage message) throws Exception { String dashBoardIdString = message.body; Long dashBoardId; try { dashBoardId = Long.parseLong(dashBoardIdString); } catch (NumberFormatException ex) { log.error("Dash board id {} not valid.", dashBoardIdString); ctx.writeAndFlush(produce(message.id, INVALID_COMMAND_FORMAT)); return; } User user = Session.findUserByChannel(ctx.channel()); String token = userRegistry.getToken(user, dashBoardId); ctx.writeAndFlush(produce(message.id, message.command, token)); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void messageReceived(ChannelHandlerContext ctx, HardwareStateHolder state, StringMessage message) { Session session = sessionDao.userSession.get(state.user); String[] bodyParts = message.body.split(StringUtils.BODY_SEPARATOR_STRING); if (bodyParts.length != 3) { log.error("SetWidgetProperty command body has wrong format. {}", message.body); ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); return; } byte pin = ParseUtil.parseByte(bodyParts[0]); String property = bodyParts[1]; String propertyValue = bodyParts[2]; if (property.length() == 0 || propertyValue.length() == 0) { log.error("SetWidgetProperty command body has wrong format. {}", message.body); ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); return; } DashBoard dash = state.user.profile.getDashByIdOrThrow(state.dashId); //for now supporting only virtual pins Widget widget = dash.findWidgetByPin(pin, PinType.VIRTUAL); if (widget == null) { log.error("No widget for SetWidgetProperty command. {}", message.body); ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); return; } boolean isChanged; try { isChanged = ReflectionUtil.setProperty(widget, property, propertyValue); } catch (Exception e) { log.error("Error setting widget property. Reason : {}", e.getMessage()); ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); return; } if (isChanged) { if (dash.isActive) { session.sendToApps(SET_WIDGET_PROPERTY, message.id, dash.id + StringUtils.BODY_SEPARATOR_STRING + message.body); } ctx.writeAndFlush(ok(message.id), ctx.voidPromise()); } else { ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); } }
#vulnerable code public void messageReceived(ChannelHandlerContext ctx, HardwareStateHolder state, StringMessage message) { Session session = sessionDao.userSession.get(state.user); String[] bodyParts = message.body.split(StringUtils.BODY_SEPARATOR_STRING); if (bodyParts.length != 3) { throw new IllegalCommandException("SetWidgetProperty command body has wrong format."); } byte pin = ParseUtil.parseByte(bodyParts[0]); String property = bodyParts[1]; String propertyValue = bodyParts[2]; if (property.length() == 0 || propertyValue.length() == 0) { throw new IllegalCommandException("SetWidgetProperty command body has wrong format."); } DashBoard dash = state.user.profile.getDashByIdOrThrow(state.dashId); //for now supporting only virtual pins Widget widget = dash.findWidgetByPin(pin, PinType.VIRTUAL); boolean isChanged; try { isChanged = ReflectionUtil.setProperty(widget, property, propertyValue); } catch (Exception e) { log.error("Error setting widget property. Reason : {}", e.getMessage()); ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); return; } if (isChanged) { if (dash.isActive) { session.sendToApps(SET_WIDGET_PROPERTY, message.id, dash.id + StringUtils.BODY_SEPARATOR_STRING + message.body); } ctx.writeAndFlush(ok(message.id), ctx.voidPromise()); } else { ctx.writeAndFlush(makeResponse(message.id, ILLEGAL_COMMAND_BODY), ctx.voidPromise()); } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { TokenManager tokenManager = new TokenManager(new ConcurrentHashMap<>(), null, null, ""); String email = "[email protected]"; String pass = "b"; String appName = AppName.BLYNK; User user = new User(email, SHA256Util.makeHash(pass, email), appName, "local", false, false); user.purchaseEnergy(98000); int count = 300; user.profile.dashBoards = new DashBoard[count]; for (int i = 1; i <= count; i++) { DashBoard dash = new DashBoard(); dash.id = i; dash.theme = Theme.Blynk; dash.isActive = true; user.profile.dashBoards[i - 1] = dash; } List<String> tokens = new ArrayList<>(); for (int i = 1; i <= count; i++) { //tokens.add(tokenManager.refreshToken(user, i, 0)); } write("/path/300_tokens.txt", tokens); write(Paths.get("/path/" + email + "." + appName + ".user"), JsonParser.toJson(user)); //scp /path/[email protected] root@IP:/root/data/ }
#vulnerable code public static void main(String[] args) throws Exception { TokenManager tokenManager = new TokenManager(new ConcurrentHashMap<>(), null, null, ""); String email = "[email protected]"; String pass = "b"; String appName = AppName.BLYNK; User user = new User(email, SHA256Util.makeHash(pass, email), appName, "local", false, false); user.purchaseEnergy(98000); int count = 300; user.profile.dashBoards = new DashBoard[count]; for (int i = 1; i <= count; i++) { DashBoard dash = new DashBoard(); dash.id = i; dash.theme = Theme.Blynk; dash.isActive = true; user.profile.dashBoards[i - 1] = dash; } List<String> tokens = new ArrayList<>(); for (int i = 1; i <= count; i++) { tokens.add(tokenManager.refreshToken(user, i, 0)); } write("/path/300_tokens.txt", tokens); write(Paths.get("/path/" + email + "." + appName + ".user"), JsonParser.toJson(user)); //scp /path/[email protected] root@IP:/root/data/ } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return badRequest("Invalid token."); } User user = tokenValue.user; int dashId = tokenValue.dash.id; int deviceId = tokenValue.device.id; Session session = sessionDao.userSession.get(new UserKey(user)); if (session == null) { log.debug("No session for user {}.", user.email); return badRequest("Device wasn't connected yet."); } String body = otaManager.buildOTAInitCommandBody(path); if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) { log.debug("No device in session."); return badRequest("No device in session."); } User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get(); if (initiator != null) { tokenValue.device.updateOTAInfo(initiator.email); } return ok(path); }
#vulnerable code private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return badRequest("Invalid token."); } User user = tokenValue.user; int dashId = tokenValue.dash.id; int deviceId = tokenValue.deviceId; Session session = sessionDao.userSession.get(new UserKey(user)); if (session == null) { log.debug("No session for user {}.", user.email); return badRequest("Device wasn't connected yet."); } String body = otaManager.buildOTAInitCommandBody(path); if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) { log.debug("No device in session."); return badRequest("No device in session."); } Device device = tokenValue.dash.getDeviceById(deviceId); User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get(); if (initiator != null) { device.updateOTAInfo(initiator.email); } return ok(path); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void messageReceived(ChannelHandlerContext ctx, Message message) { String token = message.body; User userThatShared = userRegistry.sharedTokenManager.getUserByToken(token); if (userThatShared == null) { throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id); } Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token); if (dashId == null) { throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id); } DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId); cleanPrivateData(dashBoard); ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString())); }
#vulnerable code public void messageReceived(ChannelHandlerContext ctx, Message message) { String token = message.body; User userThatShared = userRegistry.sharedTokenManager.getUserByToken(token); if (userThatShared == null) { throw new InvalidTokenException("Illegal sharing token. No user with those shared token.", message.id); } Integer dashId = getSharedDashId(userThatShared.dashShareTokens, token); if (dashId == null) { throw new InvalidTokenException("Illegal sharing token. User has not token. Could happen only in rare cases.", message.id); } DashBoard dashBoard = userThatShared.profile.getDashboardById(dashId); ctx.writeAndFlush(produce(message.id, message.command, dashBoard.toString())); } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDeleteCommand() throws IOException { StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager()); ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>(); long ts = getTS() / AverageAggregator.HOUR; AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); AggregationValue aggregationValue = new AggregationValue(); aggregationValue.update(100); AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); AggregationValue aggregationValue2 = new AggregationValue(); aggregationValue2.update(150.54); AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts); AggregationValue aggregationValue3 = new AggregationValue(); aggregationValue3.update(200); map.put(aggregationKey, aggregationValue); map.put(aggregationKey2, aggregationValue2); map.put(aggregationKey3, aggregationValue3); when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); when(averageAggregator.getHourly()).thenReturn(map); when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); when(properties.getProperty("data.folder")).thenReturn(System.getProperty("java.io.tmpdir")); storageWorker.run(); assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY)))); new ReportingDao(reportingFolder, null, properties).delete("test", 1, PinType.ANALOG, (byte) 1); assertFalse(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); }
#vulnerable code @Test public void testDeleteCommand() throws IOException { StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null)); ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>(); long ts = getTS() / AverageAggregator.HOUR; AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); AggregationValue aggregationValue = new AggregationValue(); aggregationValue.update(100); AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); AggregationValue aggregationValue2 = new AggregationValue(); aggregationValue2.update(150.54); AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts); AggregationValue aggregationValue3 = new AggregationValue(); aggregationValue3.update(200); map.put(aggregationKey, aggregationValue); map.put(aggregationKey2, aggregationValue2); map.put(aggregationKey3, aggregationValue3); when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); when(averageAggregator.getHourly()).thenReturn(map); when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); when(properties.getProperty("data.folder")).thenReturn(System.getProperty("java.io.tmpdir")); storageWorker.run(); assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY)))); new ReportingDao(reportingFolder, null, properties).delete("test", 1, PinType.ANALOG, (byte) 1); assertFalse(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code RegularTokenManager(Iterable<User> users) { this.cache = new ConcurrentHashMap<String, TokenValue>() {{ for (User user : users) { if (user.profile != null) { for (DashBoard dashBoard : user.profile.dashBoards) { for (Device device : dashBoard.devices) { if (device.token != null) { put(device.token, new TokenValue(user, dashBoard, device)); } } } } } }}; }
#vulnerable code String assignToken(User user, int dashId, int deviceId, String newToken) { // Clean old token from cache if exists. DashBoard dash = user.profile.getDashByIdOrThrow(dashId); Device device = dash.getDeviceById(deviceId); String oldToken = deleteDeviceToken(device); //assign new token device.token = newToken; cache.put(newToken, new TokenValue(user, dash, device)); user.lastModifiedTs = System.currentTimeMillis(); log.debug("Generated token for user {}, dashId {}, deviceId {} is {}.", user.email, dashId, deviceId, newToken); return oldToken; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @POST @Path("{token}/email") @Consumes(value = MediaType.APPLICATION_JSON) public Response email(@PathParam("token") String token, EmailPojo message) { globalStats.mark(HTTP_EMAIL); TokenValue tokenValue = tokenManager.getUserByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } DashBoard dash = tokenValue.user.profile.getDashById(tokenValue.dashId); if (dash == null || !dash.isActive) { log.debug("Project is not active."); return Response.badRequest("Project is not active."); } Mail mail = dash.getWidgetByType(Mail.class); if (mail == null) { log.debug("No email widget."); return Response.badRequest("No email widget."); } if (message == null || message.subj == null || message.subj.equals("") || message.to == null || message.to.equals("")) { log.debug("Email body empty. '{}'", message); return Response.badRequest("Email body is wrong. Missing or empty fields 'to', 'subj'."); } log.trace("Sending Mail for user {}, with message : '{}'.", tokenValue.user.name, message.subj); mail(tokenValue.user.name, message.to, message.subj, message.title); return Response.ok(); }
#vulnerable code @POST @Path("{token}/email") @Consumes(value = MediaType.APPLICATION_JSON) public Response email(@PathParam("token") String token, EmailPojo message) { globalStats.mark(HTTP_EMAIL); User user = tokenManager.getUserByToken(token); if (user == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } Integer dashId = user.getDashIdByToken(token); if (dashId == null) { log.debug("Dash id for token {} not found. User {}", token, user.name); return Response.badRequest("Didn't find dash id for token."); } DashBoard dash = user.profile.getDashById(dashId); if (!dash.isActive) { log.debug("Project is not active."); return Response.badRequest("Project is not active."); } Mail mail = dash.getWidgetByType(Mail.class); if (mail == null) { log.debug("No email widget."); return Response.badRequest("No email widget."); } if (message == null || message.subj == null || message.subj.equals("") || message.to == null || message.to.equals("")) { log.debug("Email body empty. '{}'", message); return Response.badRequest("Email body is wrong. Missing or empty fields 'to', 'subj'."); } log.trace("Sending Mail for user {}, with message : '{}'.", user.name, message.subj); mail(user.name, message.to, message.subj, message.title); return Response.ok(); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("{token}/pin/{pin}") @Metric(HTTP_GET_PIN_DATA) public Response getWidgetPinData(@PathParam("token") String token, @PathParam("pin") String pinString) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } User user = tokenValue.user; int deviceId = tokenValue.deviceId; DashBoard dashBoard = tokenValue.dash; PinType pinType; byte pin; try { pinType = PinType.getPinType(pinString.charAt(0)); pin = Byte.parseByte(pinString.substring(1)); } catch (NumberFormatException | IllegalCommandBodyException e) { log.debug("Wrong pin format. {}", pinString); return Response.badRequest("Wrong pin format."); } Widget widget = dashBoard.findWidgetByPin(deviceId, pin, pinType); if (widget == null) { String value = dashBoard.pinsStorage.get(new PinStorageKey(deviceId, pinType, pin)); if (value == null) { log.debug("Requested pin {} not found. User {}", pinString, user.email); return Response.badRequest("Requested pin doesn't exist in the app."); } return ok(JsonParser.valueToJsonAsString(value.split(StringUtils.BODY_SEPARATOR_STRING))); } return ok(widget.getJsonValue()); }
#vulnerable code @GET @Path("{token}/pin/{pin}") @Metric(HTTP_GET_PIN_DATA) public Response getWidgetPinData(@PathParam("token") String token, @PathParam("pin") String pinString) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int dashId = tokenValue.dashId; final int deviceId = tokenValue.deviceId; DashBoard dashBoard = user.profile.getDashById(dashId); PinType pinType; byte pin; try { pinType = PinType.getPinType(pinString.charAt(0)); pin = Byte.parseByte(pinString.substring(1)); } catch (NumberFormatException | IllegalCommandBodyException e) { log.debug("Wrong pin format. {}", pinString); return Response.badRequest("Wrong pin format."); } Widget widget = dashBoard.findWidgetByPin(deviceId, pin, pinType); if (widget == null) { String value = dashBoard.pinsStorage.get(new PinStorageKey(deviceId, pinType, pin)); if (value == null) { log.debug("Requested pin {} not found. User {}", pinString, user.email); return Response.badRequest("Requested pin doesn't exist in the app."); } return ok(JsonParser.valueToJsonAsString(value.split(StringUtils.BODY_SEPARATOR_STRING))); } return ok(widget.getJsonValue()); } #location 31 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("{token}/project") @Metric(HTTP_GET_PROJECT) public Response getDashboard(@PathParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } return ok(tokenValue.dash.toString()); }
#vulnerable code @GET @Path("{token}/project") @Metric(HTTP_GET_PROJECT) public Response getDashboard(@PathParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int dashId = tokenValue.dashId; DashBoard dashBoard = user.profile.getDashById(dashId); return ok(dashBoard.toString()); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) { String[] split = StringUtils.split2(message.body); int dashId = ParseUtil.parseInt(split[0]); DashBoard dash = user.profile.getDashByIdOrThrow(dashId); if (split.length == 2) { int deviceId = ParseUtil.parseInt(split[1]); Device device = dash.getDeviceById(deviceId); if (device == null || device.token == null) { throw new IllegalCommandBodyException("Wrong device id."); } makeSingleTokenEmail(ctx, dash, device, user.name, message.id); } else { if (dash.devices.length == 1) { makeSingleTokenEmail(ctx, dash, dash.devices[0], user.name, message.id); } else { sendMultiTokenEmail(ctx, dash, user.name, message.id); } } }
#vulnerable code public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) { String[] split = StringUtils.split2(message.body); int dashId = ParseUtil.parseInt(split[0]); int deviceId = 0; //new value for multi devices if (split.length == 2) { deviceId = ParseUtil.parseInt(split[1]); } DashBoard dashBoard = user.profile.getDashByIdOrThrow(dashId); Device device = dashBoard.getDeviceById(deviceId); String token = device.token; if (token == null) { throw new IllegalCommandBodyException("Wrong device id."); } String to = user.name; String dashName = dashBoard.name == null ? "New Project" : dashBoard.name; String deviceName = device.name == null ? "" : device.name; String subj = "Auth Token for " + dashName + " project and device " + deviceName; String body = String.format(BODY, dashName, token); log.trace("Sending Mail for user {}, with token : '{}'.", user.name, token); mail(ctx.channel(), user.name, to, subj, body, message.id); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @PUT @Path("/{token}/widget/{pin}") @Consumes(value = MediaType.APPLICATION_JSON) public Response updateWidgetPinData(@PathParam("token") String token, @PathParam("pin") String pinString, String[] pinValues) { User user = userDao.tokenManager.getUserByToken(token); if (user == null) { log.error("Requested token {} not found.", token); return Response.notFound(); } Integer dashId = user.getDashIdByToken(token); if (dashId == null) { log.error("Dash id for token {} not found. User {}", token, user.name); return Response.notFound(); } DashBoard dashBoard = user.profile.getDashById(dashId); PinType pinType; byte pin; try { pinType = PinType.getPingType(pinString.charAt(0)); pin = Byte.parseByte(pinString.substring(1)); } catch (NumberFormatException e) { log.error("Wrong pin format. {}", pinString); return Response.badRequest(); } Widget widget = dashBoard.findWidgetByPin(pin, pinType); if (widget == null) { log.error("Requested pin {} not found. User {}", pinString, user.name); return Response.notFound(); } widget.updateIfSame(new HardwareBody(pinType, pin, pinValues)); String body = widget.makeHardwareBody(); if (body != null) { Session session = sessionDao.getUserSession().get(user); session.sendMessageToHardware(dashId, new HardwareMessage(111, body)); } return Response.noContent(); }
#vulnerable code @PUT @Path("/{token}/widget/{pin}") @Consumes(value = MediaType.APPLICATION_JSON) public Response updateWidgetPinData(@PathParam("token") String token, @PathParam("pin") String pinString, String[] pinValues) { User user = userDao.tokenManager.getUserByToken(token); if (user == null) { log.error("Requested token {} not found.", token); return Response.notFound(); } Integer dashId = user.getDashIdByToken(token); if (dashId == null) { log.error("Dash id for token {} not found. User {}", token, user.name); return Response.notFound(); } DashBoard dashBoard = user.profile.getDashById(dashId); PinType pinType; byte pin; try { pinType = PinType.getPingType(pinString.charAt(0)); pin = Byte.parseByte(pinString.substring(1)); } catch (NumberFormatException e) { log.error("Wrong pin format. {}", pinString); return Response.badRequest(); } Widget widget = dashBoard.findWidgetByPin(pin, pinType); if (widget == null) { log.error("Requested pin {} not found. User {}", pinString, user.name); return Response.notFound(); } widget.updateIfSame(new HardwareBody(pinType, pin, pinValues)); return Response.noContent(); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Response updateWidgetProperty(String token, String pinString, String property, String... values) { if (values.length == 0) { log.debug("No properties for update provided."); return Response.badRequest("No properties for update provided."); } TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int deviceId = tokenValue.deviceId; DashBoard dash = tokenValue.dash; //todo add test for this use case if (!dash.isActive) { return Response.badRequest("Project is not active."); } PinType pinType; byte pin; try { pinType = PinType.getPinType(pinString.charAt(0)); pin = Byte.parseByte(pinString.substring(1)); } catch (NumberFormatException | IllegalCommandBodyException e) { log.debug("Wrong pin format. {}", pinString); return Response.badRequest("Wrong pin format."); } //for now supporting only virtual pins Widget widget = dash.findWidgetByPin(deviceId, pin, pinType); if (widget == null || pinType != PinType.VIRTUAL) { log.debug("No widget for SetWidgetProperty command."); return Response.badRequest("No widget for SetWidgetProperty command."); } try { //todo for now supporting only single property widget.setProperty(property, values[0]); } catch (Exception e) { log.debug("Error setting widget property. Reason : {}", e.getMessage()); return Response.badRequest("Error setting widget property."); } Session session = sessionDao.userSession.get(new UserKey(user)); session.sendToApps(SET_WIDGET_PROPERTY, 111, dash.id, deviceId, "" + pin + BODY_SEPARATOR + property + BODY_SEPARATOR + values[0]); return Response.ok(); }
#vulnerable code public Response updateWidgetProperty(String token, String pinString, String property, String... values) { if (values.length == 0) { log.debug("No properties for update provided."); return Response.badRequest("No properties for update provided."); } TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int dashId = tokenValue.dashId; final int deviceId = tokenValue.deviceId; DashBoard dash = user.profile.getDashById(dashId); //todo add test for this use case if (!dash.isActive) { return Response.badRequest("Project is not active."); } PinType pinType; byte pin; try { pinType = PinType.getPinType(pinString.charAt(0)); pin = Byte.parseByte(pinString.substring(1)); } catch (NumberFormatException | IllegalCommandBodyException e) { log.debug("Wrong pin format. {}", pinString); return Response.badRequest("Wrong pin format."); } //for now supporting only virtual pins Widget widget = dash.findWidgetByPin(deviceId, pin, pinType); if (widget == null || pinType != PinType.VIRTUAL) { log.debug("No widget for SetWidgetProperty command."); return Response.badRequest("No widget for SetWidgetProperty command."); } try { //todo for now supporting only single property widget.setProperty(property, values[0]); } catch (Exception e) { log.debug("Error setting widget property. Reason : {}", e.getMessage()); return Response.badRequest("Error setting widget property."); } Session session = sessionDao.userSession.get(new UserKey(user)); session.sendToApps(SET_WIDGET_PROPERTY, 111, dash.id, deviceId, "" + pin + BODY_SEPARATOR + property + BODY_SEPARATOR + values[0]); return Response.ok(); } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void parseHardwareInfo(ChannelHandlerContext ctx, String[] messageParts, HardwareStateHolder state, int msgId) { HardwareInfo hardwareInfo = new HardwareInfo(messageParts); int newHardwareInterval = hardwareInfo.heartbeatInterval; log.trace("Info command. heartbeat interval {}", newHardwareInterval); if (hardwareIdleTimeout != 0 && newHardwareInterval > 0) { int newReadTimeout = (int) Math.ceil(newHardwareInterval * 2.3D); log.debug("Changing read timeout interval to {}", newReadTimeout); ctx.pipeline().replace(ReadTimeoutHandler.class, "H_ReadTimeout", new ReadTimeoutHandler(newReadTimeout)); } DashBoard dashBoard = state.user.profile.getDashByIdOrThrow(state.dashId); Device device = dashBoard.getDeviceById(state.deviceId); if (device != null) { if (otaManager.isUpdateRequired(hardwareInfo)) { otaManager.sendOtaCommand(ctx, device); log.info("Ota command is sent for user {} and device {}:{}.", state.user.email, device.name, device.id); } device.hardwareInfo = hardwareInfo; dashBoard.updatedAt = System.currentTimeMillis(); } ctx.writeAndFlush(ok(msgId), ctx.voidPromise()); }
#vulnerable code private void parseHardwareInfo(ChannelHandlerContext ctx, String[] messageParts, HardwareStateHolder state, int msgId) { HardwareInfo hardwareInfo = new HardwareInfo(messageParts); int newHardwareInterval = hardwareInfo.heartbeatInterval; log.trace("Info command. heartbeat interval {}", newHardwareInterval); if (hardwareIdleTimeout != 0 && newHardwareInterval > 0) { int newReadTimeout = (int) Math.ceil(newHardwareInterval * 2.3D); log.debug("Changing read timeout interval to {}", newReadTimeout); ctx.pipeline().replace(ReadTimeoutHandler.class, "H_ReadTimeout", new ReadTimeoutHandler(newReadTimeout)); } DashBoard dashBoard = state.user.profile.getDashByIdOrThrow(state.dashId); Device device = dashBoard.getDeviceById(state.deviceId); if (otaManager.isUpdateRequired(hardwareInfo)) { otaManager.sendOtaCommand(ctx, device); log.info("Ota command is sent for user {} and device {}:{}.", state.user.email, device.name, device.id); } device.hardwareInfo = hardwareInfo; dashBoard.updatedAt = System.currentTimeMillis(); ctx.writeAndFlush(ok(msgId), ctx.voidPromise()); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void testGetTestString() { RedisClient redisClient = new RedisClient("localhost", "123", 6378, false); String result = redisClient.getServerByToken("test"); assertEquals("It's working!", result); }
#vulnerable code @Test @Ignore public void testGetTestString() { RealRedisClient redisClient = new RealRedisClient("localhost", "123", 6378); String result = redisClient.getServerByToken("test"); assertEquals("It's working!", result); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStore2() throws IOException { StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager()); ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>(); long ts = getTS() / AverageAggregator.HOUR; AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); AggregationValue aggregationValue = new AggregationValue(); aggregationValue.update(100); AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); AggregationValue aggregationValue2 = new AggregationValue(); aggregationValue2.update(150.54); AggregationKey aggregationKey3 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 2); AggregationValue aggregationValue3 = new AggregationValue(); aggregationValue3.update(200); map.put(aggregationKey, aggregationValue); map.put(aggregationKey2, aggregationValue2); map.put(aggregationKey3, aggregationValue3); when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); when(averageAggregator.getHourly()).thenReturn(map); when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); storageWorker.run(); assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); //take less byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 1, GraphType.HOURLY); ByteBuffer byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(16, data.length); assertEquals(100.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); //take more data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 24, GraphType.HOURLY); byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(48, data.length); assertEquals(200.0, byteBuffer.getDouble(), 0.001); assertEquals((ts - 2) * AverageAggregator.HOUR, byteBuffer.getLong()); assertEquals(150.54, byteBuffer.getDouble(), 0.001); assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong()); assertEquals(100.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); }
#vulnerable code @Test public void testStore2() throws IOException { StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null)); ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>(); long ts = getTS() / AverageAggregator.HOUR; AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); AggregationValue aggregationValue = new AggregationValue(); aggregationValue.update(100); AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); AggregationValue aggregationValue2 = new AggregationValue(); aggregationValue2.update(150.54); AggregationKey aggregationKey3 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 2); AggregationValue aggregationValue3 = new AggregationValue(); aggregationValue3.update(200); map.put(aggregationKey, aggregationValue); map.put(aggregationKey2, aggregationValue2); map.put(aggregationKey3, aggregationValue3); when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); when(averageAggregator.getHourly()).thenReturn(map); when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); storageWorker.run(); assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); //take less byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 1, GraphType.HOURLY); ByteBuffer byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(16, data.length); assertEquals(100.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); //take more data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 24, GraphType.HOURLY); byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(48, data.length); assertEquals(200.0, byteBuffer.getDouble(), 0.001); assertEquals((ts - 2) * AverageAggregator.HOUR, byteBuffer.getLong()); assertEquals(150.54, byteBuffer.getDouble(), 0.001); assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong()); assertEquals(100.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("{token}/rtc") @Metric(HTTP_GET_PIN_DATA) public Response getWidgetPinData(@PathParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } User user = tokenValue.user; RTC rtc = tokenValue.dash.getWidgetByType(RTC.class); if (rtc == null) { log.debug("Requested rtc widget not found. User {}", user.email); return Response.badRequest("Requested rtc not exists in app."); } return ok(rtc.getJsonValue()); }
#vulnerable code @GET @Path("{token}/rtc") @Metric(HTTP_GET_PIN_DATA) public Response getWidgetPinData(@PathParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int dashId = tokenValue.dashId; DashBoard dashBoard = user.profile.getDashById(dashId); RTC rtc = dashBoard.getWidgetByType(RTC.class); if (rtc == null) { log.debug("Requested rtc widget not found. User {}", user.email); return Response.badRequest("Requested rtc not exists in app."); } return ok(rtc.getJsonValue()); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void add(Set<String> doNotRemovePaths, DashBoard dash, EnhancedHistoryGraph graph) { for (GraphDataStream graphDataStream : graph.dataStreams) { if (graphDataStream != null && graphDataStream.dataStream != null && graphDataStream.dataStream.isValid()) { DataStream dataStream = graphDataStream.dataStream; Target target = dash.getTarget(graphDataStream.targetId); if (target != null) { for (int deviceId : target.getAssignedDeviceIds()) { for (GraphGranularityType type : GraphGranularityType.values()) { String filename = ReportingDao.generateFilename(dash.id, deviceId, dataStream.pinType.pintTypeChar, dataStream.pin, type.label); doNotRemovePaths.add(filename); } } } } } }
#vulnerable code private static void add(Set<String> doNotRemovePaths, DashBoard dash, EnhancedHistoryGraph graph) { for (GraphDataStream graphDataStream : graph.dataStreams) { if (graphDataStream != null && graphDataStream.dataStream != null && graphDataStream.dataStream.isValid()) { DataStream dataStream = graphDataStream.dataStream; Target target = dash.getTarget(graphDataStream.targetId); for (int deviceId : target.getAssignedDeviceIds()) { for (GraphGranularityType type : GraphGranularityType.values()) { String filename = ReportingDao.generateFilename(dash.id, deviceId, dataStream.pinType.pintTypeChar, dataStream.pin, type.label); doNotRemovePaths.add(filename); } } } } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static List<String> find(String staticResourcesFolder) throws Exception { CodeSource src = ServerLauncher.class.getProtectionDomain().getCodeSource(); List<String> staticResources = new ArrayList<>(); if (src != null) { URL jar = src.getLocation(); try (ZipInputStream zip = new ZipInputStream(jar.openStream())) { ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { String entryName = ze.getName(); if (entryName.startsWith(staticResourcesFolder) && (entryName.endsWith(".js") || entryName.endsWith(".css") || entryName.endsWith(".html")) || entryName.endsWith(".ico") || entryName.endsWith(".png")) { staticResources.add(entryName); } } } } return staticResources; }
#vulnerable code public static List<String> find(String staticResourcesFolder) throws Exception { CodeSource src = ServerLauncher.class.getProtectionDomain().getCodeSource(); List<String> staticResources = new ArrayList<>(); if (src != null) { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); ZipEntry ze; while((ze = zip.getNextEntry()) != null) { String entryName = ze.getName(); if (entryName.startsWith(staticResourcesFolder) && (entryName.endsWith(".js") || entryName.endsWith(".css") || entryName.endsWith(".html")) || entryName.endsWith(".ico") || entryName.endsWith(".png")) { staticResources.add(entryName); } } } return staticResources; } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception{ List<FlashedToken> flashedTokens = generateTokens(100, "Grow", 2); DBManager dbManager = new DBManager("db-test.properties", new BlockingIOProcessor(1, 100, null)); dbManager.insertFlashedTokens(flashedTokens); for (FlashedToken token : flashedTokens) { Path path = Paths.get("/home/doom369/Downloads/grow", token.token + "_" + token.deviceId + ".jpg"); generateQR(token.token, path); } }
#vulnerable code public static void main(String[] args) { List<FlashedToken> flashedTokens = generateTokens(10, AppName.BLYNK, 1); DBManager dbManager = new DBManager("db-test.properties", new BlockingIOProcessor(1, 100, null)); dbManager.insertFlashedTokens(flashedTokens); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) { String[] split = split2(message.body); if (split.length < 2) { throw new IllegalCommandException("Wrong income message format."); } int dashId = ParseUtil.parseInt(split[0]) ; String deviceString = split[1]; if (deviceString == null || deviceString.equals("")) { throw new IllegalCommandException("Income device message is empty."); } DashBoard dash = user.profile.getDashByIdOrThrow(dashId); Device newDevice = JsonParser.parseDevice(deviceString); log.debug("Updating new device {}.", deviceString); Device existingDevice = dash.getDeviceById(newDevice.id); if (existingDevice == null) { throw new IllegalCommandException("Attempt to update device with non existing id."); } existingDevice.update(newDevice); dash.updatedAt = System.currentTimeMillis(); user.lastModifiedTs = dash.updatedAt; ctx.writeAndFlush(ok(message.id), ctx.voidPromise()); }
#vulnerable code public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) { String[] split = split2(message.body); if (split.length < 2) { throw new IllegalCommandException("Wrong income message format."); } int dashId = ParseUtil.parseInt(split[0]) ; String deviceString = split[1]; if (deviceString == null || deviceString.equals("")) { throw new IllegalCommandException("Income device message is empty."); } DashBoard dash = user.profile.getDashByIdOrThrow(dashId); Device newDevice = JsonParser.parseDevice(deviceString); log.debug("Updating new device {}.", deviceString); Device existingDevice = dash.getDeviceById(newDevice.id); existingDevice.update(newDevice); dash.updatedAt = System.currentTimeMillis(); user.lastModifiedTs = dash.updatedAt; ctx.writeAndFlush(ok(message.id), ctx.voidPromise()); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStore() throws IOException { StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager()); ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>(); long ts = getTS() / AverageAggregator.HOUR; AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); AggregationValue aggregationValue = new AggregationValue(); aggregationValue.update(100); AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); AggregationValue aggregationValue2 = new AggregationValue(); aggregationValue2.update(150.54); AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts); AggregationValue aggregationValue3 = new AggregationValue(); aggregationValue3.update(200); map.put(aggregationKey, aggregationValue); map.put(aggregationKey2, aggregationValue2); map.put(aggregationKey3, aggregationValue3); when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); when(averageAggregator.getHourly()).thenReturn(map); when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); storageWorker.run(); assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY)))); byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 2, GraphType.HOURLY); ByteBuffer byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(32, data.length); assertEquals(150.54, byteBuffer.getDouble(), 0.001); assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong()); assertEquals(100.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); data = ReportingDao.getAllFromDisk(reportingFolder, "test2", 2, PinType.ANALOG, (byte) 2, 1, GraphType.HOURLY); byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(16, data.length); assertEquals(200.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); }
#vulnerable code @Test public void testStore() throws IOException { StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null)); ConcurrentHashMap<AggregationKey, AggregationValue> map = new ConcurrentHashMap<>(); long ts = getTS() / AverageAggregator.HOUR; AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); AggregationValue aggregationValue = new AggregationValue(); aggregationValue.update(100); AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); AggregationValue aggregationValue2 = new AggregationValue(); aggregationValue2.update(150.54); AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts); AggregationValue aggregationValue3 = new AggregationValue(); aggregationValue3.update(200); map.put(aggregationKey, aggregationValue); map.put(aggregationKey2, aggregationValue2); map.put(aggregationKey3, aggregationValue3); when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); when(averageAggregator.getHourly()).thenReturn(map); when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); storageWorker.run(); assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY)))); byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 2, GraphType.HOURLY); ByteBuffer byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(32, data.length); assertEquals(150.54, byteBuffer.getDouble(), 0.001); assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong()); assertEquals(100.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); data = ReportingDao.getAllFromDisk(reportingFolder, "test2", 2, PinType.ANALOG, (byte) 2, 1, GraphType.HOURLY); byteBuffer = ByteBuffer.wrap(data); assertNotNull(data); assertEquals(16, data.length); assertEquals(200.0, byteBuffer.getDouble(), 0.001); assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void testIOS() throws Exception { GCMWrapper gcmWrapper = new GCMWrapper(props, client); gcmWrapper.send(new IOSGCMMessage("to", Priority.normal, "yo!!!", 1), null, null); }
#vulnerable code @Test @Ignore public void testIOS() throws Exception { GCMWrapper gcmWrapper = new GCMWrapper(null, null); gcmWrapper.send(new IOSGCMMessage("to", Priority.normal, "yo!!!", 1), null, null); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("/{projectId}") public Response getProject(@Context User user, @PathParam("projectId") int projectId) { DashBoard project = user.profile.getDashById(projectId); //project.token = user.dashTokens.get(projectId); return ok(project); }
#vulnerable code @GET @Path("/{projectId}") public Response getProject(@Context User user, @PathParam("projectId") int projectId) { DashBoard project = user.profile.getDashById(projectId); project.token = user.dashTokens.get(projectId); return ok(project); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("{token}/isAppConnected") @Metric(HTTP_IS_APP_CONNECTED) public Response isAppConnected(@PathParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } User user = tokenValue.user; Session session = sessionDao.userSession.get(new UserKey(user)); return ok(tokenValue.dash.isActive && session.isAppConnected()); }
#vulnerable code @GET @Path("{token}/isAppConnected") @Metric(HTTP_IS_APP_CONNECTED) public Response isAppConnected(@PathParam("token") String token) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int dashId = tokenValue.dashId; final DashBoard dashBoard = user.profile.getDashById(dashId); final Session session = sessionDao.userSession.get(new UserKey(user)); return ok(dashBoard.isActive && session.isAppConnected()); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void channelRead0(ChannelHandlerContext ctx, LoadProfileMessage message) throws Exception { User authUser = Session.findUserByChannel(ctx.channel(), message.id); String body = authUser.getUserProfile() == null ? "{}" : authUser.getUserProfile().toString(); ctx.writeAndFlush(produce(message.id, message.command, body)); }
#vulnerable code @Override protected void channelRead0(ChannelHandlerContext ctx, LoadProfileMessage message) throws Exception { User authUser = Session.findUserByChannel(ctx.channel()); String body = authUser.getUserProfile() == null ? "{}" : authUser.getUserProfile().toString(); ctx.writeAndFlush(produce(message.id, message.command, body)); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @POST @Path("{token}/notify") @Consumes(value = MediaType.APPLICATION_JSON) @Metric(HTTP_NOTIFY) public Response notify(@PathParam("token") String token, PushMessagePojo message) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; if (message == null || Notification.isWrongBody(message.body)) { log.debug("Notification body is wrong. '{}'", message == null ? "" : message.body); return Response.badRequest("Body is empty or larger than 255 chars."); } DashBoard dash = tokenValue.dash; if (!dash.isActive) { log.debug("Project is not active."); return Response.badRequest("Project is not active."); } Notification notification = dash.getWidgetByType(Notification.class); if (notification == null || notification.hasNoToken()) { log.debug("No notification tokens."); if (notification == null) { return Response.badRequest("No notification widget."); } else { return Response.badRequest("Notification widget not initialized."); } } log.trace("Sending push for user {}, with message : '{}'.", user.email, message.body); notification.push(gcmWrapper, message.body, dash.id); return Response.ok(); }
#vulnerable code @POST @Path("{token}/notify") @Consumes(value = MediaType.APPLICATION_JSON) @Metric(HTTP_NOTIFY) public Response notify(@PathParam("token") String token, PushMessagePojo message) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return Response.badRequest("Invalid token."); } final User user = tokenValue.user; final int dashId = tokenValue.dashId; if (message == null || Notification.isWrongBody(message.body)) { log.debug("Notification body is wrong. '{}'", message == null ? "" : message.body); return Response.badRequest("Body is empty or larger than 255 chars."); } DashBoard dash = user.profile.getDashById(dashId); if (!dash.isActive) { log.debug("Project is not active."); return Response.badRequest("Project is not active."); } Notification notification = dash.getWidgetByType(Notification.class); if (notification == null || notification.hasNoToken()) { log.debug("No notification tokens."); if (notification == null) { return Response.badRequest("No notification widget."); } else { return Response.badRequest("Notification widget not initialized."); } } log.trace("Sending push for user {}, with message : '{}'.", user.email, message.body); notification.push(gcmWrapper, message.body, dash.id); return Response.ok(); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void testAndroid() throws Exception { when(props.getProperty("gcm.api.key")).thenReturn(""); when(props.getProperty("gcm.server")).thenReturn(""); GCMWrapper gcmWrapper = new GCMWrapper(props, client); gcmWrapper.send(new AndroidGCMMessage("", Priority.normal, "yo!!!", 1), null, null); Thread.sleep(5000); }
#vulnerable code @Test @Ignore public void testAndroid() throws Exception { GCMWrapper gcmWrapper = new GCMWrapper(null, null); gcmWrapper.send(new AndroidGCMMessage("", Priority.normal, "yo!!!", 1), null, null); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String unCompress(String str) throws IOException { if (null == str || str.length() <= 0) { return str; } try ( // 创建一个新的 byte 数组输出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组 ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(StrConst.DEFAULT_CHARSET_NAME)); // 使用默认缓冲区大小创建新的输入流 GZIPInputStream gzip = new GZIPInputStream(in);) { byte[] buffer = new byte[256]; int n = 0; // 将未压缩数据读入字节数组 while ((n = gzip.read(buffer)) >= 0) { // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流 out.write(buffer, 0, n); } // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串 return out.toString(StrConst.DEFAULT_CHARSET_NAME); } }
#vulnerable code public static String unCompress(String str) throws IOException { if (null == str || str.length() <= 0) { return str; } // 创建一个新的 byte 数组输出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组 ByteArrayInputStream in = new ByteArrayInputStream(str .getBytes("UTF-8")); // 使用默认缓冲区大小创建新的输入流 GZIPInputStream gzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n = 0; while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组 // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流 out.write(buffer, 0, n); } // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串 return out.toString("UTF-8"); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String unCompress(String str) throws IOException { if (null == str || str.length() <= 0) { return str; } try ( // 创建一个新的 byte 数组输出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组 ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(StrConst.DEFAULT_CHARSET_NAME)); // 使用默认缓冲区大小创建新的输入流 GZIPInputStream gzip = new GZIPInputStream(in);) { byte[] buffer = new byte[256]; int n = 0; // 将未压缩数据读入字节数组 while ((n = gzip.read(buffer)) >= 0) { // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流 out.write(buffer, 0, n); } // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串 return out.toString(StrConst.DEFAULT_CHARSET_NAME); } }
#vulnerable code public static String unCompress(String str) throws IOException { if (null == str || str.length() <= 0) { return str; } // 创建一个新的 byte 数组输出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组 ByteArrayInputStream in = new ByteArrayInputStream(str .getBytes("UTF-8")); // 使用默认缓冲区大小创建新的输入流 GZIPInputStream gzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n = 0; while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组 // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流 out.write(buffer, 0, n); } // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串 return out.toString("UTF-8"); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void testThrowsExceptionWithNullTestInstance() throws Exception { assertThrows(NullPointerException.class, () -> { annotationsReader.getOptionsFromAnnotatedField(null, Options.class); }); }
#vulnerable code @Test void testThrowsExceptionWithNullTestInstance() throws Exception { Object optionsFromAnnotatedField = annotationsReader .getOptionsFromAnnotatedField(null, Options.class); assertThat(optionsFromAnnotatedField, nullValue()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String startContainer(DockerContainer dockerContainer) throws DockerException, InterruptedException { String imageId = dockerContainer.getImageId(); log.info("Starting Docker container {}", imageId); com.spotify.docker.client.messages.HostConfig.Builder hostConfigBuilder = HostConfig .builder(); com.spotify.docker.client.messages.ContainerConfig.Builder containerConfigBuilder = ContainerConfig .builder(); boolean privileged = dockerContainer.isPrivileged(); if (privileged) { log.trace("Using privileged mode"); hostConfigBuilder.privileged(true); } Optional<String> network = dockerContainer.getNetwork(); if (network.isPresent()) { log.trace("Using network: {}", network.get()); hostConfigBuilder.networkMode(network.get()); } Optional<Map<String, List<PortBinding>>> portBindings = dockerContainer .getPortBindings(); if (portBindings.isPresent()) { log.trace("Using port bindings: {}", portBindings.get()); hostConfigBuilder.portBindings(portBindings.get()); containerConfigBuilder.exposedPorts(portBindings.get().keySet()); } Optional<List<String>> binds = dockerContainer.getBinds(); if (binds.isPresent()) { log.trace("Using binds: {}", binds.get()); hostConfigBuilder.binds(binds.get()); } Optional<List<String>> envs = dockerContainer.getEnvs(); if (envs.isPresent()) { log.trace("Using envs: {}", envs.get()); containerConfigBuilder.env(envs.get()); } Optional<List<String>> cmd = dockerContainer.getCmd(); if (cmd.isPresent()) { log.trace("Using cmd: {}", cmd.get()); containerConfigBuilder.cmd(cmd.get()); } Optional<List<String>> entryPoint = dockerContainer.getEntryPoint(); if (entryPoint.isPresent()) { log.trace("Using entryPoint: {}", entryPoint.get()); containerConfigBuilder.entrypoint(entryPoint.get()); } ContainerConfig createContainer = containerConfigBuilder.image(imageId) .hostConfig(hostConfigBuilder.build()).build(); String containerId = dockerClient.createContainer(createContainer).id(); dockerClient.startContainer(containerId); return containerId; }
#vulnerable code public String startContainer(DockerContainer dockerContainer) throws DockerException, InterruptedException { String imageId = dockerContainer.getImageId(); log.info("Starting Docker container {}", imageId); com.spotify.docker.client.messages.HostConfig.Builder hostConfigBuilder = HostConfig .builder(); com.spotify.docker.client.messages.ContainerConfig.Builder containerConfigBuilder = ContainerConfig .builder(); boolean privileged = dockerContainer.isPrivileged(); if (privileged) { log.trace("Using privileged mode"); hostConfigBuilder.privileged(true); } Optional<String> network = dockerContainer.getNetwork(); if (network.isPresent()) { log.trace("Using network: {}", network.get()); hostConfigBuilder.networkMode(network.get()); } Optional<Map<String, List<PortBinding>>> portBindings = dockerContainer .getPortBindings(); if (portBindings.isPresent()) { log.trace("Using port bindings: {}", portBindings.get()); hostConfigBuilder.portBindings(portBindings.get()); containerConfigBuilder.exposedPorts(portBindings.get().keySet()); } Optional<List<String>> binds = dockerContainer.getBinds(); if (binds.isPresent()) { log.trace("Using binds: {}", binds.get()); hostConfigBuilder.binds(binds.get()); } Optional<List<String>> envs = dockerContainer.getEnvs(); if (envs.isPresent()) { log.trace("Using envs: {}", envs.get()); containerConfigBuilder.env(envs.get()); } Optional<List<String>> cmd = dockerContainer.getCmd(); if (cmd.isPresent()) { log.trace("Using cmd: {}", cmd.get()); containerConfigBuilder.cmd(cmd.get()); } Optional<List<String>> entryPoint = dockerContainer.getEntryPoint(); if (entryPoint.isPresent()) { log.trace("Using entryPoint: {}", entryPoint.get()); containerConfigBuilder.entrypoint(entryPoint.get()); } ContainerConfig createContainer = containerConfigBuilder.image(imageId) .hostConfig(hostConfigBuilder.build()).build(); String containerId = dockerClient.createContainer(createContainer).id(); dockerClient.startContainer(containerId); boolean isPrivileged = dockerClient.inspectContainer(containerId) .hostConfig().privileged(); log.debug("Docker container {} is running in privileged mode: {}", imageId, isPrivileged); return containerId; } #location 54 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void stopService() { this.stop = true; }
#vulnerable code @Override public void stopService() { this.stop = true; writer.stopService(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws Exception { TChannel tchannel = new TChannel.Builder("ping-client").build(); Map<String, String> headers = new HashMap<String, String>() { { put("some", "header"); } }; Request<Ping> request = new Request.Builder<>(new Ping("{'key': 'ping?'}")) .setEndpoint("ping") .setHeaders(headers) .build(); for (int i = 0; i < this.requests; i++) { Promise<Response<Pong>> f = tchannel.makeRequest( this.host, this.port, "service", ArgScheme.JSON, request, Pong.class ); final int iteration = i; f.addListener(new GenericFutureListener<Future<? super Response<Pong>>>() { @Override public void operationComplete(Future<? super Response<Pong>> future) throws Exception { Response<?> response = (Response<?>) future.get(100, TimeUnit.MILLISECONDS); if (iteration % 1000 == 0) { System.out.println(response); } } }); } tchannel.shutdown(); }
#vulnerable code public void run() throws Exception { TChannel tchannel = new TChannel.Builder("ping-client").build(); Req<Ping> req = new Req<Ping>( "ping", new HashMap<String, String>() { { put("some", "header"); } }, new Ping("{'key': 'ping?'}") ); for (int i = 0; i < this.requests; i++) { Promise<Res<Pong>> f = tchannel.makeRequest( this.host, this.port, "service", ArgScheme.JSON.getScheme(), Pong.class, req ); f.addListener(new GenericFutureListener<Future<? super Res<Pong>>>() { @Override public void operationComplete(Future<? super Res<Pong>> future) throws Exception { if (future.isSuccess()) { Res<Pong> res = (Res<Pong>) future.get(); System.out.println(res); } } }); } tchannel.shutdown(); } #location 36 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws Exception { TChannel tchannel = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .setServerPort(this.port) .build(); tchannel.listen().channel().closeFuture().sync(); }
#vulnerable code public void run() throws Exception { TChannel tchannel = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .setPort(this.port) .build(); tchannel.listen().channel().closeFuture().sync(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long missCount() { return missCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long removeCount() { return removeCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree) { this.capacity = capacity; this.freeCapacity = capacity; this.cleanUpTriggerFree = cleanUpTriggerFree; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = new Table(roundUpToPowerOf2(hts)); double lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75d; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long size() { return size; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree) { this.capacity = capacity; this.freeCapacity = capacity; this.cleanUpTriggerFree = cleanUpTriggerFree; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = new Table(roundUpToPowerOf2(hts)); double lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75d; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long rehashes() { return rehashes; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long missCount() { return missCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree, long cleanUpTargetFree) { this.capacity = capacity; this.freeCapacity = capacity; this.cleanUpTriggerFree = cleanUpTriggerFree; this.cleanUpTargetFree = cleanUpTargetFree; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = new Table(roundUpToPowerOf2(hts)); double lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75d; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long cleanUpCount() { return cleanUpCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long putReplaceCount() { return putReplaceCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long evictedEntries() { return evictedEntries; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code int hashTableSize() { return table.size(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code boolean replaceEntry(long hash, long oldHashEntryAdr, long newHashEntryAdr, long bytes) { LongArrayList derefList = null; lock.lock(); try { long prevEntryAdr = 0L; for (long hashEntryAdr = table.getFirst(hash); hashEntryAdr != 0L; prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr)) { if (hashEntryAdr != oldHashEntryAdr) continue; // remove existing entry replaceInternal(oldHashEntryAdr, prevEntryAdr, newHashEntryAdr); while (freeCapacity < bytes) { long eldestHashAdr = removeEldest(); if (eldestHashAdr == 0L) { return false; } if (derefList == null) derefList = new LongArrayList(); derefList.add(eldestHashAdr); } return true; } return false; } finally { lock.unlock(); if (derefList != null) for (int i = 0; i < derefList.size(); i++) HashEntries.dereference(derefList.getLong(i)); } } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree) { this.capacity = capacity; this.freeCapacity = capacity; this.cleanUpTriggerFree = cleanUpTriggerFree; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = new Table(roundUpToPowerOf2(hts)); double lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75d; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long freeCapacity() { return freeCapacity; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long putAddCount() { return putAddCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long rehashes() { return rehashes; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long size() { return size; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long removeCount() { return removeCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long putAddCount() { return putAddCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long capacity, long cleanUpTriggerFree) { this.capacity = capacity; this.freeCapacity = capacity; this.cleanUpTriggerFree = cleanUpTriggerFree; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = new Table(roundUpToPowerOf2(hts)); double lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75d; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long evictedEntries() { return evictedEntries; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long hitCount() { return hitCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long putAddCount() { return putAddCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long hitCount() { return hitCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long putReplaceCount() { return putReplaceCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long hitCount() { return hitCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long rehashes() { return rehashes; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code boolean putEntry(long newHashEntryAdr, long hash, long keyLen, long bytes, boolean ifAbsent, long oldValueAdr, long oldValueLen) { long removeHashEntryAdr = 0L; LongArrayList derefList = null; lock.lock(); try { long hashEntryAdr; long ptr = table.bucketOffset(hash); for (int idx = 0; idx < entriesPerBucket; idx++, ptr += Util.BUCKET_ENTRY_LEN) { if ((hashEntryAdr = table.getEntryAdr(ptr)) == 0L) break; if (table.getHash(ptr) != hash) continue; // fetch allocLen here - same CPU cache line needed by key compare long allocLen = HashEntries.getAllocLen(hashEntryAdr); if (notSameKey(newHashEntryAdr, keyLen, hashEntryAdr)) continue; // replace existing entry if (ifAbsent) return false; if (oldValueAdr != 0L) { // code for replace() operation if (HashEntries.getValueLen(hashEntryAdr) != oldValueLen || !HashEntries.compare(hashEntryAdr, Util.ENTRY_OFF_DATA + Util.roundUpTo8(keyLen), oldValueAdr, 0L, oldValueLen)) return false; } freeCapacity += allocLen; table.removeFromTableWithOff(hashEntryAdr, ptr, idx); removeHashEntryAdr = hashEntryAdr; break; } if (freeCapacity < bytes) { derefList = new LongArrayList(); do { long eldestEntryAdr = table.removeEldest(); if (eldestEntryAdr == 0L) { if (removeHashEntryAdr != 0L) size--; return false; } freeCapacity += HashEntries.getAllocLen(eldestEntryAdr); size--; evictedEntries++; derefList.add(eldestEntryAdr); } while (freeCapacity < bytes); } if (removeHashEntryAdr == 0L) { if (size >= threshold) rehash(); size++; } if (!add(newHashEntryAdr, hash)) return false; freeCapacity -= bytes; if (removeHashEntryAdr == 0L) putAddCount++; else putReplaceCount++; return true; } finally { lock.unlock(); if (removeHashEntryAdr != 0L) HashEntries.dereference(removeHashEntryAdr); if (derefList != null) for (int i = 0; i < derefList.size(); i++) HashEntries.dereference(derefList.getLong(i)); } } #location 92 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long size() { return size; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code long size() { return size; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.