instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void getInfo() { this.info = new ObjectInformationCommand(getAccount(), getClient(), getAccess(), getContainer(), this).call(); this.setInfoRetrieved(); }
#vulnerable code protected void getInfo() { ObjectInformation info = new ObjectInformationCommand(getAccount(), getClient(), getAccess(), getContainer(), this).call(); this.lastModified = info.getLastModified(); this.etag = info.getEtag(); this.contentLength = info.getContentLength(); this.contentType = info.getContentType(); this.setMetadata(info.getMetadata()); this.setInfoRetrieved(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public StoredObject setDeleteAfter(long seconds) { checkForInfo(); info.setDeleteAt(null); info.setDeleteAfter(new DeleteAfter(seconds)); commandFactory.createObjectMetadataCommand( getAccount(), getClient(), getAccess(), this, info.getHeadersIncludingHeader(info.getDeleteAfter())).call(); return this; }
#vulnerable code public StoredObject setDeleteAfter(long seconds) { checkForInfo(); info.setDeleteAt(null); info.setDeleteAfter(new DeleteAfter(seconds)); new ObjectMetadataCommand( getAccount(), getClient(), getAccess(), this, info.getHeadersIncludingHeader(info.getDeleteAfter())).call(); return this; } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testWrite() throws Exception { final File out1 = File.createTempFile("jdeb", ".ar"); final ArArchiveOutputStream os = new ArArchiveOutputStream(new FileOutputStream(out1)); os.putArchiveEntry(new ArArchiveEntry("data", 4)); os.write("data".getBytes()); os.closeArchiveEntry(); os.close(); assertTrue(out1.delete()); }
#vulnerable code public void testWrite() throws Exception { final File out1 = File.createTempFile("jdeb", ".ar"); final ArOutputStream os = new ArOutputStream(new FileOutputStream(out1)); os.putNextEntry(new ArEntry("data", 4)); os.write("data".getBytes()); os.close(); assertTrue(out1.delete()); } #location 10 #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)); StringBuffer buffer = new StringBuffer(); 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++; 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 StringBuffer(); } final int i = line.indexOf(':'); if (i < 0) { throw new ParseException("Line misses ':' delimitter", 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)); StringBuffer buffer = new StringBuffer(); 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++; 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 StringBuffer(); } final int i = line.indexOf(':'); if (i < 0) { throw new ParseException("Line misses ':' delimitter", linenr); } key = line.substring(0, i); buffer.append(line.substring(i+1).trim()); continue; } // continueing old value buffer.append('\n').append(line.substring(1)); } br.close(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code String toString( final String[] pKeys ) { final StringBuffer s = new StringBuffer(); for (int i = 0; i < pKeys.length; i++) { final String key = pKeys[i]; final String value = (String) values.get(key); if (value != null) { s.append(key).append(":"); try { BufferedReader reader = new BufferedReader(new StringReader(value)); String line; while ((line = reader.readLine()) != null) { if (line.length() != 0 && !Character.isWhitespace(line.charAt(0))) { s.append(' '); } s.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } } } return s.toString(); }
#vulnerable code String toString( final String[] pKeys ) { final StringBuffer s = new StringBuffer(); for (int i = 0; i < pKeys.length; i++) { final String key = pKeys[i]; final String value = (String) values.get(key); if (value != null) { s.append(key).append(": "); try { LineNumberReader reader = new LineNumberReader(new StringReader(value)); String line; while ((line = reader.readLine()) != null) { if (reader.getLineNumber() > 0 && line.length() != 0 && !Character.isWhitespace(line.charAt(0))) { // indent the line with a white space s.append(' '); } s.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } } } return s.toString(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void execute() { if (control == null || !control.isDirectory()) { throw new BuildException("You need to point the 'control' attribute to the control directory."); } if (changes != null && changes.isDirectory()) { throw new BuildException("If you want the changes written out provide the file via 'changes' attribute."); } if (dataProducers.size() == 0) { throw new BuildException("You need to provide at least one reference to a tgz or directory with data."); } if (deb == null) { throw new BuildException("You need to point the 'destfile' attribute to where the deb 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(new Console() { public void println(String s) { log(s); } }); try { final ChangesDescriptor changesDescriptor = processor.createDeb(controlFiles, data, new FileOutputStream(deb)); log("created " + deb); if (changes != null) { processor.createChanges(changesDescriptor, new FileOutputStream(changes)); log("created changes file " + changes); } } catch (Exception e) { log("failed to create debian package " + e); e.printStackTrace(); } }
#vulnerable code public void execute() { if (control == null || !control.isDirectory()) { throw new BuildException("You need to point the 'control' attribute to the control directory."); } if (changes != null && !changes.isFile()) { throw new BuildException("If you want the changes written out provide the file via 'changes' attribute."); } if (dataProducers.size() == 0) { throw new BuildException("You need to provide at least one reference to a tgz or directory with data."); } if (deb == null) { throw new BuildException("You need to point the 'destfile' attribute to where the deb 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(new Console() { public void println(String s) { log(s); } }); try { final ChangesDescriptor changesDescriptor = processor.createDeb(controlFiles, data, new FileOutputStream(deb)); if (changes != null) { processor.createChanges(changesDescriptor, new FileOutputStream(changes)); } } catch (Exception e) { log("failed to create debian package " + e); e.printStackTrace(); } log("created " + deb); } #location 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() { public void visit(TarArchiveEntry entry, byte[] content) throws IOException { assertTrue("prefix", entry.getName().startsWith("./foo/")); if (entry.isDirectory()) { assertEquals("directory mode (" + entry.getName() + ")", 040700, entry.getMode()); } else { assertEquals("file mode (" + entry.getName() + ")", 0100600, entry.getMode()); } assertEquals("user", "ebourg", entry.getUserName()); assertEquals("group", "ebourg", entry.getGroupName()); } }, Compression.GZIP); }
#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()); ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar.gz")) { TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(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; } } } in.close(); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() { public void visit(TarArchiveEntry entry, byte[] content) throws IOException { assertTrue("prefix", entry.getName().startsWith("./foo/")); if (entry.isDirectory()) { assertEquals("directory mode (" + entry.getName() + ")", 040700, entry.getMode()); } else { assertEquals("file mode (" + entry.getName() + ")", 0100600, entry.getMode()); } assertEquals("user", "ebourg", entry.getUserName()); assertEquals("group", "ebourg", entry.getGroupName()); } }, Compression.GZIP); }
#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()); ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar.gz")) { TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(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; } } } in.close(); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private PackageDescriptor createPackageDescriptor(File file, BigInteger pDataSize) throws IOException, ParseException { FilteredConfigurationFile controlFile = new FilteredConfigurationFile(file.getName(), new FileInputStream(file), resolver); PackageDescriptor packageDescriptor = new PackageDescriptor(new ByteArrayInputStream(controlFile.toString().getBytes())); if (packageDescriptor.get("Date") == null) { // Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822) SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH); packageDescriptor.set("Date", fmt.format(new Date())); } if (packageDescriptor.get("Distribution") == null) { packageDescriptor.set("Distribution", "unknown"); } if (packageDescriptor.get("Urgency") == null) { packageDescriptor.set("Urgency", "low"); } packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString()); // override the Version if the DEBVERSION environment variable is defined final String debVersion = System.getenv("DEBVERSION"); if (debVersion != null) { packageDescriptor.set("Version", debVersion); console.info("Using version'" + debVersion + "' from the environment variables."); } // override the Maintainer field if the DEBFULLNAME and DEBEMAIL environment variables are defined final String debFullName = System.getenv("DEBFULLNAME"); final String debEmail = System.getenv("DEBEMAIL"); if (debFullName != null && debEmail != null) { final String maintainer = debFullName + " <" + debEmail + ">"; packageDescriptor.set("Maintainer", maintainer); console.info("Using maintainer '" + maintainer + "' from the environment variables."); } return packageDescriptor; }
#vulnerable code private PackageDescriptor createPackageDescriptor(File file, BigInteger pDataSize) throws IOException, ParseException { PackageDescriptor packageDescriptor = new PackageDescriptor(new FileInputStream(file), resolver); if (packageDescriptor.get("Date") == null) { // Mon, 26 Mar 2007 11:44:04 +0200 (RFC 2822) SimpleDateFormat fmt = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH); packageDescriptor.set("Date", fmt.format(new Date())); } if (packageDescriptor.get("Distribution") == null) { packageDescriptor.set("Distribution", "unknown"); } if (packageDescriptor.get("Urgency") == null) { packageDescriptor.set("Urgency", "low"); } packageDescriptor.set("Installed-Size", pDataSize.divide(BigInteger.valueOf(1024)).toString()); // override the Version if the DEBVERSION environment variable is defined final String debVersion = System.getenv("DEBVERSION"); if (debVersion != null) { packageDescriptor.set("Version", debVersion); console.info("Using version'" + debVersion + "' from the environment variables."); } // override the Maintainer field if the DEBFULLNAME and DEBEMAIL environment variables are defined final String debFullName = System.getenv("DEBFULLNAME"); final String debEmail = System.getenv("DEBEMAIL"); if (debFullName != null && debEmail != null) { final String maintainer = debFullName + " <" + debEmail + ">"; packageDescriptor.set("Maintainer", maintainer); console.info("Using maintainer '" + maintainer + "' from the environment variables."); } return packageDescriptor; } #location 2 #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; 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(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; } } } 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(in); while ((tar.getNextEntry()) != null); } else { // skip to the next entry in.skip(entry.getLength()); } } assertTrue("tar file not found", found); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-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.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); break; } 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("bz2 file not found", found); }
#vulnerable code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-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.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); break; } 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("bz2 file not found", found); } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); final AtomicBoolean found = new AtomicBoolean(false); ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArchiveWalker.walk(in, new ArchiveVisitor<ArArchiveEntry>() { public void visit(ArArchiveEntry entry, byte[] content) throws IOException { if (entry.getName().equals("data.tar.bz2")) { found.set(true); assertEquals("header 0", (byte) 'B', content[0]); assertEquals("header 1", (byte) 'Z', content[1]); TarInputStream tar = new TarInputStream(new BZip2CompressorInputStream(new ByteArrayInputStream(content))); while ((tar.getNextEntry()) != null) ; tar.close(); } } }); assertTrue("bz2 file not found", found.get()); }
#vulnerable code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-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.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null) { ; } tar.close(); break; } 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("bz2 file not found", found); } #location 30 #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 Console() { public void println(String s) { } }, 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 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 DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip"); assertTrue(packageDescriptor.isValid()); final Set filesInDeb = new HashSet(); final ArInputStream ar = new ArInputStream(new FileInputStream(deb)); while(true) { final ArEntry arEntry = ar.getNextEntry(); 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.add(tarEntry.getName()); } tar.close(); break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } ar.close(); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3")); assertTrue("Cannot delete the file " + deb, deb.delete()); }
#vulnerable code public void testCreation() throws Exception { final Processor processor = new Processor(new Console() { public void println(String s) { } }, 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 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 DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip"); assertTrue(packageDescriptor.isValid()); final Set filesInDeb = new HashSet(); FileInputStream in = new FileInputStream(deb); final ArInputStream ar = new ArInputStream(in); while(true) { final ArEntry arEntry = ar.getNextEntry(); if (arEntry == null) { break; } if ("data.tar.gz".equals(arEntry.getName())) { final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar)); while(true) { final TarEntry tarEntry = tar.getNextEntry(); if (tarEntry == null) { break; } filesInDeb.add(tarEntry.getName()); } tar.close(); break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } in.close(); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3")); assertTrue("Cannot delete the file " + deb, deb.delete()); } #location 37 #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 Console() { public void println(String s) { } }, 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 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 DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip"); assertTrue(packageDescriptor.isValid()); final Set filesInDeb = new HashSet(); final ArInputStream ar = new ArInputStream(new FileInputStream(deb)); while(true) { final ArEntry arEntry = ar.getNextEntry(); if (arEntry == null) { break; } if ("data.tar.gz".equals(arEntry.getName())) { final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar)); while(true) { final TarEntry tarEntry = tar.getNextEntry(); if (tarEntry == null) { break; } filesInDeb.add(tarEntry.getName()); } tar.close(); break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3")); assertTrue(deb.delete()); }
#vulnerable code public void testCreation() throws Exception { final Processor processor = new Processor(new Console() { public void println(String s) { } }, 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 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 DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip"); assertTrue(packageDescriptor.isValid()); final Set filesInDeb = new HashSet(); final ArInputStream ar = new ArInputStream(new FileInputStream(deb)); while(true) { final ArEntry arEntry = ar.getNextEntry(); if (arEntry == null) { break; } if ("data.tar.gz".equals(arEntry.getName())) { final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar)); while(true) { final TarEntry tarEntry = tar.getNextEntry(); if (tarEntry == null) { break; } filesInDeb.add(tarEntry.getName()); } break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3")); deb.delete(); } #location 40 #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; 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); }
#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(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; } } } assertTrue("tar file not found", found); } #location 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCreateParentDirectories() throws Exception { File archive = new File("target/data.tar"); if (archive.exists()) { archive.delete(); } DataBuilder builder = new DataBuilder(new NullConsole()); DataProducer producer = new DataProducerFile(new File("pom.xml"), "/usr/share/myapp/pom.xml", null, null, null); builder.buildData(Arrays.asList(producer), archive, new StringBuilder(), Compression.NONE); int count = 0; TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new FileInputStream(archive)); while (in.getNextTarEntry() != null) { count++; } } finally { if (in != null) { in.close(); } } assertEquals("entries", 4, count); }
#vulnerable code public void testCreateParentDirectories() throws Exception { File archive = new File("target/data.tar"); if (archive.exists()) { archive.delete(); } DataBuilder builder = new DataBuilder(new NullConsole()); DataProducer producer = new DataProducerFile(new File("pom.xml"), "/usr/share/myapp/pom.xml", null, null, null); builder.buildData(Arrays.asList(producer), archive, new StringBuilder(), Compression.NONE); int count = 0; TarArchiveInputStream in = new TarArchiveInputStream(new FileInputStream(archive)); while (in.getNextTarEntry() != null) { count++; } assertEquals("entries", 4, count); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-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.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); break; } 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("bz2 file not found", found); }
#vulnerable code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-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.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); break; } 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("bz2 file not found", found); } #location 28 #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 39 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void execute() { if (control == null || !control.isDirectory()) { throw new BuildException("You need to point the 'control' attribute to the control directory."); } if (changesIn != null) { if (!changesIn.isFile() || !changesIn.canRead()) { throw new BuildException("The 'changesIn' attribute needs to point to a readable file. " + changesIn + " was not found/readable."); } if (changesOut == null) { throw new BuildException("A 'changesIn' without a 'changesOut' does not make much sense."); } if (!isPossibleOutput(changesOut)) { throw new BuildException("Cannot write the output for 'changesOut' to " + changesOut); } if (changesSave != null && !isPossibleOutput(changesSave)) { throw new BuildException("Cannot write the output for 'changesSave' to " + changesSave); } } else { if (changesOut != null || changesSave != null) { throw new BuildException("The 'changesOut' or 'changesSave' attributes may only be used when there is a 'changesIn' specified."); } } if (dataProducers.size() == 0) { throw new BuildException("You need to provide at least one reference to a tgz or directory with data."); } if (deb == null) { throw new BuildException("You need to point the 'destfile' attribute to where the deb 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(new Console() { public void println(String s) { if (verbose) { log(s); } } }, null); final PackageDescriptor packageDescriptor; try { log("Creating debian package: " + deb); packageDescriptor = processor.createDeb(controlFiles, data, deb); } catch (Exception e) { throw new BuildException("Failed to create debian package " + deb, e); } final TextfileChangesProvider changesProvider; try { if (changesOut == null) { return; } log("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 BuildException("Failed to create debian changes file " + changesOut, e); } try { if (changesSave == null) { return; } log("Saving changes to file: " + changesSave); changesProvider.save(new FileOutputStream(changesSave)); } catch (Exception e) { throw new BuildException("Failed to save debian changes file " + changesSave, e); } }
#vulnerable code public void execute() { if (control == null || !control.isDirectory()) { throw new BuildException("You need to point the 'control' attribute to the control directory."); } if (changesIn != null) { if (!changesIn.isFile() || !changesIn.canRead()) { throw new BuildException("The 'changesIn' attribute needs to point to a readable file. " + changesIn + " was not found/readable."); } if (changesOut == null) { throw new BuildException("A 'changesIn' without a 'changesOut' does not make much sense."); } if (!isPossibleOutput(changesOut)) { throw new BuildException("Cannot write the output for 'changesOut' to " + changesOut); } if (changesSave != null && !isPossibleOutput(changesSave)) { throw new BuildException("Cannot write the output for 'changesSave' to " + changesSave); } } else { if (changesOut != null || changesSave != null) { throw new BuildException("The 'changesOut' or 'changesSave' attributes may only be used when there is a 'changesIn' specified."); } } if (dataProducers.size() == 0) { throw new BuildException("You need to provide at least one reference to a tgz or directory with data."); } if (deb == null) { throw new BuildException("You need to point the 'destfile' attribute to where the deb 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(new Console() { public void println(String s) { if (verbose) { log(s); } } }, null); final PackageDescriptor packageDescriptor; try { packageDescriptor = processor.createDeb(controlFiles, data, deb); log("Created " + deb); } catch (Exception e) { throw new BuildException("Failed to create debian package " + deb, e); } final TextfileChangesProvider changesProvider; try { if (changesOut == null) { return; } // 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)); log("Created changes file " + changesOut); } catch (Exception e) { throw new BuildException("Failed to create debian changes file " + changesOut, e); } try { if (changesSave == null) { return; } changesProvider.save(new FileOutputStream(changesSave)); log("Saved changes to file " + changesSave); } catch (Exception e) { throw new BuildException("Failed to save debian changes file " + changesSave, e); } } #location 59 #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 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 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 @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 @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 @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 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 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 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); }
#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.dashId; 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."); } DashBoard dash = user.profile.getDashById(dashId); Device device = dash.getDeviceById(deviceId); User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get(); if (initiator != null) { device.updateOTAInfo(initiator.email); } return ok(path); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed 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 = removeOldToken(device); //todo should never happen. but due to back compatibility if (device == null) { throw new IllegalCommandBodyException("Error refreshing token for user + " + user.name); } //assign new token device.token = newToken; cache.put(newToken, new TokenValue(user, dashId, deviceId)); user.lastModifiedTs = System.currentTimeMillis(); log.debug("Generated token for user {}, dashId {}, deviceId {} is {}.", user.name, dashId, deviceId, newToken); return oldToken; }
#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 = removeOldToken(device); //assign new token device.token = newToken; cache.put(newToken, new TokenValue(user, dashId, deviceId)); user.lastModifiedTs = System.currentTimeMillis(); log.debug("Generated token for user {}, dashId {}, deviceId {} is {}.", user.name, 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 @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; 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."); } tokenValue.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 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(); } #location 35 #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 @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 @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 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 @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; 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 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 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; 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, 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 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; 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, 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 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 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 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, 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 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, 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; 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.
#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 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 putEntry(long newHashEntryAdr, long hash, long keyLen, long bytes, boolean ifAbsent, long oldValueAddr, long oldValueOffset, long oldValueLen) { long removeHashEntryAdr = 0L; LongArrayList derefList = null; lock.lock(); try { long oldHashEntryAdr = 0L; long hashEntryAdr; long prevEntryAdr = 0L; for (hashEntryAdr = table.getFirst(hash); hashEntryAdr != 0L; prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr)) { if (notSameKey(newHashEntryAdr, hash, keyLen, hashEntryAdr)) continue; // replace existing entry if (ifAbsent) return false; if (oldValueAddr != 0L) { // code for replace() operation long valueLen = HashEntries.getValueLen(hashEntryAdr); if (valueLen != oldValueLen || !HashEntries.compare(hashEntryAdr, Util.ENTRY_OFF_DATA + Util.roundUpTo8(keyLen), oldValueAddr, oldValueOffset, oldValueLen)) return false; } removeInternal(hashEntryAdr, prevEntryAdr); removeHashEntryAdr = hashEntryAdr; oldHashEntryAdr = hashEntryAdr; break; } while (freeCapacity < bytes) { long eldestHashAdr = removeEldest(); if (eldestHashAdr == 0L) { if (oldHashEntryAdr != 0L) size--; return false; } if (derefList == null) derefList = new LongArrayList(); derefList.add(eldestHashAdr); } if (hashEntryAdr == 0L) { if (size >= threshold) rehash(); size++; } freeCapacity -= bytes; add(newHashEntryAdr, hash); if (hashEntryAdr == 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 79 #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 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; 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 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 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 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, 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 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 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 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 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 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 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, 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 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 public List<JadbDevice> getDevices() throws IOException, JadbException { try (Transport transport = createTransport()) { transport.send("host:devices"); transport.verifyResponse(); String body = transport.readString(); return parseDevices(body); } }
#vulnerable code public List<JadbDevice> getDevices() throws IOException, JadbException { Transport devices = createTransport(); devices.send("host:devices"); devices.verifyResponse(); String body = devices.readString(); devices.close(); return parseDevices(body); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void start() throws InterruptedException { thread = new Thread(this, "Fake Adb Server"); thread.setDaemon(true); thread.start(); serverReady(); }
#vulnerable code public void start() throws InterruptedException { thread = new Thread(this, "Fake Adb Server"); thread.setDaemon(true); thread.start(); synchronized (lockObject) { if (!isStarted) { lockObject.wait(); } } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getHostVersion() throws IOException, JadbException { try (Transport transport = createTransport()) { transport.send("host:version"); transport.verifyResponse(); return transport.readString(); } }
#vulnerable code public String getHostVersion() throws IOException, JadbException { Transport main = createTransport(); main.send("host:version"); main.verifyResponse(); String version = main.readString(); main.close(); return version; } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<RemoteFile> list(String remotePath) throws IOException, JadbException { try (Transport transport = getTransport()) { SyncTransport sync = transport.startSync(); sync.send("LIST", remotePath); List<RemoteFile> result = new ArrayList<>(); for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) { result.add(dent); } return result; } }
#vulnerable code public List<RemoteFile> list(String remotePath) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("LIST", remotePath); List<RemoteFile> result = new ArrayList<>(); for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) { result.add(dent); } return result; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String readString(int length) throws IOException { byte[] responseBuffer = new byte[length]; dataInput.readFully(responseBuffer); return new String(responseBuffer, StandardCharsets.UTF_8); }
#vulnerable code public String readString(int length) throws IOException { DataInput reader = new DataInputStream(inputStream); byte[] responseBuffer = new byte[length]; reader.readFully(responseBuffer); return new String(responseBuffer, StandardCharsets.UTF_8); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void vanilla() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestConfiguration.class); Service service = context.getBean(Service.class); Foo foo = context.getBean(Foo.class); assertFalse(AopUtils.isAopProxy(foo)); service.service(); assertEquals(3, service.getCount()); context.close(); }
#vulnerable code @Test public void vanilla() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestConfiguration.class); Service service = context.getBean(Service.class); service.service(); assertEquals(3, service.getCount()); context.close(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmpytObjectCRC() { String key = "empty-object-crc"; try { // put PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, new ByteArrayInputStream(new String("").getBytes())); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); Assert.assertEquals(putObjectResult.getRequestId().length(), REQUEST_ID_LEN); String localFile = TestUtils.genFixedLengthFile(0); putObjectResult = ossClient.putObject(bucketName, key, new FileInputStream(localFile)); Assert.assertEquals(putObjectResult.getClientCRC(), putObjectResult.getServerCRC()); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); Assert.assertEquals(putObjectResult.getRequestId().length(), REQUEST_ID_LEN); putObjectResult = ossClient.putObject(bucketName, key, new File(localFile)); Assert.assertEquals(putObjectResult.getClientCRC(), putObjectResult.getServerCRC()); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); Assert.assertEquals(putObjectResult.getRequestId().length(), REQUEST_ID_LEN); // get OSSObject ossObject = ossClient.getObject(bucketName, key); Assert.assertNull(ossObject.getClientCRC()); Assert.assertNotNull(ossObject.getServerCRC()); Assert.assertEquals(ossObject.getRequestId().length(), REQUEST_ID_LEN); Assert.assertTrue(IOUtils.getCRCValue(ossObject.getObjectContent()) == 0L); InputStream content = ossObject.getObjectContent(); while (content.read() != -1) { } ossObject.setClientCRC(IOUtils.getCRCValue(content)); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); content.close(); ossClient.deleteObject(bucketName, key); TestUtils.removeFile(localFile); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } }
#vulnerable code @Test public void testEmpytObjectCRC() { String key = "empty-object-crc"; try { // put PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, new ByteArrayInputStream(new String("").getBytes())); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); String localFile = TestUtils.genFixedLengthFile(0); putObjectResult = ossClient.putObject(bucketName, key, new FileInputStream(localFile)); Assert.assertEquals(putObjectResult.getClientCRC(), putObjectResult.getServerCRC()); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); putObjectResult = ossClient.putObject(bucketName, key, new File(localFile)); Assert.assertEquals(putObjectResult.getClientCRC(), putObjectResult.getServerCRC()); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); // get OSSObject ossObject = ossClient.getObject(bucketName, key); Assert.assertNull(ossObject.getClientCRC()); Assert.assertNotNull(ossObject.getServerCRC()); Assert.assertTrue(IOUtils.getCRCValue(ossObject.getObjectContent()) == 0L); InputStream content = ossObject.getObjectContent(); while (content.read() != -1) { } ossObject.setClientCRC(IOUtils.getCRCValue(content)); Assert.assertTrue(putObjectResult.getClientCRC() == 0L); Assert.assertTrue(putObjectResult.getServerCRC() == 0L); content.close(); ossClient.deleteObject(bucketName, key); TestUtils.removeFile(localFile); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SneakyThrows @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { String token = request.getHeader(Constant.TOKEN); redisTemplate.delete(Constant.AUTHENTICATION_TOKEN); redisTemplate.delete(token); }
#vulnerable code @SneakyThrows @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { String token = request.getHeader(Constant.TOKEN); redisTemplate.delete(Constant.AUTHENTICATION_TOKEN); byte[] authenticationKey = redisTokenStoreSerializationStrategy.serialize(token); RedisConnection conn = redisTemplate.getConnectionFactory().getConnection(); try{ conn.openPipeline(); conn.get(authenticationKey); conn.del(authenticationKey); conn.closePipeline(); }finally { conn.close(); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<BOBRequestDetail> getRequestBOBDetails() { if (requestBOBDetails == null) { List<String> detailLines = getDetailLines(); if (detailLines == null) return null; BOBRequestDetail detail; requestBOBDetails = new ArrayList<>(); for (String detailLine : detailLines) { detail = parseDetailLinesToRequestBOBDetail(detailLine); requestBOBDetails.add(detail); } } return requestBOBDetails; }
#vulnerable code private List<BOBRequestDetail> getRequestBOBDetails() { if (requestBOBDetails == null) { List<String> detailLines = getDetailLines(); if (detailLines == null) return null; BOBRequestDetail detail; requestBOBDetails = new ArrayList<>(); for (String detailLine : detailLines) { detail = parseDetailLinesToRequestBOBDetail(detailLine); setNonGMGValues(detail); //FSIS-2993 //2018.04.28 address type must be upper case if(StringUtils.isNotEmpty(detail.getAddressType())) { detail.setAddressType(detail.getAddressType().toUpperCase()); } requestBOBDetails.add(detail); } } return requestBOBDetails; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getResponseBody() throws IOException { String contentType = getContentType(); String charset = "UTF-8"; if (contentType != null) { for (String part : contentType.split(";")) { if (part.startsWith("charset=")) { charset = part.substring("charset=".length()); } } } return contentToString(charset); }
#vulnerable code @Override public String getResponseBody() throws IOException { String contentType = getContentType(); String charset = "UTF-8"; if (contentType != null) { for (String part : contentType.split(";")) { if (part.startsWith("charset=")) { charset = part.substring("charset=".length()); } } } InputStream responseInput = getResponseBodyAsStream(); return contentToString(charset); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getResponseBodyExcerpt(int maxLength) throws IOException { String contentType = getContentType(); String charset = "UTF-8"; if (contentType != null) { for (String part : contentType.split(";")) { if (part.startsWith("charset=")) { charset = part.substring("charset=".length()); } } } String response = contentToString(charset); return response.length() <= maxLength ? response : response.substring(0,maxLength); }
#vulnerable code @Override public String getResponseBodyExcerpt(int maxLength) throws IOException { String contentType = getContentType(); String charset = "UTF-8"; if (contentType != null) { for (String part : contentType.split(";")) { if (part.startsWith("charset=")) { charset = part.substring("charset=".length()); } } } InputStream responseInput = getResponseBodyAsStream(); String response = contentToString(charset); return response.length() <= maxLength ? response : response.substring(0,maxLength); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Results run(String tomlString) { if (tomlString.isEmpty()) { return results; } String[] lines = tomlString.split("[\\n\\r]"); StringBuilder multilineBuilder = new StringBuilder(); Multiline multiline = Multiline.NONE; String key = null; String value = null; for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (line != null && multiline.isTrimmable()) { line = line.trim(); } if (isComment(line) || line.isEmpty()) { continue; } if (isTableArray(line)) { String tableName = Keys.getTableArrayName(line); if (tableName != null) { results.startTableArray(tableName); String afterTableName = line.substring(tableName.length() + 4); if (!isComment(afterTableName)) { results.errors.append("Invalid table array definition: " + line + "\n\n"); } } else { results.errors.append("Invalid table array definition: " + line + "\n\n"); } continue; } if (multiline.isNotMultiline() && isTable(line)) { String tableName = Keys.getTableName(line); if (tableName != null) { results.startTables(tableName); } else { results.errors.append("Invalid table definition: " + line + "\n\n"); } continue; } if (multiline.isNotMultiline() && !line.contains("=")) { results.errors.append("Invalid key definition: " + line); continue; } String[] pair = line.split("=", 2); if (multiline.isNotMultiline() && MULTILINE_ARRAY_REGEX.matcher(pair[1].trim()).matches()) { multiline = Multiline.ARRAY; key = pair[0].trim(); multilineBuilder.append(removeComment(pair[1])); continue; } if (multiline.isNotMultiline() && pair[1].trim().startsWith("\"\"\"")) { multiline = Multiline.STRING; multilineBuilder.append(pair[1]); key = pair[0].trim(); if (pair[1].trim().indexOf("\"\"\"", 3) > -1) { multiline = Multiline.NONE; pair[1] = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { if (multilineBuilder.toString().trim().length() > 3) { multilineBuilder.append('\n'); } continue; } } if (multiline.isNotMultiline() && pair[1].trim().startsWith(STRING_LITERAL_DELIMITER)) { multiline = Multiline.STRING_LITERAL; multilineBuilder.append(pair[1]); key = pair[0].trim(); if (pair[1].trim().indexOf(STRING_LITERAL_DELIMITER, 3) > -1) { multiline = Multiline.NONE; pair[1] = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { if (multilineBuilder.toString().trim().length() > 3) { multilineBuilder.append('\n'); } continue; } } if (multiline == Multiline.ARRAY) { String lineWithoutComment = removeComment(line); multilineBuilder.append(lineWithoutComment); if (MULTILINE_ARRAY_REGEX_END.matcher(lineWithoutComment).matches()) { multiline = Multiline.NONE; value = multilineBuilder.toString(); multilineBuilder.delete(0, multilineBuilder.length()); } else { continue; } } else if (multiline == Multiline.STRING) { multilineBuilder.append(line); if (line.contains("\"\"\"")) { multiline = Multiline.NONE; value = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { multilineBuilder.append('\n'); continue; } } else if (multiline == Multiline.STRING_LITERAL) { multilineBuilder.append(line); if (line.contains(STRING_LITERAL_DELIMITER)) { multiline = Multiline.NONE; value = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { multilineBuilder.append('\n'); continue; } } else { key = Keys.getKey(pair[0]); if (key == null) { results.errors.append("Invalid key name: " + pair[0] + "\n"); continue; } value = pair[1].trim(); } Object convertedValue = VALUE_ANALYSIS.convert(value); if (convertedValue != INVALID) { results.addValue(key, convertedValue); } else { results.errors.append("Invalid key/value: " + key + " = " + value + "\n"); } } if (multiline != Multiline.NONE) { results.errors.append("Unterminated multiline " + multiline.toString().toLowerCase().replace('_', ' ') + "\n"); } return results; }
#vulnerable code Results run(String tomlString) { if (tomlString.isEmpty()) { return results; } String[] lines = tomlString.split("[\\n\\r]"); StringBuilder multilineBuilder = new StringBuilder(); Multiline multiline = Multiline.NONE; String key = null; String value = null; for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (line != null && multiline.isTrimmable()) { line = line.trim(); } if (isComment(line) || line.isEmpty()) { continue; } if (isTableArray(line)) { String tableName = getTableArrayName(line); if (tableName != null) { results.startTableArray(tableName); String afterTableName = line.substring(tableName.length() + 4); if (!isComment(afterTableName)) { results.errors.append("Invalid table array definition: " + line + "\n\n"); } } else { results.errors.append("Invalid table array definition: " + line + "\n\n"); } continue; } if (multiline.isNotMultiline() && isTable(line)) { String tableName = getTableName(line); if (tableName != null) { results.startTables(tableName); } else { results.errors.append("Invalid table definition: " + line + "\n\n"); } continue; } if (multiline.isNotMultiline() && !line.contains("=")) { results.errors.append("Invalid key definition: " + line); continue; } String[] pair = line.split("=", 2); if (multiline.isNotMultiline() && MULTILINE_ARRAY_REGEX.matcher(pair[1].trim()).matches()) { multiline = Multiline.ARRAY; key = pair[0].trim(); multilineBuilder.append(removeComment(pair[1])); continue; } if (multiline.isNotMultiline() && pair[1].trim().startsWith("\"\"\"")) { multiline = Multiline.STRING; multilineBuilder.append(pair[1]); key = pair[0].trim(); if (pair[1].trim().indexOf("\"\"\"", 3) > -1) { multiline = Multiline.NONE; pair[1] = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { if (multilineBuilder.toString().trim().length() > 3) { multilineBuilder.append('\n'); } continue; } } if (multiline.isNotMultiline() && pair[1].trim().startsWith(STRING_LITERAL_DELIMITER)) { multiline = Multiline.STRING_LITERAL; multilineBuilder.append(pair[1]); key = pair[0].trim(); if (pair[1].trim().indexOf(STRING_LITERAL_DELIMITER, 3) > -1) { multiline = Multiline.NONE; pair[1] = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { if (multilineBuilder.toString().trim().length() > 3) { multilineBuilder.append('\n'); } continue; } } if (multiline == Multiline.ARRAY) { String lineWithoutComment = removeComment(line); multilineBuilder.append(lineWithoutComment); if (MULTILINE_ARRAY_REGEX_END.matcher(lineWithoutComment).matches()) { multiline = Multiline.NONE; value = multilineBuilder.toString(); multilineBuilder.delete(0, multilineBuilder.length()); } else { continue; } } else if (multiline == Multiline.STRING) { multilineBuilder.append(line); if (line.contains("\"\"\"")) { multiline = Multiline.NONE; value = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { multilineBuilder.append('\n'); continue; } } else if (multiline == Multiline.STRING_LITERAL) { multilineBuilder.append(line); if (line.contains(STRING_LITERAL_DELIMITER)) { multiline = Multiline.NONE; value = multilineBuilder.toString().trim(); multilineBuilder.delete(0, multilineBuilder.length()); } else { multilineBuilder.append('\n'); continue; } } else { key = pair[0].trim(); value = pair[1].trim(); } if (!isKeyValid(key)) { results.errors.append("Invalid key name: " + key + "\n"); continue; } Object convertedValue = VALUE_ANALYSIS.convert(value); if (convertedValue != INVALID) { results.addValue(key, convertedValue); } else { results.errors.append("Invalid key/value: " + key + " = " + value + "\n"); } } if (multiline != Multiline.NONE) { results.errors.append("Unterminated multiline " + multiline.toString().toLowerCase().replace('_', ' ') + "\n"); } return results; } #location 133 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void starten() { daten = new Daten(pfad); Daten.nogui = true; if (!userAgent.equals("")) { Daten.setUserAgentManuel(userAgent); } // Infos schreiben Log.startMeldungen(this.getClass().getName()); if (senderAllesLaden) { Log.systemMeldung("Programmstart: alles laden"); } else { Log.systemMeldung("Programmstart: nur update laden"); } Log.systemMeldung("ImportUrl: " + importUrl); Log.systemMeldung("Outputfile: " + output); Log.systemMeldung(""); Log.systemMeldung(""); Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { @Override public void fertig(ListenerFilmeLadenEvent event) { undTschuess(true /* exit */); } }); // laden was es schon gibt //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); new IoXmlFilmlisteLesen().standardFilmlisteLesen(); // das eigentliche Suchen der Filme bei den Sendern starten Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); }
#vulnerable code public void starten() { daten = new Daten(pfad); Daten.nogui = true; if (!userAgent.equals("")) { Daten.setUserAgentManuel(userAgent); } // Infos schreiben Log.startMeldungen(this.getClass().getName()); if (senderAllesLaden) { Log.systemMeldung("Programmstart: alles laden"); } else { Log.systemMeldung("Programmstart: nur update laden"); } Log.systemMeldung("ImportUrl: " + importUrl); Log.systemMeldung("Outputfile: " + output); Log.systemMeldung(""); Log.systemMeldung(""); Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { @Override public void fertig(ListenerFilmeLadenEvent event) { undTschuess(true /* exit */); } }); // laden was es schon gibt Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); // das eigentliche Suchen der Filme bei den Sendern starten Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getPfadVlc() { if (Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) { new DialogOk(null, true, new PanelProgrammPfade(), "Pfade Standardprogramme").setVisible(true); } return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR]; }
#vulnerable code public static String getPfadVlc() { /////////////////////// if (!Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) { return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR]; } final String PFAD_LINUX_VLC = "/usr/bin/vlc"; final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; String pfad = ""; if (System.getProperty("os.name").toLowerCase().contains("windows")) { pfad = getWindowsVlcPath(); } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { pfad = PFAD_LINUX_VLC; } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { pfad = PFAD_MAC_VLC; } if (new File(pfad).exists()) { return pfad; } else { return ""; } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getPfadFlv() { if (Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { new DialogOk(null, true, new PanelProgrammPfade(), "Pfade Standardprogramme").setVisible(true); } return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; }
#vulnerable code public static String getPfadFlv() { ///////////////////// if (!Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; } final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer"; final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe"; String pfad = ""; if (System.getProperty("os.name").toLowerCase().contains("windows")) { pfad = GuiFunktionenProgramme.getPathJar() + PFAD_WINDOWS_FLV; } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { pfad = PFAD_LINUX_FLV; } if (new File(pfad).exists()) { return pfad; } else { return ""; } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getMusterPfadMplayer() { final String PFAD_LINUX = "/usr/bin/mplayer"; final String PFAD_MAC = "/opt/local/bin/mplayer"; final String PFAD_WIN_DEFAULT = "C:\\Program Files\\SMPlayer\\mplayer\\mplayer.exe"; final String PFAD_WIN = "\\SMPlayer\\mplayer\\mplayer.exe"; String pfad; switch (getOs()) { case OS_LINUX: pfad = PFAD_LINUX; break; case OS_MAC: pfad = PFAD_MAC; break; case OS_WIN_32BIT: case OS_WIN_64BIT: case OS_UNKNOWN: default: if (System.getenv("ProgramFiles") != null) { pfad = System.getenv("ProgramFiles") + PFAD_WIN; } else if (System.getenv("ProgramFiles(x86)") != null) { pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; } else { pfad = PFAD_WIN_DEFAULT; } } if (!new File(pfad).exists()) { pfad = ""; } return pfad; }
#vulnerable code public static String getMusterPfadMplayer() { final String PFAD_LINUX = "/usr/bin/mplayer"; final String PFAD_MAC = "/opt/local/bin/mplayer"; String pfad = ""; if (System.getProperty("os.name").toLowerCase().contains("windows")) { pfad = getWindowsMplayerPath(); } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { pfad = PFAD_LINUX; } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { pfad = PFAD_MAC; } if (new File(pfad).exists()) { return pfad; } else { return ""; } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void starten() { daten = new Daten(pfad); Daten.nogui = true; if (!userAgent.equals("")) { Daten.setUserAgentManuel(userAgent); } // Infos schreiben Log.startMeldungen(this.getClass().getName()); if (senderAllesLaden) { Log.systemMeldung("Programmstart: alles laden"); } else { Log.systemMeldung("Programmstart: nur update laden"); } Log.systemMeldung("ImportUrl: " + importUrl); Log.systemMeldung("Outputfile: " + output); Log.systemMeldung(""); Log.systemMeldung(""); Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { @Override public void fertig(ListenerFilmeLadenEvent event) { undTschuess(true /* exit */); } }); // laden was es schon gibt //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); new IoXmlFilmlisteLesen().standardFilmlisteLesen(); // das eigentliche Suchen der Filme bei den Sendern starten Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); }
#vulnerable code public void starten() { daten = new Daten(pfad); Daten.nogui = true; if (!userAgent.equals("")) { Daten.setUserAgentManuel(userAgent); } // Infos schreiben Log.startMeldungen(this.getClass().getName()); if (senderAllesLaden) { Log.systemMeldung("Programmstart: alles laden"); } else { Log.systemMeldung("Programmstart: nur update laden"); } Log.systemMeldung("ImportUrl: " + importUrl); Log.systemMeldung("Outputfile: " + output); Log.systemMeldung(""); Log.systemMeldung(""); Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { @Override public void fertig(ListenerFilmeLadenEvent event) { undTschuess(true /* exit */); } }); // laden was es schon gibt Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); // das eigentliche Suchen der Filme bei den Sendern starten Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { try { setBackground(null); setForeground(null); setFont(null); setIcon(null); setHorizontalAlignment(SwingConstants.LEADING); super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); int r = table.convertRowIndexToModel(row); int c = table.convertColumnIndexToModel(column); String url = table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_URL_NR).toString(); DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); // Abos boolean abo = !table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_ABO_NR).equals(""); // Starts Start s = ddaten.starterClass.getStart(url); if (s != null) { setColor(this, s, isSelected); } if (c == DatenDownload.DOWNLOAD_RESTZEIT_NR) { this.setText(download.getTextRestzeit(ddaten, s)); } else if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) { int i = Integer.parseInt(download.arr[DatenDownload.DOWNLOAD_PROGRESS_NR]); setHorizontalAlignment(SwingConstants.CENTER); if (s != null && 1 < i && i < DatenDownload.PROGRESS_FERTIG) { JProgressBar progressBar = new JProgressBar(0, 1000); JPanel panel = new JPanel(new BorderLayout()); if (s != null) { setColor(panel, s, isSelected); setColor(progressBar, s, isSelected); } progressBar.setBorder(BorderFactory.createEmptyBorder()); progressBar.setStringPainted(true); progressBar.setUI(new BasicProgressBarUI() { @Override protected Color getSelectionBackground() { return UIManager.getDefaults().getColor("Table.foreground"); } @Override protected Color getSelectionForeground() { return Color.white; } }); panel.add(progressBar); panel.setBorder(BorderFactory.createEmptyBorder()); progressBar.setValue(i); double d = i / 10.0; progressBar.setString(Double.toString(d) + "%"); return panel; } else { this.setText(download.getTextProgress(ddaten, s)); } } else if (c == DatenDownload.DOWNLOAD_ABO_NR) { setFont(new java.awt.Font("Dialog", Font.BOLD, 12)); if (abo) { setForeground(GuiKonstanten.ABO_FOREGROUND); } else { setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png"))); setHorizontalAlignment(SwingConstants.CENTER); } } else if (c == DatenDownload.DOWNLOAD_PROGRAMM_RESTART_NR) { boolean restart = download.isRestart(); setHorizontalAlignment(SwingConstants.CENTER); if (restart) { setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/ja_16.png"))); } else { setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png"))); } } } catch (Exception ex) { Log.fehlerMeldung(758200166, Log.FEHLER_ART_PROG, this.getClass().getName(), ex); } return this; }
#vulnerable code @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { try { setBackground(null); setForeground(null); setFont(null); setIcon(null); setHorizontalAlignment(SwingConstants.LEADING); super.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); int r = table.convertRowIndexToModel(row); int c = table.convertColumnIndexToModel(column); String url = table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_URL_NR).toString(); // Abos boolean abo = !table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_ABO_NR).equals(""); // Starts Start s = ddaten.starterClass.getStart(url); if (s != null) { setColor(this, s, isSelected); if (c == DatenDownload.DOWNLOAD_RESTZEIT_NR) { if (s.restSekunden > 0) { if (s.restSekunden < 60) { this.setText("< 1 Min."); } else { this.setText(Long.toString(s.restSekunden / 60) + " Min."); } } else { this.setText(""); } } else if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) { int i = Integer.parseInt(s.datenDownload.arr[DatenDownload.DOWNLOAD_PROGRESS_NR]); setHorizontalAlignment(SwingConstants.CENTER); if (i == -1) { // noch nicht gestartet this.setText(""); } else if (i == DatenDownload.PROGRESS_WARTEN) { this.setText("warten"); } else if (i == DatenDownload.PROGRESS_GESTARTET) { this.setText("gestartet"); } else if (1 < i && i < DatenDownload.PROGRESS_FERTIG) { ////// return new ProgressPanel(s).progressPanel(); JProgressBar progressBar = new JProgressBar(0, 1000); JPanel panel = new JPanel(new BorderLayout()); setColor(panel, s, isSelected); setColor(progressBar, s, isSelected); progressBar.setBorder(BorderFactory.createEmptyBorder()); progressBar.setStringPainted(true); progressBar.setUI(new BasicProgressBarUI() { @Override protected Color getSelectionBackground() { return UIManager.getDefaults().getColor("Table.foreground"); } @Override protected Color getSelectionForeground() { return Color.white; } }); panel.add(progressBar); panel.setBorder(BorderFactory.createEmptyBorder()); progressBar.setValue(i); double d = i / 10.0; progressBar.setString(Double.toString(d) + "%"); return panel; } else if (i == DatenDownload.PROGRESS_FERTIG) { if (s != null) { if (s.status == Start.STATUS_ERR) { this.setText("fehlerhaft"); } else { this.setText("fertig"); } } else { this.setText("fertig"); } } } } else { if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) { this.setText(""); } } if (c == DatenDownload.DOWNLOAD_ABO_NR) { setFont(new java.awt.Font("Dialog", Font.BOLD, 12)); if (abo) { setForeground(GuiKonstanten.ABO_FOREGROUND); } else { setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png"))); setHorizontalAlignment(SwingConstants.CENTER); } } if (c == DatenDownload.DOWNLOAD_PROGRAMM_RESTART_NR) { boolean restart = ddaten.listeDownloads.getDownloadByUrl(url).isRestart(); setHorizontalAlignment(SwingConstants.CENTER); if (restart) { setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/ja_16.png"))); } else { setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png"))); } } } catch (Exception ex) { Log.fehlerMeldung(758200166, Log.FEHLER_ART_PROG, this.getClass().getName(), ex); } return this; } #location 99 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void addToListNormal() { //<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br /> //<a style="margin-left:20px;" href="?programm=168&amp;id=14487&amp;ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br /> //<a style="margin-left:20px;" href="?programm=168&amp;id=14485&amp;ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br /> final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/"; final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\""; final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">"; final String MUSTER_DATUM = "title=\"Sendung vom "; listeThemen.clear(); seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); int pos = 0; int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2; String url, thema, datum, titel; while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) { try { thema = ""; pos += MUSTER_THEMA.length(); stop = seite.indexOf(MUSTER_THEMA, pos); pos1 = pos; if ((pos2 = seite.indexOf("<", pos1)) != -1) { thema = seite.substring(pos1, pos2); } while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) { titel = ""; datum = ""; if (stop != -1 && pos1 > stop) { // dann schon das nächste Thema break; } pos1 += MUSTER_URL.length(); if ((pos2 = seite.indexOf("\"", pos1)) != -1) { url = seite.substring(pos1, pos2); //if (!url.equals("")) { url = StringEscapeUtils.unescapeXml(url); if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) { // Datum if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) { pDatum1 += MUSTER_DATUM.length(); if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) { if (stop != -1 && pDatum1 < stop && pDatum2 < stop) { // dann schon das nächste Thema datum = seite.substring(pDatum1, pDatum2); } } } // Titel if ((pTitel1 = seite.indexOf(">", pos2)) != -1) { pTitel1 += 1; if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) { //if (stop != -1 && pTitel1 > stop && pTitel2 > stop) { if (stop != -1 && pTitel1 < stop && pTitel2 < stop) { titel = seite.substring(pTitel1, pTitel2); } } } // in die Liste eintragen String[] add = new String[]{ADRESSE + url, thema, titel, datum}; listeThemen.addUrl(add); } } } } catch (Exception ex) { Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, ""); } } }
#vulnerable code void ladenHttp(String filmWebsite, String thema, String alter) { // erst die Nummer suchen // >25420<4<165<23. Die b // <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg< final String MUSTER_BILD = "<http://www."; seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); String nummer, url, bild, urlFilm, titel; nummer = seiteHttp.extract(">", "<"); bild = seiteHttp.extract(MUSTER_BILD, "<"); if (!bild.isEmpty()) { bild = "http://www." + bild; } // die URL bauen: // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az if (!nummer.isEmpty()) { url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az"; seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); final String MUSTER_URL = "var videofile = \""; final String MUSTER_TITEL = "var videotitle = \""; urlFilm = seiteHttp.extract(MUSTER_URL, "\""); titel = seiteHttp.extract(MUSTER_TITEL, "\""); if (!urlFilm.equals("")) { meldung(urlFilm); // DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp, // String datum, String zeit, // long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) { DatenFilm film = null; if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) { film.addUrlKlein(urlFilm, ""); } else { // dann gibs ihn noch nicht addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */, ""/*datum*/, ""/*zeit*/, 0, "", bild, "", new String[]{""})); } } else { Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite); } } } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getPfadFlv() { if (Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { new DialogOk(null, true, new PanelProgrammPfade(), "Pfade Standardprogramme").setVisible(true); } return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; }
#vulnerable code public static String getPfadFlv() { ///////////////////// if (!Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; } final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer"; final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe"; String pfad = ""; if (System.getProperty("os.name").toLowerCase().contains("windows")) { pfad = GuiFunktionenProgramme.getPathJar() + PFAD_WINDOWS_FLV; } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { pfad = PFAD_LINUX_FLV; } if (new File(pfad).exists()) { return pfad; } else { return ""; } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void starten() { daten = new Daten(pfad); Daten.nogui = true; if (!userAgent.equals("")) { Daten.setUserAgentManuel(userAgent); } // Infos schreiben Log.startMeldungen(this.getClass().getName()); if (senderAllesLaden) { Log.systemMeldung("Programmstart: alles laden"); } else { Log.systemMeldung("Programmstart: nur update laden"); } Log.systemMeldung("ImportUrl: " + importUrl); Log.systemMeldung("Outputfile: " + output); Log.systemMeldung(""); Log.systemMeldung(""); Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { @Override public void fertig(ListenerFilmeLadenEvent event) { undTschuess(true /* exit */); } }); // laden was es schon gibt //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); new IoXmlFilmlisteLesen().standardFilmlisteLesen(); if (!senderLoeschen.isEmpty()) { senderLoeschenUndExit(); } else { // das eigentliche Suchen der Filme bei den Sendern starten Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); } }
#vulnerable code public void starten() { daten = new Daten(pfad); Daten.nogui = true; if (!userAgent.equals("")) { Daten.setUserAgentManuel(userAgent); } // Infos schreiben Log.startMeldungen(this.getClass().getName()); if (senderAllesLaden) { Log.systemMeldung("Programmstart: alles laden"); } else { Log.systemMeldung("Programmstart: nur update laden"); } Log.systemMeldung("ImportUrl: " + importUrl); Log.systemMeldung("Outputfile: " + output); Log.systemMeldung(""); Log.systemMeldung(""); Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { @Override public void fertig(ListenerFilmeLadenEvent event) { undTschuess(true /* exit */); } }); // laden was es schon gibt //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); new IoXmlFilmlisteLesen().standardFilmlisteLesen(); if (!senderLoeschen.isEmpty()) { senderLoeschenUndExit(); } // das eigentliche Suchen der Filme bei den Sendern starten Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION