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 @Test public void testAppender() throws Exception { for (int i = 0; i < 8; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); for (final File file : files) { assertHeader(file); assertFooter(file); } final File logFile = new File(LOGFILE); assertThat(logFile, exists()); assertHeader(logFile); }
#vulnerable code @Test public void testAppender() throws Exception { for (int i = 0; i < 8; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); for (final File file : files) { assertHeader(file); assertFooter(file); } final File logFile = new File(LOGFILE); assertTrue("Expected logfile to exist: " + LOGFILE, logFile.exists()); assertHeader(logFile); } #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 testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); }
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); Message msg = message instanceof Message ? (ObjectMessage) message : new ObjectMessage(message); logger.log(null, fqcn, lvl, msg, t); }
#vulnerable code public void forcedLog(String fqcn, Priority level, Object message, Throwable t) { org.apache.logging.log4j.Level lvl = org.apache.logging.log4j.Level.toLevel(level.toString()); logger.log(null, fqcn, lvl, new ObjectMessage(message), t); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addScript(Script script) { ScriptEngine engine = manager.getEngineByName(script.getLanguage()); if (engine == null) { logger.error("No ScriptEngine found for language " + script.getLanguage() + ". Available languages are: " + languages); return; } if (engine.getFactory().getParameter("THREADING") == null) { scripts.put(script.getName(), new ThreadLocalScriptRunner(script)); } else { scripts.put(script.getName(), new MainScriptRunner(engine, script)); } }
#vulnerable code public void addScript(Script script) { ScriptEngine engine = manager.getEngineByName(script.getLanguage()); if (engine == null) { logger.error("No ScriptEngine found for language " + script.getLanguage()); } if (engine.getFactory().getParameter("THREADING") == null) { scripts.put(script.getName(), new ThreadLocalScriptRunner(script)); } else { scripts.put(script.getName(), new MainScriptRunner(engine, script)); } } #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 testAppender() throws Exception { final Logger logger = ctx.getLogger(); logger.debug("This is test message number 1"); Thread.sleep(1500); // Trigger the rollover for (int i = 0; i < 16; ++i) { logger.debug("This is test message number " + i + 1); } final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final int MAX_TRIES = 20; final Matcher<File[]> hasGzippedFile = hasItemInArray(that(hasName(that(endsWith(".gz"))))); for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); if (hasGzippedFile.matches(files)) { return; // test succeeded } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No compressed files found"); }
#vulnerable code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); logger.debug("This is test message number 1"); Thread.sleep(1500); // Trigger the rollover for (int i = 0; i < 16; ++i) { logger.debug("This is test message number " + i + 1); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final int MAX_TRIES = 20; for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); for (final File file : files) { if (file.getName().endsWith(".gz")) { return; // test succeeded } } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No compressed files found"); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void logToFile() throws Exception { final FileOutputStream fos = new FileOutputStream(LOGFILE, false); fos.flush(); fos.close(); final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test"); logger.debug("This is a test"); final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE))); try { int count = 0; String str = ""; while (is.available() != 0) { str = is.readLine(); ++count; } assertTrue("Incorrect count " + count, count == 1); assertTrue("Bad data", str.endsWith("This is a test")); } finally { is.close(); } }
#vulnerable code @Test public void logToFile() throws Exception { final FileOutputStream fos = new FileOutputStream(LOGFILE, false); fos.flush(); fos.close(); final Logger logger = LogManager.getLogger("org.apache.logging.log4j.test2.Test"); logger.debug("This is a test"); final DataInputStream is = new DataInputStream(new BufferedInputStream(new FileInputStream(LOGFILE))); int count = 0; String str = ""; while (is.available() != 0) { str = is.readLine(); ++count; } assertTrue("Incorrect count " + count, count == 1); assertTrue("Bad data", str.endsWith("This is a test")); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) throws Exception { final JmsTopicReceiver receiver = new JmsTopicReceiver(); receiver.doMain(args); }
#vulnerable code public static void main(final String[] args) throws Exception { if (args.length != 4) { usage("Wrong number of arguments."); } final String tcfBindingName = args[0]; final String topicBindingName = args[1]; final String username = args[2]; final String password = args[3]; final JmsServer server = new JmsServer(tcfBindingName, topicBindingName, username, password); server.start(); final Charset enc = Charset.defaultCharset(); final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, enc)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JmsTopicReceiver."); while (true) { final String line = stdin.readLine(); if (line == null || line.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); server.stop(); return; } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConfig() { final Configuration config = context.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No StructuredDataFilter", filter); assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter); final StructuredDataFilter sdFilter = (StructuredDataFilter) filter; assertFalse("Should not be And filter", sdFilter.isAnd()); final Map<String, List<String>> map = sdFilter.getMap(); assertNotNull("No Map", map); assertFalse("No elements in Map", map.isEmpty()); assertEquals("Incorrect number of elements in Map", 1, map.size()); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertEquals("List does not contain 2 elements", 2, map.get("eventId").size()); }
#vulnerable code @Test public void testConfig() { final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-sdfilter.xml"); final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No StructuredDataFilter", filter); assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter); final StructuredDataFilter sdFilter = (StructuredDataFilter) filter; assertFalse("Should not be And filter", sdFilter.isAnd()); final Map<String, List<String>> map = sdFilter.getMap(); assertNotNull("No Map", map); assertFalse("No elements in Map", map.isEmpty()); assertEquals("Incorrect number of elements in Map", 1, map.size()); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertEquals("List does not contain 2 elements", 2, map.get("eventId").size()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMissingRootLogger() throws Exception { final LoggerContext ctx = context.getContext(); final Logger logger = ctx.getLogger("sample.Logger1"); assertTrue("Logger should have the INFO level enabled", logger.isInfoEnabled()); assertFalse("Logger should have the DEBUG level disabled", logger.isDebugEnabled()); final Configuration config = ctx.getConfiguration(); assertNotNull("Config not null", config); // final String MISSINGROOT = "MissingRootTest"; // assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(), // MISSINGROOT.equals(config.getName())); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders not null", map); assertEquals("There should only be two appenders", 2, map.size()); assertTrue("Contains List", map.containsKey("List")); assertTrue("Contains Console", map.containsKey("Console")); final Map<String, LoggerConfig> loggerMap = config.getLoggers(); assertNotNull("loggerMap not null", loggerMap); assertEquals("There should only be one configured logger", 1, loggerMap.size()); // only the sample logger, no root logger in loggerMap! assertTrue("contains key=sample", loggerMap.containsKey("sample")); final LoggerConfig sample = loggerMap.get("sample"); final Map<String, Appender> sampleAppenders = sample.getAppenders(); assertEquals("The sample logger should only have one appender", 1, sampleAppenders.size()); // sample only has List appender, not Console! assertTrue("The sample appender should be a ListAppender", sampleAppenders.containsKey("List")); final AbstractConfiguration baseConfig = (AbstractConfiguration) config; final LoggerConfig root = baseConfig.getRootLogger(); final Map<String, Appender> rootAppenders = root.getAppenders(); assertEquals("The root logger should only have one appender", 1, rootAppenders.size()); // root only has Console appender! assertTrue("The root appender should be a ConsoleAppender", rootAppenders.containsKey("Console")); assertEquals(Level.ERROR, root.getLevel()); }
#vulnerable code @Test public void testMissingRootLogger() throws Exception { PluginManager.addPackage("org.apache.logging.log4j.test.appender"); final LoggerContext ctx = Configurator.initialize("Test1", "missingRootLogger.xml"); final Logger logger = LogManager.getLogger("sample.Logger1"); final Configuration config = ctx.getConfiguration(); assertNotNull("Config not null", config); // final String MISSINGROOT = "MissingRootTest"; // assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(), // MISSINGROOT.equals(config.getName())); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders not null", map); assertEquals("Appenders Size", 2, map.size()); assertTrue("Contains List", map.containsKey("List")); assertTrue("Contains Console", map.containsKey("Console")); final Map<String, LoggerConfig> loggerMap = config.getLoggers(); assertNotNull("loggerMap not null", loggerMap); assertEquals("loggerMap Size", 1, loggerMap.size()); // only the sample logger, no root logger in loggerMap! assertTrue("contains key=sample", loggerMap.containsKey("sample")); final LoggerConfig sample = loggerMap.get("sample"); final Map<String, Appender> sampleAppenders = sample.getAppenders(); assertEquals("sampleAppenders Size", 1, sampleAppenders.size()); // sample only has List appender, not Console! assertTrue("sample has appender List", sampleAppenders.containsKey("List")); final AbstractConfiguration baseConfig = (AbstractConfiguration) config; final LoggerConfig root = baseConfig.getRootLogger(); final Map<String, Appender> rootAppenders = root.getAppenders(); assertEquals("rootAppenders Size", 1, rootAppenders.size()); // root only has Console appender! assertTrue("root has appender Console", rootAppenders.containsKey("Console")); assertEquals(Level.ERROR, root.getLevel()); logger.isDebugEnabled(); Configurator.shutdown(ctx); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { try (final FileInputStream fis = new FileInputStream(source); final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) { zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; }
#vulnerable code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { final FileInputStream fis = new FileInputStream(source); final FileOutputStream fos = new FileOutputStream(destination); final ZipOutputStream zos = new ZipOutputStream(fos); zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } zos.close(); fis.close(); if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); try (final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream()) { filteredOut.flush(); } verify(out); }
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream(); filteredOut.flush(); filteredOut.close(); verify(out); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Object deserializeStream(final String witness) throws Exception { try (final ObjectInputStream objIs = new ObjectInputStream(new FileInputStream(witness))) { return objIs.readObject(); } }
#vulnerable code public static Object deserializeStream(final String witness) throws Exception { final FileInputStream fileIs = new FileInputStream(witness); final ObjectInputStream objIs = new ObjectInputStream(fileIs); try { return objIs.readObject(); } finally { objIs.close(); } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz")))))); }
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { if (file.getName().endsWith(".gz")) { found = true; break; } } assertTrue("No compressed files found", found); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { try (final FileInputStream fis = new FileInputStream(source); final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destination))) { zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; }
#vulnerable code public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) throws IOException { if (source.exists()) { final FileInputStream fis = new FileInputStream(source); final FileOutputStream fos = new FileOutputStream(destination); final ZipOutputStream zos = new ZipOutputStream(fos); zos.setLevel(level); final ZipEntry zipEntry = new ZipEntry(source.getName()); zos.putNextEntry(zipEntry); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { zos.write(inbuf, 0, n); } zos.close(); fis.close(); if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static OutputStream getOutputStream(final boolean follow, final Target target) { final PrintStream printStream = target == Target.SYSTEM_OUT ? follow ? new PrintStream(new SystemOutStream()) : System.out : follow ? new PrintStream(new SystemErrStream()) : System.err; PropertiesUtil propsUtil = PropertiesUtil.getProperties(); if (!propsUtil.getStringProperty("os.name").startsWith("Windows") || propsUtil.getBooleanProperty("log4j.skipJansi")) { return printStream; } else { try { final ClassLoader loader = Loader.getClassLoader(); // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); return (OutputStream) constructor.newInstance(printStream); } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed"); } catch (final NoSuchMethodException nsme) { LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); } catch (final Exception ex) { LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); } return printStream; } }
#vulnerable code private static OutputStream getOutputStream(final boolean follow, final Target target) { final PrintStream printStream = target == Target.SYSTEM_OUT ? follow ? new PrintStream(new SystemOutStream()) : System.out : follow ? new PrintStream(new SystemErrStream()) : System.err; if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) { return printStream; } else { try { final ClassLoader loader = Loader.getClassLoader(); // We type the parameter as a wildcard to avoid a hard reference to Jansi. final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream"); final Constructor<?> constructor = clazz.getConstructor(OutputStream.class); return (OutputStream) constructor.newInstance(printStream); } catch (final ClassNotFoundException cnfe) { LOGGER.debug("Jansi is not installed"); } catch (final NoSuchMethodException nsme) { LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor"); } catch (final Exception ex) { LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream"); } return printStream; } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static boolean execute(final File source, final File destination, final boolean deleteSource) throws IOException { if (source.exists()) { try (final FileInputStream fis = new FileInputStream(source); final BufferedOutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream( destination)))) { final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { os.write(inbuf, 0, n); } } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; }
#vulnerable code public static boolean execute(final File source, final File destination, final boolean deleteSource) throws IOException { if (source.exists()) { final FileInputStream fis = new FileInputStream(source); final FileOutputStream fos = new FileOutputStream(destination); final GZIPOutputStream gzos = new GZIPOutputStream(fos); final BufferedOutputStream os = new BufferedOutputStream(gzos); final byte[] inbuf = new byte[BUF_SIZE]; int n; while ((n = fis.read(inbuf)) != -1) { os.write(inbuf, 0, n); } os.close(); fis.close(); if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; } return false; } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; }
#vulnerable code @Override protected void releaseSub() { if (transceiver != null) { try { transceiver.close(); } catch (final IOException ioe) { LOGGER.error("Attempt to clean up Avro transceiver failed", ioe); } } client = null; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public byte[] toByteArray(final LogEvent event) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new PrivateObjectOutputStream(baos); try { oos.writeObject(event); } finally { oos.close(); } } catch (IOException ioe) { LOGGER.error("Serialization of LogEvent failed.", ioe); } return baos.toByteArray(); }
#vulnerable code public byte[] toByteArray(final LogEvent event) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new PrivateObjectOutputStream(baos); oos.writeObject(event); } catch (IOException ioe) { LOGGER.error("Serialization of LogEvent failed.", ioe); } return baos.toByteArray(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testJmsTopicAppenderCompatibility() throws Exception { final JmsAppender appender = (JmsAppender) ctx.getRequiredAppender("JmsTopicAppender"); final LogEvent expected = createLogEvent(); appender.append(expected); then(session).should().createObjectMessage(eq(expected)); then(objectMessage).should().setJMSTimestamp(anyLong()); then(messageProducer).should().send(objectMessage); appender.stop(); then(session).should().close(); then(connection).should().close(); }
#vulnerable code @Test public void testJmsTopicAppenderCompatibility() throws Exception { assertEquals(0, topic.size()); final JmsAppender appender = (JmsAppender) ctx.getRequiredAppender("JmsTopicAppender"); final LogEvent expected = createLogEvent(); appender.append(expected); assertEquals(1, topic.size()); final Message message = topic.getMessageAt(0); assertNotNull(message); assertThat(message, instanceOf(ObjectMessage.class)); final ObjectMessage objectMessage = (ObjectMessage) message; final Object o = objectMessage.getObject(); assertThat(o, instanceOf(LogEvent.class)); final LogEvent actual = (LogEvent) o; assertEquals(expected.getMessage().getFormattedMessage(), actual.getMessage().getFormattedMessage()); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) throws Exception { final JmsQueueReceiver receiver = new JmsQueueReceiver(); receiver.doMain(args); }
#vulnerable code public static void main(final String[] args) throws Exception { if (args.length != 4) { usage("Wrong number of arguments."); } final String qcfBindingName = args[0]; final String queueBindingName = args[1]; final String username = args[2]; final String password = args[3]; final JmsServer server = new JmsServer(qcfBindingName, queueBindingName, username, password); server.start(); final Charset enc = Charset.defaultCharset(); final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, enc)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JmsQueueReceiver."); while (true) { final String line = stdin.readLine(); if (line == null || line.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); server.stop(); return; } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMemMapExtendsIfNeeded() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final Logger log = LogManager.getLogger(); final char[] text = new char[200]; Arrays.fill(text, 'A'); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", 256, f.length()); log.warn(new String(text)); assertEquals("grown", 256 * 2, f.length()); log.warn(new String(text)); assertEquals("grown again", 256 * 3, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.lineSeparator().length(); assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length()); String line1, line2, line3, line4; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); assertNotNull(line2); assertThat(line2, containsString(new String(text))); assertNotNull(line3); assertThat(line3, containsString(new String(text))); assertNull("only three lines were logged", line4); }
#vulnerable code @Test public void testMemMapExtendsIfNeeded() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final Logger log = LogManager.getLogger(); final char[] text = new char[200]; Arrays.fill(text, 'A'); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", 256, f.length()); log.warn(new String(text)); assertEquals("grown", 256 * 2, f.length()); log.warn(new String(text)); assertEquals("grown again", 256 * 3, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.getProperty("line.separator").length(); assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length()); String line1, line2, line3, line4; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); line4 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); assertNotNull(line2); assertThat(line2, containsString(new String(text))); assertNotNull(line3); assertThat(line3, containsString(new String(text))); assertNull("only three lines were logged", line4); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void setupQueue() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener listener = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(listener); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new QueueConnectionFactoryImpl() ); //context.rebind(QUEUE_NAME, new MockQueue(QUEUE_NAME)); //System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); //receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); }
#vulnerable code private static void setupQueue() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener l = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(l); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new QueueConnectionFactoryImpl() ); //context.rebind(QUEUE_NAME, new MockQueue(QUEUE_NAME)); //System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); //receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) throws Exception { final JmsQueueReceiver receiver = new JmsQueueReceiver(); receiver.doMain(args); }
#vulnerable code public static void main(final String[] args) throws Exception { if (args.length != 4) { usage("Wrong number of arguments."); } final String qcfBindingName = args[0]; final String queueBindingName = args[1]; final String username = args[2]; final String password = args[3]; final JmsServer server = new JmsServer(qcfBindingName, queueBindingName, username, password); server.start(); final Charset enc = Charset.defaultCharset(); final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in, enc)); // Loop until the word "exit" is typed System.out.println("Type \"exit\" to quit JmsQueueReceiver."); while (true) { final String line = stdin.readLine(); if (line == null || line.equalsIgnoreCase("exit")) { System.out.println("Exiting. Kill the application if it does not exit " + "due to daemon threads."); server.stop(); return; } } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Charset getSupportedCharset(final String charsetName) { Charset charset = null; if (charsetName != null) { if (Charset.isSupported(charsetName)) { charset = Charset.forName(charsetName); } } if (charset == null) { charset = UTF_8; if (charsetName != null) { StatusLogger.getLogger().error("Charset " + charsetName + " is not supported for layout, using " + charset.displayName()); } } return charset; }
#vulnerable code public static Charset getSupportedCharset(final String charsetName) { Charset charset = null; if (charsetName != null) { if (Charset.isSupported(charsetName)) { charset = Charset.forName(charsetName); } } if (charset == null) { charset = Charset.forName(UTF_8); if (charsetName != null) { StatusLogger.getLogger().error("Charset " + charsetName + " is not supported for layout, using " + charset.displayName()); } } return charset; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GenerateMicroBenchmark public String test03_getCallerClassNameReflectively() { return ReflectionUtil.getCallerClass(3).getName(); }
#vulnerable code @GenerateMicroBenchmark public String test03_getCallerClassNameReflectively() { return ReflectiveCallerClassUtility.getCaller(3).getName(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); final Matcher<File> withCorrectFileName = both(hasName(that(endsWith(".log")))).and(hasName(that(startsWith("test1")))); assertThat(files, hasItemInArray(withCorrectFileName)); }
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { final String name = file.getName(); if (name.startsWith("test1") && name.endsWith(".log")) { found = true; break; } } assertTrue("No archived files found", found); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReconnect() throws Exception { List<String> list = new ArrayList<String>(); TestSocketServer server = new TestSocketServer(list); server.start(); Thread.sleep(300); //System.err.println("Initializing logger"); final Logger logger = LogManager.getLogger(SocketReconnectTest.class); String message = "Log #1"; logger.error(message); String expectedHeader = "Header"; String msg = null; String header = null; for (int i = 0; i < 5; ++i) { Thread.sleep(100); if (list.size() > 1) { header = list.get(0); msg = list.get(1); break; } } assertNotNull("No header", header); assertEquals(expectedHeader, header); assertNotNull("No message", msg); assertEquals(message, msg); server.shutdown(); server.join(); list.clear(); message = "Log #2"; boolean exceptionCaught = false; for (int i = 0; i < 5; ++i) { try { logger.error(message); } catch (final AppenderRuntimeException e) { exceptionCaught = true; break; // System.err.println("Caught expected exception"); } } assertTrue("No Exception thrown", exceptionCaught); message = "Log #3"; server = new TestSocketServer(list); server.start(); Thread.sleep(300); msg = null; header = null; logger.error(message); for (int i = 0; i < 5; ++i) { Thread.sleep(100); if (list.size() > 1) { header = list.get(0); msg = list.get(1); break; } } assertNotNull("No header", header); assertEquals(expectedHeader, header); assertNotNull("No message", msg); assertEquals(message, msg); server.shutdown(); server.join(); }
#vulnerable code @Test public void testReconnect() throws Exception { TestSocketServer testServer = null; ExecutorService executor = null; Future<InputStream> futureIn; final InputStream in; try { executor = Executors.newSingleThreadExecutor(); System.err.println("Initializing server"); testServer = new TestSocketServer(); futureIn = executor.submit(testServer); Thread.sleep(300); //System.err.println("Initializing logger"); final Logger logger = LogManager.getLogger(SocketReconnectTest.class); String message = "Log #1"; logger.error(message); BufferedReader reader = new BufferedReader(new InputStreamReader(futureIn.get())); assertEquals(message, reader.readLine()); closeQuietly(testServer); executor.shutdown(); try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) { System.err.println("Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } message = "Log #2"; logger.error(message); message = "Log #3"; try { logger.error(message); } catch (final AppenderRuntimeException e) { // System.err.println("Caught expected exception"); } //System.err.println("Re-initializing server"); executor = Executors.newSingleThreadExecutor(); testServer = new TestSocketServer(); futureIn = executor.submit(testServer); Thread.sleep(500); try { logger.error(message); reader = new BufferedReader(new InputStreamReader(futureIn.get())); assertEquals(message, reader.readLine()); } catch (final AppenderRuntimeException e) { e.printStackTrace(); fail("Unexpected Exception"); } //System.err.println("Sleeping to demonstrate repeated re-connections"); //Thread.sleep(5000); } finally { closeQuietly(testServer); closeQuietly(executor); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void forceRemap(final int linesPerIteration, final int iterations, final IPerfTestRunner runner) { final int LINESEP = System.lineSeparator().getBytes(Charset.defaultCharset()).length; final int bytesPerLine = 0 + IPerfTestRunner.THROUGHPUT_MSG.getBytes().length; final int bytesWritten = bytesPerLine * linesPerIteration * iterations; final int threshold = 1073741824; // magic number: defined in perf9MMapLocation.xml int todo = threshold - bytesWritten; if (todo <= 0) { return; } final byte[] filler = new byte[4096]; Arrays.fill(filler, (byte) 'X'); final String str = new String(filler, Charset.defaultCharset()); do { runner.log(str); } while ((todo -= (4096 + LINESEP)) > 0); }
#vulnerable code private void forceRemap(final int linesPerIteration, final int iterations, final IPerfTestRunner runner) { final int LINESEP = System.getProperty("line.separator").getBytes(Charset.defaultCharset()).length; final int bytesPerLine = 0 + IPerfTestRunner.THROUGHPUT_MSG.getBytes().length; final int bytesWritten = bytesPerLine * linesPerIteration * iterations; final int threshold = 1073741824; // magic number: defined in perf9MMapLocation.xml int todo = threshold - bytesWritten; if (todo <= 0) { return; } final byte[] filler = new byte[4096]; Arrays.fill(filler, (byte) 'X'); final String str = new String(filler, Charset.defaultCharset()); do { runner.log(str); } while ((todo -= (4096 + LINESEP)) > 0); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void setupQueue() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener listener = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(listener); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new TopicConnectionFactoryImpl() ); //context.rebind(QUEUE_NAME, new MockQueue(QUEUE_NAME)); //System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); //receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); }
#vulnerable code private static void setupQueue() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener l = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(l); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new TopicConnectionFactoryImpl() ); //context.rebind(QUEUE_NAME, new MockQueue(QUEUE_NAME)); //System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); //receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); } #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 testWrite_multiplesOfBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, RandomAccessFileManager.DEFAULT_BUFFER_SIZE, null, null); final int size = RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3; final byte[] data = new byte[size]; manager.write(data); // no buffer overflow exception // buffer is full but not flushed yet assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 2, raf.length()); }}
#vulnerable code @Test public void testWrite_multiplesOfBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); final RandomAccessFile raf = new RandomAccessFile(file, "rw"); final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, RandomAccessFileManager.DEFAULT_BUFFER_SIZE, null, null); final int size = RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3; final byte[] data = new byte[size]; manager.write(data); // no buffer overflow exception // buffer is full but not flushed yet assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 2, raf.length()); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWrite_dataExceedingMinBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final int bufferSize = 1; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, bufferSize, null, null); final int size = bufferSize * 3 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(bufferSize * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now }}
#vulnerable code @Test public void testWrite_dataExceedingMinBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); final RandomAccessFile raf = new RandomAccessFile(file, "rw"); final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final int bufferSize = 1; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, bufferSize, null, null); final int size = bufferSize * 3 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(bufferSize * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public T build() { verify(); // first try to use a builder class if one is available try { LOGGER.debug("Building Plugin[name={}, class={}]. Searching for builder factory method...", pluginType.getElementName(), pluginType.getPluginClass().getName()); final Builder<T> builder = createBuilder(this.clazz); if (builder != null) { injectFields(builder); final T result = builder.build(); LOGGER.debug("Built Plugin[name={}] OK from builder factory method.", pluginType.getElementName()); return result; } } catch (final Exception e) { LOGGER.error("Unable to inject fields into builder class for plugin type {}, element {}.", this.clazz, node.getName(), e); } // or fall back to factory method if no builder class is available try { LOGGER.debug("Still building Plugin[name={}, class={}]. Searching for factory method...", pluginType.getElementName(), pluginType.getPluginClass().getName()); final Method factory = findFactoryMethod(this.clazz); final Object[] params = generateParameters(factory); @SuppressWarnings("unchecked") final T plugin = (T) factory.invoke(null, params); LOGGER.debug("Built Plugin[name={}] OK from factory method.", pluginType.getElementName()); return plugin; } catch (final Exception e) { LOGGER.error("Unable to invoke factory method in class {} for element {}.", this.clazz, this.node.getName(), e); return null; } }
#vulnerable code @Override public T build() { verify(); // first try to use a builder class if one is available try { LOGGER.debug("Building Plugin[name={}, class={}]. Searching for builder factory method...", pluginType.getElementName(), pluginType.getPluginClass().getName()); final Builder<T> builder = createBuilder(this.clazz); if (builder != null) { injectFields(builder); final T result = builder.build(); LOGGER.debug("Built Plugin[name={}] OK from builder factory method.", pluginType.getElementName()); return result; } } catch (final Exception e) { LOGGER.catching(Level.ERROR, e); LOGGER.error("Unable to inject fields into builder class for plugin type {}, element {}.", this.clazz, node.getName()); } // or fall back to factory method if no builder class is available try { LOGGER.debug("Still building Plugin[name={}, class={}]. Searching for factory method...", pluginType.getElementName(), pluginType.getPluginClass().getName()); final Method factory = findFactoryMethod(this.clazz); final Object[] params = generateParameters(factory); @SuppressWarnings("unchecked") final T plugin = (T) factory.invoke(null, params); LOGGER.debug("Built Plugin[name={}] OK from factory method.", pluginType.getElementName()); return plugin; } catch (final Exception e) { LOGGER.catching(Level.ERROR, e); LOGGER.error("Unable to invoke factory method in class {} for element {}.", this.clazz, this.node.getName()); return null; } } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz")))))); }
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } Thread.sleep(50); final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { if (file.getName().endsWith(".gz")) { found = true; break; } } assertTrue("No compressed files found", found); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Object deserializeStream(final String witness) throws Exception { final FileInputStream fileIs = new FileInputStream(witness); final ObjectInputStream objIs = new ObjectInputStream(fileIs); try { return objIs.readObject(); } finally { objIs.close(); } }
#vulnerable code public static Object deserializeStream(final String witness) throws Exception { final FileInputStream fileIs = new FileInputStream(witness); final ObjectInputStream objIs = new ObjectInputStream(fileIs); return objIs.readObject(); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) throws Exception { final CommandLineArguments cla = parseCommandLine(args, TcpSocketServer.class, new CommandLineArguments()); if (cla.isHelp()) { return; } if (cla.getConfigLocation() != null) { ConfigurationFactory.setConfigurationFactory(new ServerConfigurationFactory(cla.getConfigLocation())); } final TcpSocketServer<ObjectInputStream> socketServer = TcpSocketServer .createSerializedSocketServer(cla.getPort(), cla.getBacklog(), cla.getLocalBindAddress()); final Thread serverThread = new Log4jThread(socketServer); serverThread.start(); if (cla.isInteractive()) { final Charset enc = Charset.defaultCharset(); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, enc)); while (true) { final String line = reader.readLine(); if (line == null || line.equalsIgnoreCase("Quit") || line.equalsIgnoreCase("Stop") || line.equalsIgnoreCase("Exit")) { socketServer.shutdown(); serverThread.join(); break; } } } }
#vulnerable code public static void main(final String[] args) throws Exception { if (args.length < 1 || args.length > 2) { System.err.println("Incorrect number of arguments: " + args.length); printUsage(); return; } final int port = Integer.parseInt(args[0]); if (port <= 0 || port >= MAX_PORT) { System.err.println("Invalid port number: " + port); printUsage(); return; } if (args.length == 2 && args[1].length() > 0) { ConfigurationFactory.setConfigurationFactory(new ServerConfigurationFactory(args[1])); } final TcpSocketServer<ObjectInputStream> socketServer = TcpSocketServer.createSerializedSocketServer(port); final Thread serverThread = new Log4jThread(socketServer); serverThread.start(); final Charset enc = Charset.defaultCharset(); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, enc)); while (true) { final String line = reader.readLine(); if (line == null || line.equalsIgnoreCase("Quit") || line.equalsIgnoreCase("Stop") || line.equalsIgnoreCase("Exit")) { socketServer.shutdown(); serverThread.join(); break; } } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void checkConfiguration() { final long current; if (((counter.incrementAndGet() & MASK) == 0) && ((current = System.nanoTime()) - nextCheck >= 0)) { LOCK.lock(); try { nextCheck = current + intervalNano; final long currentLastModified = file.lastModified(); if (currentLastModified > lastModified) { lastModified = currentLastModified; for (final ConfigurationListener listener : listeners) { final Thread thread = new Thread(new ReconfigurationWorker(listener, reconfigurable)); thread.setDaemon(true); thread.start(); } } } finally { LOCK.unlock(); } } }
#vulnerable code @Override public void checkConfiguration() { final long current; if (((counter.incrementAndGet() & MASK) == 0) && ((current = System.currentTimeMillis()) >= nextCheck)) { LOCK.lock(); try { nextCheck = current + intervalSeconds; if (file.lastModified() > lastModified) { lastModified = file.lastModified(); for (final ConfigurationListener listener : listeners) { final Thread thread = new Thread(new ReconfigurationWorker(listener, reconfigurable)); thread.setDaemon(true); thread.start(); } } } finally { LOCK.unlock(); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMemMapBasics() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final Logger log = LogManager.getLogger(); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length()); log.warn("Test log2"); assertEquals("not grown", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.lineSeparator().length(); assertEquals("Shrunk to actual used size", 186 + 2 * LINESEP, f.length()); String line1, line2, line3; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); assertNotNull(line2); assertThat(line2, containsString("Test log2")); assertNull("only two lines were logged", line3); }
#vulnerable code @Test public void testMemMapBasics() throws Exception { final File f = new File(LOGFILE); if (f.exists()) { assertTrue(f.delete()); } assertTrue(!f.exists()); final Logger log = LogManager.getLogger(); try { log.warn("Test log1"); assertTrue(f.exists()); assertEquals("initial length", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length()); log.warn("Test log2"); assertEquals("not grown", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length()); } finally { CoreLoggerContexts.stopLoggerContext(false); } final int LINESEP = System.getProperty("line.separator").length(); assertEquals("Shrunk to actual used size", 186 + 2 * LINESEP, f.length()); String line1, line2, line3; try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) { line1 = reader.readLine(); line2 = reader.readLine(); line3 = reader.readLine(); } assertNotNull(line1); assertThat(line1, containsString("Test log1")); assertNotNull(line2); assertThat(line2, containsString("Test log2")); assertNull("only two lines were logged", line3); } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void getStream_Marker() { final PrintWriter stream = logger.printWriter(MarkerManager.getMarker("HI"), Level.INFO); stream.println("println"); stream.print("print with embedded newline\n"); stream.println("last line"); stream.close(); assertEquals(3, results.size()); assertEquals("println 1", "HI INFO println", results.get(0)); assertEquals("print with embedded newline", "HI INFO print with embedded newline", results.get(1)); assertEquals("println 2", "HI INFO last line", results.get(2)); }
#vulnerable code @Test public void getStream_Marker() { final LoggerStream stream = logger.getStream(MarkerManager.getMarker("HI"), Level.INFO); stream.println("Hello, world!"); stream.print("How about this?\n"); stream.println("Is this thing on?"); assertEquals(3, results.size()); assertThat("Incorrect message.", results.get(0), startsWith("HI INFO Hello")); assertThat("Incorrect message.", results.get(1), startsWith("HI INFO How about")); assertThat("Incorrect message.", results.get(2), startsWith("HI INFO Is this")); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerFilterOutputStream los = new LoggerFilterOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); }
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void encode(final ConcurrentMap<String, ConcurrentMap<String, PluginType<?>>> map) { final String fileName = rootDir + PATH + FILENAME; DataOutputStream dos = null; try { final File file = new File(rootDir + PATH); file.mkdirs(); final FileOutputStream fos = new FileOutputStream(fileName); final BufferedOutputStream bos = new BufferedOutputStream(fos); dos = new DataOutputStream(bos); dos.writeInt(map.size()); for (final Map.Entry<String, ConcurrentMap<String, PluginType<?>>> outer : map.entrySet()) { dos.writeUTF(outer.getKey()); dos.writeInt(outer.getValue().size()); for (final Map.Entry<String, PluginType<?>> entry : outer.getValue().entrySet()) { dos.writeUTF(entry.getKey()); final PluginType<?> pt = entry.getValue(); dos.writeUTF(pt.getPluginClass().getName()); dos.writeUTF(pt.getElementName()); dos.writeBoolean(pt.isObjectPrintable()); dos.writeBoolean(pt.isDeferChildren()); } } } catch (final Exception ex) { ex.printStackTrace(); } finally { Closer.closeSilent(dos); } }
#vulnerable code private static void encode(final ConcurrentMap<String, ConcurrentMap<String, PluginType<?>>> map) { final String fileName = rootDir + PATH + FILENAME; DataOutputStream dos = null; try { final File file = new File(rootDir + PATH); file.mkdirs(); final FileOutputStream fos = new FileOutputStream(fileName); final BufferedOutputStream bos = new BufferedOutputStream(fos); dos = new DataOutputStream(bos); dos.writeInt(map.size()); for (final Map.Entry<String, ConcurrentMap<String, PluginType<?>>> outer : map.entrySet()) { dos.writeUTF(outer.getKey()); dos.writeInt(outer.getValue().size()); for (final Map.Entry<String, PluginType<?>> entry : outer.getValue().entrySet()) { dos.writeUTF(entry.getKey()); final PluginType<?> pt = entry.getValue(); dos.writeUTF(pt.getPluginClass().getName()); dos.writeUTF(pt.getElementName()); dos.writeBoolean(pt.isObjectPrintable()); dos.writeBoolean(pt.isDeferChildren()); } } } catch (final Exception ex) { ex.printStackTrace(); } finally { try { dos.close(); } catch (final Exception ignored) { // nothing we can do here... } } } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static EnumMap<Level, String> createLevelStyleMap(final String[] options) { if (options.length < 2) { return DEFAULT_STYLES; } Map<String, String> styles = AnsiEscape.createMap(options[1]); EnumMap<Level, String> levelStyles = new EnumMap<Level, String>(DEFAULT_STYLES); for (Map.Entry<String, String> entry : styles.entrySet()) { final Level key = Level.valueOf(entry.getKey()); if (key == null) { LOGGER.error("Unkown level name: " + entry.getKey()); } else { levelStyles.put(key, entry.getValue()); } } return levelStyles; }
#vulnerable code private static EnumMap<Level, String> createLevelStyleMap(final String[] options) { Map<String, String> styles = options.length < 2 ? null : AnsiEscape.createMap(options[1]); EnumMap<Level, String> levelStyles = new EnumMap<Level, String>(LEVEL_STYLES_DEFAULT); for (Map.Entry<String, String> entry : styles.entrySet()) { final Level key = Level.valueOf(entry.getKey()); if (key == null) { LOGGER.error("Unkown level name: " + entry.getKey()); } else { levelStyles.put(key, entry.getValue()); } } return levelStyles; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addScript(Script script) { ScriptEngine engine = manager.getEngineByName(script.getLanguage()); if (engine == null) { logger.error("No ScriptEngine found for language " + script.getLanguage() + ". Available languages are: " + languages); return; } if (engine.getFactory().getParameter("THREADING") == null) { scripts.put(script.getName(), new ThreadLocalScriptRunner(script)); } else { scripts.put(script.getName(), new MainScriptRunner(engine, script)); } }
#vulnerable code public void addScript(Script script) { ScriptEngine engine = manager.getEngineByName(script.getLanguage()); if (engine == null) { logger.error("No ScriptEngine found for language " + script.getLanguage()); } if (engine.getFactory().getParameter("THREADING") == null) { scripts.put(script.getName(), new ThreadLocalScriptRunner(script)); } else { scripts.put(script.getName(), new MainScriptRunner(engine, script)); } } #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 testReconnect() throws Exception { List<String> list = new ArrayList<String>(); TestSocketServer server = new TestSocketServer(list); server.start(); Thread.sleep(300); //System.err.println("Initializing logger"); final Logger logger = LogManager.getLogger(SocketReconnectTest.class); String message = "Log #1"; logger.error(message); String expectedHeader = "Header"; String msg = null; String header = null; for (int i = 0; i < 5; ++i) { Thread.sleep(100); if (list.size() > 1) { header = list.get(0); msg = list.get(1); break; } } assertNotNull("No header", header); assertEquals(expectedHeader, header); assertNotNull("No message", msg); assertEquals(message, msg); server.shutdown(); server.join(); list.clear(); message = "Log #2"; boolean exceptionCaught = false; for (int i = 0; i < 5; ++i) { try { logger.error(message); } catch (final AppenderRuntimeException e) { exceptionCaught = true; break; // System.err.println("Caught expected exception"); } } assertTrue("No Exception thrown", exceptionCaught); message = "Log #3"; server = new TestSocketServer(list); server.start(); Thread.sleep(300); msg = null; header = null; logger.error(message); for (int i = 0; i < 5; ++i) { Thread.sleep(100); if (list.size() > 1) { header = list.get(0); msg = list.get(1); break; } } assertNotNull("No header", header); assertEquals(expectedHeader, header); assertNotNull("No message", msg); assertEquals(message, msg); server.shutdown(); server.join(); }
#vulnerable code @Test public void testReconnect() throws Exception { TestSocketServer testServer = null; ExecutorService executor = null; Future<InputStream> futureIn; final InputStream in; try { executor = Executors.newSingleThreadExecutor(); System.err.println("Initializing server"); testServer = new TestSocketServer(); futureIn = executor.submit(testServer); Thread.sleep(300); //System.err.println("Initializing logger"); final Logger logger = LogManager.getLogger(SocketReconnectTest.class); String message = "Log #1"; logger.error(message); BufferedReader reader = new BufferedReader(new InputStreamReader(futureIn.get())); assertEquals(message, reader.readLine()); closeQuietly(testServer); executor.shutdown(); try { // Wait a while for existing tasks to terminate if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) { System.err.println("Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted executor.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } message = "Log #2"; logger.error(message); message = "Log #3"; try { logger.error(message); } catch (final AppenderRuntimeException e) { // System.err.println("Caught expected exception"); } //System.err.println("Re-initializing server"); executor = Executors.newSingleThreadExecutor(); testServer = new TestSocketServer(); futureIn = executor.submit(testServer); Thread.sleep(500); try { logger.error(message); reader = new BufferedReader(new InputStreamReader(futureIn.get())); assertEquals(message, reader.readLine()); } catch (final AppenderRuntimeException e) { e.printStackTrace(); fail("Unexpected Exception"); } //System.err.println("Sleeping to demonstrate repeated re-connections"); //Thread.sleep(5000); } finally { closeQuietly(testServer); closeQuietly(executor); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWrite_dataExceedingMinBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final int bufferSize = 1; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, bufferSize, null, null); final int size = bufferSize * 3 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(bufferSize * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now }}
#vulnerable code @Test public void testWrite_dataExceedingMinBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); final RandomAccessFile raf = new RandomAccessFile(file, "rw"); final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final int bufferSize = 1; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, bufferSize, null, null); final int size = bufferSize * 3 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(bufferSize * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @BeforeClass public static void setupClass() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener listener = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(listener); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new QueueConnectionFactoryImpl() ); context.rebind(QUEUE_NAME, new MockQueue(QUEUE_NAME)); ((LoggerContext) LogManager.getContext()).reconfigure(); receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); }
#vulnerable code @BeforeClass public static void setupClass() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener l = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(l); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new QueueConnectionFactoryImpl() ); context.rebind(QUEUE_NAME, new MockQueue(QUEUE_NAME)); ((LoggerContext) LogManager.getContext()).reconfigure(); receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); assertThat(files, hasItemInArray(that(hasName(that(endsWith(fileExtension)))))); }
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { if (file.getName().endsWith(fileExtension)) { found = true; break; } } assertTrue("No compressed files found", found); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAsyncLogUsesNanoTimeClock() throws Exception { final File file = new File("target", "NanoTimeToFileTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); final AsyncLogger log = (AsyncLogger) LogManager.getLogger("com.foo.Bar"); final long before = System.nanoTime(); log.info("Use actual System.nanoTime()"); assertTrue("using SystemNanoClock", log.getNanoClock() instanceof SystemNanoClock); final long DUMMYNANOTIME = -53; log.getContext().getConfiguration().setNanoClock(new DummyNanoClock(DUMMYNANOTIME)); log.updateConfiguration(log.getContext().getConfiguration()); // trigger a new nano clock lookup log.updateConfiguration(log.getContext().getConfiguration()); log.info("Use dummy nano clock"); assertTrue("using SystemNanoClock", log.getNanoClock() instanceof DummyNanoClock); CoreLoggerContexts.stopLoggerContext(file); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(file)); final String line1 = reader.readLine(); final String line2 = reader.readLine(); // System.out.println(line1); // System.out.println(line2); reader.close(); file.delete(); assertNotNull("line1", line1); assertNotNull("line2", line2); final String[] line1Parts = line1.split(" AND "); assertEquals("Use actual System.nanoTime()", line1Parts[2]); assertEquals(line1Parts[0], line1Parts[1]); long loggedNanoTime = Long.parseLong(line1Parts[0]); assertTrue("used system nano time", loggedNanoTime - before < TimeUnit.SECONDS.toNanos(1)); final String[] line2Parts = line2.split(" AND "); assertEquals("Use dummy nano clock", line2Parts[2]); assertEquals(String.valueOf(DUMMYNANOTIME), line2Parts[0]); assertEquals(String.valueOf(DUMMYNANOTIME), line2Parts[1]); }
#vulnerable code @Test public void testAsyncLogUsesNanoTimeClock() throws Exception { final File file = new File("target", "NanoTimeToFileTest.log"); // System.out.println(f.getAbsolutePath()); file.delete(); final AsyncLogger log = (AsyncLogger) LogManager.getLogger("com.foo.Bar"); final long before = System.nanoTime(); log.info("Use actual System.nanoTime()"); assertTrue("using SystemNanoClock", log.getNanoClock() instanceof SystemNanoClock); NanoClockFactory.setMode(Mode.Dummy); final long DUMMYNANOTIME = 0; // trigger a new nano clock lookup log.updateConfiguration(log.getContext().getConfiguration()); log.info("Use dummy nano clock"); assertTrue("using SystemNanoClock", log.getNanoClock() instanceof DummyNanoClock); CoreLoggerContexts.stopLoggerContext(file); // stop async thread final BufferedReader reader = new BufferedReader(new FileReader(file)); final String line1 = reader.readLine(); final String line2 = reader.readLine(); // System.out.println(line1); // System.out.println(line2); reader.close(); file.delete(); assertNotNull("line1", line1); assertNotNull("line2", line2); final String[] line1Parts = line1.split(" AND "); assertEquals("Use actual System.nanoTime()", line1Parts[2]); assertEquals(line1Parts[0], line1Parts[1]); long loggedNanoTime = Long.parseLong(line1Parts[0]); assertTrue("used system nano time", loggedNanoTime - before < TimeUnit.SECONDS.toNanos(1)); final String[] line2Parts = line2.split(" AND "); assertEquals("Use dummy nano clock", line2Parts[2]); assertEquals(String.valueOf(DUMMYNANOTIME), line2Parts[0]); assertEquals(String.valueOf(DUMMYNANOTIME), line2Parts[1]); } #location 42 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @BeforeClass public static void setupClass() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener listener = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(listener); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new TopicConnectionFactoryImpl() ); context.rebind(TOPIC_NAME, new MockTopic(TOPIC_NAME) ); ((LoggerContext) LogManager.getContext()).reconfigure(); receiver = new JmsTopicReceiver(FACTORY_NAME, TOPIC_NAME, null, null); }
#vulnerable code @BeforeClass public static void setupClass() throws Exception { // MockContextFactory becomes the primary JNDI provider final StatusConsoleListener l = new StatusConsoleListener(Level.ERROR); StatusLogger.getLogger().registerListener(l); MockContextFactory.setAsInitial(); context = new InitialContext(); context.rebind(FACTORY_NAME, new TopicConnectionFactoryImpl() ); context.rebind(TOPIC_NAME, new MockTopic(TOPIC_NAME) ); ((LoggerContext) LogManager.getContext()).reconfigure(); receiver = new JmsTopicReceiver(FACTORY_NAME, TOPIC_NAME, null, null); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWrite_multiplesOfBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) { final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, RandomAccessFileManager.DEFAULT_BUFFER_SIZE, null, null); final int size = RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3; final byte[] data = new byte[size]; manager.write(data); // no buffer overflow exception // buffer is full but not flushed yet assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 2, raf.length()); }}
#vulnerable code @Test public void testWrite_multiplesOfBufferSize() throws IOException { final File file = File.createTempFile("log4j2", "test"); file.deleteOnExit(); final RandomAccessFile raf = new RandomAccessFile(file, "rw"); final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM; final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, RandomAccessFileManager.DEFAULT_BUFFER_SIZE, null, null); final int size = RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3; final byte[] data = new byte[size]; manager.write(data); // no buffer overflow exception // buffer is full but not flushed yet assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 2, raf.length()); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNoArgBuilderCallerClassInfo() throws Exception { try (final PrintStream ps = IoBuilder.forLogger().buildPrintStream()) { ps.println("discarded"); final ListAppender app = context.getListAppender("IoBuilderTest"); final List<String> messages = app.getMessages(); assertThat(messages, not(empty())); assertThat(messages, hasSize(1)); final String message = messages.get(0); assertThat(message, startsWith(getClass().getName() + ".testNoArgBuilderCallerClassInfo")); app.clear(); } }
#vulnerable code @Test public void testNoArgBuilderCallerClassInfo() throws Exception { final PrintStream ps = IoBuilder.forLogger().buildPrintStream(); ps.println("discarded"); final ListAppender app = context.getListAppender("IoBuilderTest"); final List<String> messages = app.getMessages(); assertThat(messages, not(empty())); assertThat(messages, hasSize(1)); final String message = messages.get(0); assertThat(message, startsWith(getClass().getName() + ".testNoArgBuilderCallerClassInfo")); app.clear(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String toSerializable(final LogEvent event) { final Message message = event.getMessage(); final Object[] parameters = message.getParameters(); final StringBuilder buffer = getStringBuilder(); // Revisit when 1.3 is out so that we do not need to create a new // printer for each event. // No need to close the printer. try (final CSVPrinter printer = new CSVPrinter(buffer, getFormat())) { printer.printRecord(parameters); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(message, e); return getFormat().getCommentMarker() + " " + e; } }
#vulnerable code @Override public String toSerializable(final LogEvent event) { final Message message = event.getMessage(); final Object[] parameters = message.getParameters(); final StringBuilder buffer = prepareStringBuilder(strBuilder); try { // Revisit when 1.3 is out so that we do not need to create a new // printer for each event. // No need to close the printer. final CSVPrinter printer = new CSVPrinter(buffer, getFormat()); printer.printRecord(parameters); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(message, e); return getFormat().getCommentMarker() + " " + e; } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); try (final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream()) { filteredOut.flush(); } verify(out); }
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream(); filteredOut.flush(); filteredOut.close(); verify(out); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertThat(dir, both(exists()).and(hasFiles())); final File[] files = dir.listFiles(); assertNotNull(files); final Matcher<File> withCorrectFileName = both(hasName(that(endsWith(".log")))).and(hasName(that(startsWith("test1")))); assertThat(files, hasItemInArray(withCorrectFileName)); }
#vulnerable code @Test public void testAppender() throws Exception { for (int i=0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertTrue("No files created", files.length > 0); boolean found = false; for (final File file : files) { final String name = file.getName(); if (name.startsWith("test1") && name.endsWith(".log")) { found = true; break; } } assertTrue("No archived files found", found); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void encode(final ConcurrentMap<String, ConcurrentMap<String, PluginType>> map) { final String fileName = rootDir + PATH + FILENAME; DataOutputStream dos = null; try { final File file = new File(rootDir + PATH); file.mkdirs(); final FileOutputStream fos = new FileOutputStream(fileName); final BufferedOutputStream bos = new BufferedOutputStream(fos); dos = new DataOutputStream(bos); dos.writeInt(map.size()); for (final Map.Entry<String, ConcurrentMap<String, PluginType>> outer : map.entrySet()) { dos.writeUTF(outer.getKey()); dos.writeInt(outer.getValue().size()); for (final Map.Entry<String, PluginType> entry : outer.getValue().entrySet()) { dos.writeUTF(entry.getKey()); final PluginType pt = entry.getValue(); dos.writeUTF(pt.getPluginClass().getName()); dos.writeUTF(pt.getElementName()); dos.writeBoolean(pt.isObjectPrintable()); dos.writeBoolean(pt.isDeferChildren()); } } } catch (final Exception ex) { ex.printStackTrace(); } finally { try { dos.close(); } catch (Exception ignored) { // nothing we can do here... } } }
#vulnerable code private static void encode(final ConcurrentMap<String, ConcurrentMap<String, PluginType>> map) { final String fileName = rootDir + PATH + FILENAME; try { final File file = new File(rootDir + PATH); file.mkdirs(); final FileOutputStream fos = new FileOutputStream(fileName); final BufferedOutputStream bos = new BufferedOutputStream(fos); final DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(map.size()); for (final Map.Entry<String, ConcurrentMap<String, PluginType>> outer : map.entrySet()) { dos.writeUTF(outer.getKey()); dos.writeInt(outer.getValue().size()); for (final Map.Entry<String, PluginType> entry : outer.getValue().entrySet()) { dos.writeUTF(entry.getKey()); final PluginType pt = entry.getValue(); dos.writeUTF(pt.getPluginClass().getName()); dos.writeUTF(pt.getElementName()); dos.writeBoolean(pt.isObjectPrintable()); dos.writeBoolean(pt.isDeferChildren()); } } dos.close(); } catch (final Exception ex) { ex.printStackTrace(); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean isFiltered(LogEvent event) { Filters f = filters; if (f.hasFilters()) { for (Filter filter : f) { if (filter.filter(event) == Filter.Result.DENY) { return true; } } } return false; }
#vulnerable code protected boolean isFiltered(LogEvent event) { if (hasFilters) { for (Filter filter : filters) { if (filter.filter(event) == Filter.Result.DENY) { return true; } } } return false; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void log(final LogEvent event) { beforeLogEvent(); try { if (!isFiltered(event)) { processLogEvent(event); } } finally { afterLogEvent(); } }
#vulnerable code public void log(final LogEvent event) { counter.incrementAndGet(); try { if (isFiltered(event)) { return; } event.setIncludeLocation(isIncludeLocation()); callAppenders(event); if (additive && parent != null) { parent.log(event); } } finally { if (counter.decrementAndGet() == 0) { shutdownLock.lock(); try { if (shutdown.get()) { noLogEvents.signalAll(); } } finally { shutdownLock.unlock(); } } } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); try (final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream()) { filteredOut.flush(); } verify(out); }
#vulnerable code @Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock(OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()) .filter(out) .setLevel(LEVEL) .buildOutputStream(); filteredOut.flush(); filteredOut.close(); verify(out); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); String doLogStr = servletConfig.getInitParameter(P_LOG); if (doLogStr != null) { this.doLog = Boolean.parseBoolean(doLogStr); } String doForwardIPString = servletConfig.getInitParameter(P_FORWARDEDFOR); if (doForwardIPString != null) { this.doForwardIP = Boolean.parseBoolean(doForwardIPString); } try { targetUriObj = new URI(servletConfig.getInitParameter(P_TARGET_URI)); } catch (Exception e) { throw new RuntimeException("Trying to process targetUri init parameter: "+e,e); } targetUri = targetUriObj.toString(); HttpParams hcParams = new BasicHttpParams(); readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class); proxyClient = createHttpClient(hcParams); }
#vulnerable code @Override public void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); String doLogStr = servletConfig.getInitParameter(P_LOG); if (doLogStr != null) { this.doLog = Boolean.parseBoolean(doLogStr); } String doForwardIPString = servletConfig.getInitParameter(P_FORWARDEDFOR); if (doForwardIPString != null) { this.doForwardIP = Boolean.parseBoolean(doForwardIPString); } targetUri = servletConfig.getInitParameter(P_TARGET_URI); if (!(targetUri.contains("$") || targetUri.contains("{"))) { try { targetUriObj = new URI(targetUri); } catch (Exception e) { throw new RuntimeException("Trying to process targetUri init parameter: "+e,e); } targetUri = targetUriObj.toString(); } HttpParams hcParams = new BasicHttpParams(); readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class); proxyClient = createHttpClient(hcParams); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void commonInitialization(IntVar[] list, int[] weights, IntVar sum) { queueIndex = 1; assert (list.length == weights.length) : "\nLength of two vectors different in SumWeight"; numberArgs = (short) (list.length + 1); numberId = idNumber.incrementAndGet(); this.sum = sum; HashMap<IntVar, Integer> parameters = new HashMap<IntVar, Integer>(); for (int i = 0; i < list.length; i++) { assert (list[i] != null) : i + "-th element of list in SumWeighted constraint is null"; if (parameters.get(list[i]) != null) { // variable ordered in the scope of the Sum Weight constraint. Integer coeff = parameters.get(list[i]); Integer sumOfCoeff = coeff + weights[i]; parameters.put(list[i], sumOfCoeff); } else parameters.put(list[i], weights[i]); } assert (parameters.get(sum) == null) : "Sum variable is used in both sides of SumeWeight constraint."; this.list = new IntVar[parameters.size()]; this.weights = new int[parameters.size()]; int i = 0; for (Map.Entry<IntVar,Integer> e : parameters.entrySet()) { this.list[i] = e.getKey(); this.weights[i] = e.getValue(); i++; } checkForOverflow(); }
#vulnerable code private void commonInitialization(IntVar[] list, int[] weights, IntVar sum) { queueIndex = 1; assert (list.length == weights.length) : "\nLength of two vectors different in SumWeight"; numberArgs = (short) (list.length + 1); numberId = idNumber.incrementAndGet(); this.sum = sum; HashMap<IntVar, Integer> parameters = new HashMap<IntVar, Integer>(); for (int i = 0; i < list.length; i++) { assert (list[i] != null) : i + "-th element of list in SumWeighted constraint is null"; if (parameters.get(list[i]) != null) { // variable ordered in the scope of the Sum Weight constraint. Integer coeff = parameters.get(list[i]); Integer sumOfCoeff = coeff + weights[i]; parameters.put(list[i], sumOfCoeff); } else parameters.put(list[i], weights[i]); } assert (parameters.get(sum) == null) : "Sum variable is used in both sides of SumeWeight constraint."; this.list = new IntVar[parameters.size()]; this.weights = new int[parameters.size()]; int i = 0; for (IntVar var : parameters.keySet()) { this.list[i] = var; this.weights[i] = parameters.get(var); i++; } checkForOverflow(); } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(); }
#vulnerable code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { FileReader file = new FileReader(relativePath + timeCategory + listFileName); BufferedReader br = new BufferedReader(file); String line = ""; List<String> list = new ArrayList<String>(); int i = 0; while ((line = br.readLine())!=null) { list.add(i, line); i++; } return list; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(timeCategory); }
#vulnerable code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { FileReader file = new FileReader(relativePath + timeCategory + listFileName); BufferedReader br = new BufferedReader(file); String line = ""; List<String> list = new ArrayList<String>(); int i = 0; while ((line = br.readLine())!=null) { list.add(i, line); i++; } return list; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected static Collection<String> fileReader(String timeCategory) throws IOException { System.out.println("timeCategory" + timeCategory); FileReader file = new FileReader(relativePath + timeCategory + listFileName); try( BufferedReader br = new BufferedReader(file)) { String line = ""; List<String> list = new ArrayList<String>(); int i = 0; while ((line = br.readLine()) != null) { list.add(i, line); i++; } return list; } }
#vulnerable code protected static Collection<String> fileReader(String timeCategory) throws IOException { System.out.println("timeCategory" + timeCategory); FileReader file = new FileReader(relativePath + timeCategory + listFileName); BufferedReader br = new BufferedReader(file); String line = ""; List<String> list = new ArrayList<String>(); int i = 0; while ((line = br.readLine()) != null) { list.add(i, line); i++; } return list; } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code RootBNode buildBinaryTree(BinaryNode[] nodes) { BinaryNode[] nextLevelNodes = new BinaryNode[nodes.length / 2 + nodes.length % 2]; // System.out.println ("next level length = " + nextLevelNodes.length); if (nodes.length > 1) { for (int i = 0; i < nodes.length - 1; i += 2) { BinaryNode parent; if (nodes.length == 2) parent = new RootBNode(store, FloatDomain.MinFloat, FloatDomain.MaxFloat); else parent = new BNode(store, FloatDomain.MinFloat, FloatDomain.MaxFloat); parent.left = nodes[i]; parent.right = nodes[i + 1]; // currently sibling not used // nodes[i].sibling = nodes[i + 1]; // nodes[i + 1].sibling = nodes[i]; nodes[i].parent = parent; nodes[i + 1].parent = parent; nextLevelNodes[i / 2] = parent; } if (nodes.length % 2 == 1) { nextLevelNodes[nextLevelNodes.length - 1] = nextLevelNodes[0]; nextLevelNodes[0] = nodes[nodes.length - 1]; } return buildBinaryTree(nextLevelNodes); } else { // root node ((RootBNode) nodes[0]).val = this.sum; ((RootBNode) nodes[0]).rel = relationType; return (RootBNode) nodes[0]; } }
#vulnerable code void propagate(SimpleHashSet<FloatVar> fdvs) { while (!fdvs.isEmpty()) { FloatVar v = fdvs.removeFirst(); VariableNode n = varMap.get(v); n.propagate(); } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String[] readFile(String file) { List<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); }
#vulnerable code public static String[] readFile(String file) { List<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readDictionaryFromFile(String file, List<Integer> wordSizes) { for (int wordSize : wordSizes) { int wordCount = 0; IntVar[] list = new IntVar[wordSize]; for (int i = 0; i < wordSize; i++) list[i] = blank; int[] tupleForGivenWord = new int[wordSize]; MDD resultForWordSize = new MDD(list); try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } if (str.length() != wordSize) continue; for (int i = 0; i < wordSize; i++) { tupleForGivenWord[i] = mapping.get(str.substring(i, i + 1)); } wordCount++; resultForWordSize.addTuple(tupleForGivenWord); // lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } System.out.println("There are " + wordCount + " words of size " + wordSize); resultForWordSize.reduce(); mdds.put(wordSize, resultForWordSize); } }
#vulnerable code public void readDictionaryFromFile(String file, List<Integer> wordSizes) { for (int wordSize : wordSizes) { int wordCount = 0; IntVar[] list = new IntVar[wordSize]; for (int i = 0; i < wordSize; i++) list[i] = blank; int[] tupleForGivenWord = new int[wordSize]; MDD resultForWordSize = new MDD(list); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } if (str.length() != wordSize) continue; for (int i = 0; i < wordSize; i++) { tupleForGivenWord[i] = mapping.get(str.substring(i, i + 1)); } wordCount++; resultForWordSize.addTuple(tupleForGivenWord); // lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } System.out.println("There are " + wordCount + " words of size " + wordSize); resultForWordSize.reduce(); mdds.put(wordSize, resultForWordSize); } } #location 45 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static int[][] readFile(String file) { int[][] problem = null; // The problem matrix int r = 0; int c = 0; System.out.println("readFile(" + file + ")"); int lineCount = 0; try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } System.out.println(str); if (lineCount == 0) { r = Integer.parseInt(str); // number of rows } else if (lineCount == 1) { c = Integer.parseInt(str); // number of columns problem = new int[r][c]; } else { // the problem matrix String row[] = str.split(""); for (int j = 1; j <= c; j++) { String s = row[j]; if (s.equals(".")) { problem[lineCount - 2][j - 1] = -1; } else { problem[lineCount - 2][j - 1] = Integer.parseInt(s); } } } lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return problem; }
#vulnerable code public static int[][] readFile(String file) { int[][] problem = null; // The problem matrix int r = 0; int c = 0; System.out.println("readFile(" + file + ")"); int lineCount = 0; try { BufferedReader inr = new BufferedReader(new FileReader(file)); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } System.out.println(str); if (lineCount == 0) { r = Integer.parseInt(str); // number of rows } else if (lineCount == 1) { c = Integer.parseInt(str); // number of columns problem = new int[r][c]; } else { // the problem matrix String row[] = str.split(""); for (int j = 1; j <= c; j++) { String s = row[j]; if (s.equals(".")) { problem[lineCount - 2][j - 1] = -1; } else { problem[lineCount - 2][j - 1] = Integer.parseInt(s); } } } lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return problem; } #location 48 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code int estimatePruning(IntVar x, Integer v) { List<IntVar> exploredX = new ArrayList<IntVar>(); List<Integer> exploredV = new ArrayList<Integer>(); int pruning = estimatePruningRecursive(x, v, exploredX, exploredV); SimpleArrayList<IntVar> currentSimpleArrayList = null; Integer value = null; for (int i = 0; i < exploredV.size(); i++) { value = exploredV.get(i); currentSimpleArrayList = valueMapVariable.get(value); TimeStamp<Integer> stamp = stamps.get(value); int lastPosition = stamp.value(); for (int j = 0; j <= lastPosition; j++) // Edge between j and value was not counted yet if (!exploredX.contains(currentSimpleArrayList.get(j))) pruning++; stamp = null; } currentSimpleArrayList = null; value = null; exploredX = null; exploredV = null; return pruning; }
#vulnerable code int estimatePruningRecursive(IntVar xVar, Integer v, List<IntVar> exploredX, List<Integer> exploredV) { if (exploredX.contains(xVar)) return 0; exploredX.add(xVar); exploredV.add(v); int pruning = 0; IntDomain xDom = xVar.dom(); pruning = xDom.getSize() - 1; TimeStamp<Integer> stamp = null; SimpleArrayList<IntVar> currentSimpleArrayList = null; ValueEnumeration enumer = xDom.valueEnumeration(); // Permutation only if (stampValues.value() - stampNotGroundedVariables.value() == 1) for (int i = enumer.nextElement(); enumer.hasMoreElements(); i = enumer.nextElement()) { if (!exploredV.contains(i)) { Integer iInteger = i; stamp = stamps.get(iInteger); int lastPosition = stamp.value(); // lastPosition == 0 means one variable, so check if there // is atmost one variable for value if (lastPosition < exploredX.size() + 1) { currentSimpleArrayList = valueMapVariable.get(iInteger); IntVar singleVar = null; boolean single = true; for (int m = 0; m <= lastPosition; m++) if (!exploredX.contains(currentSimpleArrayList.get(m))) if (singleVar == null) singleVar = currentSimpleArrayList.get(m); else single = false; if (single && singleVar == null) { System.out.println(this); System.out.println("StampValues - 1 " + (stampValues.value() - 1)); System.out.println("Not grounded Var " + stampNotGroundedVariables.value()); int lastNotGroundedVariable = stampNotGroundedVariables.value(); Var variable = null; for (int l = 0; l <= lastNotGroundedVariable; l++) { variable = list[l]; System.out.println("Stamp for " + variable + " " + sccStamp.get(variable).value()); System.out.println("Matching " + matching.get(variable).value()); } } if (single && singleVar != null) pruning += estimatePruningRecursive(singleVar, iInteger, exploredX, exploredV); singleVar = null; } iInteger = null; } } enumer = null; stamp = stamps.get(v); currentSimpleArrayList = valueMapVariable.get(v); int lastPosition = stamp.value(); for (int i = 0; i <= lastPosition; i++) { IntVar variable = currentSimpleArrayList.get(i); // checks if there is at most one value for variable if (!exploredX.contains(variable) && variable.dom().getSize() < exploredV.size() + 2) { boolean single = true; Integer singleVal = null; for (ValueEnumeration enumerX = variable.dom().valueEnumeration(); enumerX.hasMoreElements(); ) { Integer next = enumerX.nextElement(); if (!exploredV.contains(next)) if (singleVal == null) singleVal = next; else single = false; } if (single) pruning += estimatePruningRecursive(variable, singleVal, exploredX, exploredV); } } stamp = null; return pruning; } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void consistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 1, 1); else y.domain.in(store.level, y, 0, 0); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); }
#vulnerable code @Override public void consistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 1, 1); else y.domain.in(store.level, y, 0, 0); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readAuction(String filename) { noGoods = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8")); // the first line represents the input goods String line = br.readLine(); StringTokenizer tk = new StringTokenizer(line, "(),: "); initialQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { noGoods++; tk.nextToken(); initialQuantity.add(Integer.parseInt(tk.nextToken())); } // the second line represents the output goods line = br.readLine(); tk = new StringTokenizer(line, "(),: "); finalQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { tk.nextToken(); finalQuantity.add(Integer.parseInt(tk.nextToken())); } // until the word price is read, one is reading transformations. // Assume that the transformations are properly grouped line = br.readLine(); int bidCounter = 1; int bid_xorCounter = 1; int transformationCounter = 0; int goodsCounter = 0; int Id, in, out; int[] input; int[] output; bids = new ArrayList<ArrayList<ArrayList<Transformation>>>(); bids.add(new ArrayList<ArrayList<Transformation>>()); (bids.get(0)).add(new ArrayList<Transformation>()); while (!line.equals("price")) { tk = new StringTokenizer(line, "():, "); transformationCounter++; if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; bid_xorCounter = 1; transformationCounter = 1; bids.add(new ArrayList<ArrayList<Transformation>>()); bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } //System.out.println(bidCounter + " " + bid_xorCounter); if (Integer.parseInt(tk.nextToken()) > bid_xorCounter) { bid_xorCounter++; transformationCounter = 1; bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } // this token contains the number of the transformation tk.nextToken(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).add(new Transformation()); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds = new ArrayList<Integer>(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta = new ArrayList<Delta>(); input = new int[noGoods]; output = new int[noGoods]; goodsCounter = 0; while (tk.hasMoreTokens()) { goodsCounter++; //System.out.println(goodsCounter); if (goodsCounter <= noGoods) { Id = Integer.parseInt(tk.nextToken()) - 1; in = Integer.parseInt(tk.nextToken()); input[Id] = in; } else { Id = Integer.parseInt(tk.nextToken()) - 1; out = Integer.parseInt(tk.nextToken()); output[Id] = out; } } for (int i = 0; i < noGoods; i++) { //delta = output[i] - input[i]; if (output[i] > maxDelta) { maxDelta = output[i]; } else if (-input[i] < minDelta) { minDelta = -input[i]; } if (output[i] != 0 || input[i] != 0) { //System.out.print(i + " " + input[i] + ":" + output[i] + " "); //System.out.println(bidCounter + " " + bid_xorCounter + " " + transformationCounter + " " + i + " " + delta); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds.add(i); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta .add(new Delta(input[i], output[i])); } } System.out.print("\n"); line = br.readLine(); } // now read in the price for each xor bid costs = new ArrayList<ArrayList<Integer>>(); costs.add(new ArrayList<Integer>()); bidCounter = 1; line = br.readLine(); while (!(line == null)) { tk = new StringTokenizer(line, "(): "); if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; costs.add(new ArrayList<Integer>()); } // this token contains the xor_bid id. tk.nextToken(); costs.get(bidCounter - 1).add(Integer.parseInt(tk.nextToken())); line = br.readLine(); } } catch (FileNotFoundException ex) { System.err.println("You need to run this program in a directory that contains the required file."); System.err.println(ex); System.exit(-1); } catch (IOException ex) { System.err.println(ex); } System.out.println(this.maxCost); System.out.println(this.maxDelta); System.out.println(this.minDelta); }
#vulnerable code public void readAuction(String filename) { noGoods = 0; try { BufferedReader br = new BufferedReader(new FileReader(filename)); // the first line represents the input goods String line = br.readLine(); StringTokenizer tk = new StringTokenizer(line, "(),: "); initialQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { noGoods++; tk.nextToken(); initialQuantity.add(Integer.parseInt(tk.nextToken())); } // the second line represents the output goods line = br.readLine(); tk = new StringTokenizer(line, "(),: "); finalQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { tk.nextToken(); finalQuantity.add(Integer.parseInt(tk.nextToken())); } // until the word price is read, one is reading transformations. // Assume that the transformations are properly grouped line = br.readLine(); int bidCounter = 1; int bid_xorCounter = 1; int transformationCounter = 0; int goodsCounter = 0; int Id, in, out; int[] input; int[] output; bids = new ArrayList<ArrayList<ArrayList<Transformation>>>(); bids.add(new ArrayList<ArrayList<Transformation>>()); (bids.get(0)).add(new ArrayList<Transformation>()); while (!line.equals("price")) { tk = new StringTokenizer(line, "():, "); transformationCounter++; if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; bid_xorCounter = 1; transformationCounter = 1; bids.add(new ArrayList<ArrayList<Transformation>>()); bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } //System.out.println(bidCounter + " " + bid_xorCounter); if (Integer.parseInt(tk.nextToken()) > bid_xorCounter) { bid_xorCounter++; transformationCounter = 1; bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } // this token contains the number of the transformation tk.nextToken(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).add(new Transformation()); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds = new ArrayList<Integer>(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta = new ArrayList<Delta>(); input = new int[noGoods]; output = new int[noGoods]; goodsCounter = 0; while (tk.hasMoreTokens()) { goodsCounter++; //System.out.println(goodsCounter); if (goodsCounter <= noGoods) { Id = Integer.parseInt(tk.nextToken()) - 1; in = Integer.parseInt(tk.nextToken()); input[Id] = in; } else { Id = Integer.parseInt(tk.nextToken()) - 1; out = Integer.parseInt(tk.nextToken()); output[Id] = out; } } for (int i = 0; i < noGoods; i++) { //delta = output[i] - input[i]; if (output[i] > maxDelta) { maxDelta = output[i]; } else if (-input[i] < minDelta) { minDelta = -input[i]; } if (output[i] != 0 || input[i] != 0) { //System.out.print(i + " " + input[i] + ":" + output[i] + " "); //System.out.println(bidCounter + " " + bid_xorCounter + " " + transformationCounter + " " + i + " " + delta); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds.add(i); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta .add(new Delta(input[i], output[i])); } } System.out.print("\n"); line = br.readLine(); } // now read in the price for each xor bid costs = new ArrayList<ArrayList<Integer>>(); costs.add(new ArrayList<Integer>()); bidCounter = 1; line = br.readLine(); while (!(line == null)) { tk = new StringTokenizer(line, "(): "); if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; costs.add(new ArrayList<Integer>()); } // this token contains the xor_bid id. tk.nextToken(); costs.get(bidCounter - 1).add(Integer.parseInt(tk.nextToken())); line = br.readLine(); } } catch (FileNotFoundException ex) { System.err.println("You need to run this program in a directory that contains the required file."); System.err.println(ex); System.exit(-1); } catch (IOException ex) { System.err.println(ex); } System.out.println(this.maxCost); System.out.println(this.maxDelta); System.out.println(this.minDelta); } #location 143 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readFile(String file) { System.out.println("readFile(" + file + ")"); try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; int lineCount = 0; List<List<Integer>> MatrixI = new ArrayList<List<Integer>>(); while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } str = str.replace("_", ""); String row[] = str.split("\\s+"); System.out.println(str); // first line: column names: Ignore but count them if (lineCount == 0) { c = row.length; colsums = new int[c]; } else { // This is the last line: the column sums if (row.length == c) { colsums = new int[row.length]; for (int j = 0; j < row.length; j++) { colsums[j] = Integer.parseInt(row[j]); } System.out.println(); } else { // Otherwise: // The problem matrix: index 1 .. row.length-1 // The row sums: index row.length List<Integer> this_row = new ArrayList<Integer>(); for (int j = 0; j < row.length; j++) { String s = row[j]; if (s.equals("*")) { this_row.add(0); } else { this_row.add(Integer.parseInt(s)); } } MatrixI.add(this_row); } } lineCount++; } // end while inr.close(); // // Now we know everything to be known: // Construct the problem matrix and column sums. // r = MatrixI.size(); rowsums = new int[r]; matrix = new int[r][c]; for (int i = 0; i < r; i++) { List<Integer> this_row = MatrixI.get(i); for (int j = 1; j < c + 1; j++) { matrix[i][j - 1] = this_row.get(j); } rowsums[i] = this_row.get(c + 1); } } catch (IOException e) { System.out.println(e); } }
#vulnerable code public void readFile(String file) { System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; int lineCount = 0; List<List<Integer>> MatrixI = new ArrayList<List<Integer>>(); while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } str = str.replace("_", ""); String row[] = str.split("\\s+"); System.out.println(str); // first line: column names: Ignore but count them if (lineCount == 0) { c = row.length; colsums = new int[c]; } else { // This is the last line: the column sums if (row.length == c) { colsums = new int[row.length]; for (int j = 0; j < row.length; j++) { colsums[j] = Integer.parseInt(row[j]); } System.out.println(); } else { // Otherwise: // The problem matrix: index 1 .. row.length-1 // The row sums: index row.length List<Integer> this_row = new ArrayList<Integer>(); for (int j = 0; j < row.length; j++) { String s = row[j]; if (s.equals("*")) { this_row.add(0); } else { this_row.add(Integer.parseInt(s)); } } MatrixI.add(this_row); } } lineCount++; } // end while inr.close(); // // Now we know everything to be known: // Construct the problem matrix and column sums. // r = MatrixI.size(); rowsums = new int[r]; matrix = new int[r][c]; for (int i = 0; i < r; i++) { List<Integer> this_row = MatrixI.get(i); for (int j = 1; j < c + 1; j++) { matrix[i][j - 1] = this_row.get(j); } rowsums[i] = this_row.get(c + 1); } } catch (IOException e) { System.out.println(e); } } #location 78 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ArrayList<Constraint> decompose(Store store) { if (constraints != null) return constraints; IntDomain setComplement = new IntervalDomain(); for (IntVar var : list) setComplement.addDom(var.domain); setComplement = setComplement.subtract(set); FSM fsm = new FSM(); fsm.initState = new FSMState(); fsm.allStates.add(fsm.initState); HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>(); HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>(); mappingQuantity.put(fsm.initState, 0); mappingString.put("", fsm.initState); for (int i = 0; i < q; i++) { HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>(); for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) { String stateString = entry.getKey(); FSMState state = entry.getValue(); if (mappingQuantity.get(state) < max) { // transition 1 (within a set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(set, nextState)); mappingStringNext.put(stateString + "1", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state) + 1); } if (mappingQuantity.get(state) + (q - i) > min) { // transition 0 (outside set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(setComplement, nextState)); mappingStringNext.put(stateString + "0", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state)); } } fsm.allStates.addAll(mappingString.values()); mappingString = mappingStringNext; } fsm.allStates.addAll(mappingString.values()); fsm.finalStates.addAll(mappingString.values()); for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) { String description = entry.getKey(); FSMState state = entry.getValue(); String one = description.substring(1) + "1"; FSMState predecessor = state; FSMState successor = mappingString.get(one); if (successor != null) predecessor.addTransition(new FSMTransition(set, successor)); String zero = description.substring(1) + "0"; successor = mappingString.get(zero); if (successor != null) predecessor.addTransition(new FSMTransition(setComplement, successor)); } fsm.resize(); constraints = new ArrayList<Constraint>(); constraints.add(new Regular(fsm, list)); return constraints; }
#vulnerable code @Override public ArrayList<Constraint> decompose(Store store) { if (constraints != null) return constraints; IntDomain setComplement = new IntervalDomain(); for (IntVar var : list) setComplement.addDom(var.domain); setComplement = setComplement.subtract(set); FSM fsm = new FSM(); fsm.initState = new FSMState(); fsm.allStates.add(fsm.initState); HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>(); HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>(); mappingQuantity.put(fsm.initState, 0); mappingString.put("", fsm.initState); for (int i = 0; i < q; i++) { HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>(); for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) { String stateString = entry.getKey(); FSMState state = entry.getValue(); if (mappingQuantity.get(state) < max) { // transition 1 (within a set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(set, nextState)); mappingStringNext.put(stateString + "1", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state) + 1); } if (mappingQuantity.get(state) + (q - i) > min) { // transition 0 (outside set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(setComplement, nextState)); mappingStringNext.put(stateString + "0", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state)); } } fsm.allStates.addAll(mappingString.values()); mappingString = mappingStringNext; } fsm.allStates.addAll(mappingString.values()); fsm.finalStates.addAll(mappingString.values()); for (String description : mappingString.keySet()) { String one = description.substring(1) + "1"; FSMState predecessor = mappingString.get(description); FSMState successor = mappingString.get(one); if (successor != null) predecessor.addTransition(new FSMTransition(set, successor)); String zero = description.substring(1) + "0"; successor = mappingString.get(zero); if (successor != null) predecessor.addTransition(new FSMTransition(setComplement, successor)); } fsm.resize(); constraints = new ArrayList<Constraint>(); constraints.add(new Regular(fsm, list)); return constraints; } #location 61 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); }
#vulnerable code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String[] readFile(String file) { ArrayList<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); }
#vulnerable code public static String[] readFile(String file) { ArrayList<String> result = new ArrayList<String>(); System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new FileReader(file)); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } result.add(str); } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return result.toArray(new String[result.size()]); } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); }
#vulnerable code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int countWatches() { if (watchedConstraints == null) return 0; int count = 0; for (HashSet<Constraint> c : watchedConstraints.values()) count += c.size(); return count; }
#vulnerable code public int countWatches() { if (watchedConstraints == null) return 0; int count = 0; for (Var v : watchedConstraints.keySet()) count += watchedConstraints.get(v).size(); return count; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void consistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 1, 1); else y.domain.in(store.level, y, 0, 0); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); }
#vulnerable code @Override public void consistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 1, 1); else y.domain.in(store.level, y, 0, 0); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); }
#vulnerable code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readDictionaryFromFile(String file, List<Integer> wordSizes) { for (int wordSize : wordSizes) { int wordCount = 0; IntVar[] list = new IntVar[wordSize]; for (int i = 0; i < wordSize; i++) list[i] = blank; int[] tupleForGivenWord = new int[wordSize]; MDD resultForWordSize = new MDD(list); try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } if (str.length() != wordSize) continue; for (int i = 0; i < wordSize; i++) { tupleForGivenWord[i] = mapping.get(str.substring(i, i + 1)); } wordCount++; resultForWordSize.addTuple(tupleForGivenWord); // lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } System.out.println("There are " + wordCount + " words of size " + wordSize); resultForWordSize.reduce(); mdds.put(wordSize, resultForWordSize); } }
#vulnerable code public void readDictionaryFromFile(String file, List<Integer> wordSizes) { for (int wordSize : wordSizes) { int wordCount = 0; IntVar[] list = new IntVar[wordSize]; for (int i = 0; i < wordSize; i++) list[i] = blank; int[] tupleForGivenWord = new int[wordSize]; MDD resultForWordSize = new MDD(list); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } if (str.length() != wordSize) continue; for (int i = 0; i < wordSize; i++) { tupleForGivenWord[i] = mapping.get(str.substring(i, i + 1)); } wordCount++; resultForWordSize.addTuple(tupleForGivenWord); // lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } System.out.println("There are " + wordCount + " words of size " + wordSize); resultForWordSize.reduce(); mdds.put(wordSize, resultForWordSize); } } #location 45 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ArrayList<Constraint> decompose(Store store) { if (constraints != null) return constraints; IntDomain setComplement = new IntervalDomain(); for (IntVar var : list) setComplement.addDom(var.domain); setComplement = setComplement.subtract(set); FSM fsm = new FSM(); fsm.initState = new FSMState(); fsm.allStates.add(fsm.initState); HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>(); HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>(); mappingQuantity.put(fsm.initState, 0); mappingString.put("", fsm.initState); for (int i = 0; i < q; i++) { HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>(); for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) { String stateString = entry.getKey(); FSMState state = entry.getValue(); if (mappingQuantity.get(state) < max) { // transition 1 (within a set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(set, nextState)); mappingStringNext.put(stateString + "1", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state) + 1); } if (mappingQuantity.get(state) + (q - i) > min) { // transition 0 (outside set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(setComplement, nextState)); mappingStringNext.put(stateString + "0", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state)); } } fsm.allStates.addAll(mappingString.values()); mappingString = mappingStringNext; } fsm.allStates.addAll(mappingString.values()); fsm.finalStates.addAll(mappingString.values()); for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) { String description = entry.getKey(); FSMState state = entry.getValue(); String one = description.substring(1) + "1"; FSMState predecessor = state; FSMState successor = mappingString.get(one); if (successor != null) predecessor.addTransition(new FSMTransition(set, successor)); String zero = description.substring(1) + "0"; successor = mappingString.get(zero); if (successor != null) predecessor.addTransition(new FSMTransition(setComplement, successor)); } fsm.resize(); constraints = new ArrayList<Constraint>(); constraints.add(new Regular(fsm, list)); return constraints; }
#vulnerable code @Override public ArrayList<Constraint> decompose(Store store) { if (constraints != null) return constraints; IntDomain setComplement = new IntervalDomain(); for (IntVar var : list) setComplement.addDom(var.domain); setComplement = setComplement.subtract(set); FSM fsm = new FSM(); fsm.initState = new FSMState(); fsm.allStates.add(fsm.initState); HashMap<FSMState, Integer> mappingQuantity = new HashMap<FSMState, Integer>(); HashMap<String, FSMState> mappingString = new HashMap<String, FSMState>(); mappingQuantity.put(fsm.initState, 0); mappingString.put("", fsm.initState); for (int i = 0; i < q; i++) { HashMap<String, FSMState> mappingStringNext = new HashMap<String, FSMState>(); for (Map.Entry<String, FSMState> entry : mappingString.entrySet()) { String stateString = entry.getKey(); FSMState state = entry.getValue(); if (mappingQuantity.get(state) < max) { // transition 1 (within a set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(set, nextState)); mappingStringNext.put(stateString + "1", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state) + 1); } if (mappingQuantity.get(state) + (q - i) > min) { // transition 0 (outside set) is allowed FSMState nextState = new FSMState(); state.addTransition(new FSMTransition(setComplement, nextState)); mappingStringNext.put(stateString + "0", nextState); mappingQuantity.put(nextState, mappingQuantity.get(state)); } } fsm.allStates.addAll(mappingString.values()); mappingString = mappingStringNext; } fsm.allStates.addAll(mappingString.values()); fsm.finalStates.addAll(mappingString.values()); for (String description : mappingString.keySet()) { String one = description.substring(1) + "1"; FSMState predecessor = mappingString.get(description); FSMState successor = mappingString.get(one); if (successor != null) predecessor.addTransition(new FSMTransition(set, successor)); String zero = description.substring(1) + "0"; successor = mappingString.get(zero); if (successor != null) predecessor.addTransition(new FSMTransition(setComplement, successor)); } fsm.resize(); constraints = new ArrayList<Constraint>(); constraints.add(new Regular(fsm, list)); return constraints; } #location 66 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(timeCategory); }
#vulnerable code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { FileReader file = new FileReader(relativePath + timeCategory + listFileName); BufferedReader br = new BufferedReader(file); String line = ""; List<String> list = new ArrayList<String>(); int i = 0; while ((line = br.readLine())!=null) { list.add(i, line); i++; } return list; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void init() { int n = tuple.length; rbs = new ReversibleSparseBitSet(store, x, tuple); makeSupport(); }
#vulnerable code void filterDomains() { for (int i = 0; i < x.length; i++) { int xIndex = varMap.get(x[i]); Map<Integer,long[]> xSupport = supports[xIndex]; ValueEnumeration e = x[i].dom().valueEnumeration(); while (e.hasMoreElements()) { int el = e.nextElement(); Integer indexInteger = residues[i].get(el); if (indexInteger == null) { x[i].domain.inComplement(store.level, x[i], el); continue; } int index = indexInteger.intValue(); long[] bs = xSupport.get(el); if (bs != null) { if ((rbs.words[index].value() & xSupport.get(el)[index]) == 0L) { index = rbs.intersectIndex(bs); if (index == -1) x[i].domain.inComplement(store.level, x[i], el); else residues[i].put(el, index); } } else x[i].domain.inComplement(store.level, x[i], el); } } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void consistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 1, 1); else y.domain.in(store.level, y, 0, 0); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); }
#vulnerable code @Override public void consistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 1, 1); else y.domain.in(store.level, y, 0, 0); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void init() { int n = tuple.length; int lastWordSize = n % 64; int numberBitSets = n / 64 + ((lastWordSize != 0) ? 1 : 0); rbs = new ReversibleSparseBitSet(); long[] words = makeSupportAndWords(numberBitSets); rbs.init(store, words); }
#vulnerable code void updateTable(HashSet<IntVar> fdvs) { for (IntVar v : fdvs) { // recent pruning IntDomain cd = v.dom(); IntDomain pd = cd.previousDomain(); IntDomain rp; int delta; if (pd == null) { rp = cd; delta = IntDomain.MaxInt; } else { rp = pd.subtract(cd); delta = rp.getSize(); if (delta == 0) continue; } rbs.clearMask(); int xIndex = varMap.get(v); Map<Integer, long[]> xSupport = supports[xIndex]; if (delta < cd.getSize()) { // incremental update ValueEnumeration e = rp.valueEnumeration(); while (e.hasMoreElements()) { long[] bs = xSupport.get(e.nextElement()); if (bs != null) rbs.addToMask(bs); } rbs.reverseMask(); } else { // reset-based update ValueEnumeration e = cd.valueEnumeration(); while (e.hasMoreElements()) { long[] bs = xSupport.get(e.nextElement()); if (bs != null) rbs.addToMask(bs); } } rbs.intersectWithMask(); if (rbs.isEmpty()) throw store.failException; } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readFile(String file) { System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; int lineCount = 0; ArrayList<ArrayList<Integer>> MatrixI = new ArrayList<ArrayList<Integer>>(); while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } str = str.replace("_", ""); String row[] = str.split("\\s+"); System.out.println(str); // first line: column names: Ignore but count them if (lineCount == 0) { c = row.length; colsums = new int[c]; } else { // This is the last line: the column sums if (row.length == c) { colsums = new int[row.length]; for (int j = 0; j < row.length; j++) { colsums[j] = Integer.parseInt(row[j]); } System.out.println(); } else { // Otherwise: // The problem matrix: index 1 .. row.length-1 // The row sums: index row.length ArrayList<Integer> this_row = new ArrayList<Integer>(); for (int j = 0; j < row.length; j++) { String s = row[j]; if (s.equals("*")) { this_row.add(0); } else { this_row.add(Integer.parseInt(s)); } } MatrixI.add(this_row); } } lineCount++; } // end while inr.close(); // // Now we know everything to be known: // Construct the problem matrix and column sums. // r = MatrixI.size(); rowsums = new int[r]; matrix = new int[r][c]; for (int i = 0; i < r; i++) { ArrayList<Integer> this_row = MatrixI.get(i); for (int j = 1; j < c + 1; j++) { matrix[i][j - 1] = this_row.get(j); } rowsums[i] = this_row.get(c + 1); } } catch (IOException e) { System.out.println(e); } }
#vulnerable code public void readFile(String file) { System.out.println("readFile(" + file + ")"); try { BufferedReader inr = new BufferedReader(new FileReader(file)); String str; int lineCount = 0; ArrayList<ArrayList<Integer>> MatrixI = new ArrayList<ArrayList<Integer>>(); while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments // starting with either # or % if (str.startsWith("#") || str.startsWith("%")) { continue; } str = str.replace("_", ""); String row[] = str.split("\\s+"); System.out.println(str); // first line: column names: Ignore but count them if (lineCount == 0) { c = row.length; colsums = new int[c]; } else { // This is the last line: the column sums if (row.length == c) { colsums = new int[row.length]; for (int j = 0; j < row.length; j++) { colsums[j] = Integer.parseInt(row[j]); } System.out.println(); } else { // Otherwise: // The problem matrix: index 1 .. row.length-1 // The row sums: index row.length ArrayList<Integer> this_row = new ArrayList<Integer>(); for (int j = 0; j < row.length; j++) { String s = row[j]; if (s.equals("*")) { this_row.add(0); } else { this_row.add(Integer.parseInt(s)); } } MatrixI.add(this_row); } } lineCount++; } // end while inr.close(); // // Now we know everything to be known: // Construct the problem matrix and column sums. // r = MatrixI.size(); rowsums = new int[r]; matrix = new int[r][c]; for (int i = 0; i < r; i++) { ArrayList<Integer> this_row = MatrixI.get(i); for (int j = 1; j < c + 1; j++) { matrix[i][j - 1] = this_row.get(j); } rowsums[i] = this_row.get(c + 1); } } catch (IOException e) { System.out.println(e); } } #location 78 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(timeCategory); }
#vulnerable code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { FileReader file = new FileReader(relativePath + timeCategory + listFileName); BufferedReader br = new BufferedReader(file); String line = ""; List<String> list = new ArrayList<String>(); int i = 0; while ((line = br.readLine())!=null) { list.add(i, line); i++; } return list; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void saveLatexToFile(String desc) { String fileName = this.latexFile + (calls++) + ".tex"; File f = new File(fileName); try(FileOutputStream fs = new FileOutputStream(f)) { System.out.println("save latex file " + fileName); fs.write(this.toLatex(desc).getBytes("UTF-8")); fs.flush(); fs.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
#vulnerable code public void saveLatexToFile(String desc) { String fileName = this.latexFile + (calls++) + ".tex"; File f = new File(fileName); FileOutputStream fs; try { System.out.println("save latex file " + fileName); fs = new FileOutputStream(f); fs.write(this.toLatex(desc).getBytes("UTF-8")); fs.flush(); fs.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static int[][] readFile(String file) { int[][] problem = null; // The problem matrix int r = 0; int c = 0; System.out.println("readFile(" + file + ")"); int lineCount = 0; try(BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } System.out.println(str); if (lineCount == 0) { r = Integer.parseInt(str); // number of rows } else if (lineCount == 1) { c = Integer.parseInt(str); // number of columns problem = new int[r][c]; } else { // the problem matrix String row[] = str.split(""); for (int j = 1; j <= c; j++) { String s = row[j]; if (s.equals(".")) { problem[lineCount - 2][j - 1] = -1; } else { problem[lineCount - 2][j - 1] = Integer.parseInt(s); } } } lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return problem; }
#vulnerable code public static int[][] readFile(String file) { int[][] problem = null; // The problem matrix int r = 0; int c = 0; System.out.println("readFile(" + file + ")"); int lineCount = 0; try { BufferedReader inr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String str; while ((str = inr.readLine()) != null && str.length() > 0) { str = str.trim(); // ignore comments if (str.startsWith("#") || str.startsWith("%")) { continue; } System.out.println(str); if (lineCount == 0) { r = Integer.parseInt(str); // number of rows } else if (lineCount == 1) { c = Integer.parseInt(str); // number of columns problem = new int[r][c]; } else { // the problem matrix String row[] = str.split(""); for (int j = 1; j <= c; j++) { String s = row[j]; if (s.equals(".")) { problem[lineCount - 2][j - 1] = -1; } else { problem[lineCount - 2][j - 1] = Integer.parseInt(s); } } } lineCount++; } // end while inr.close(); } catch (IOException e) { System.out.println(e); } return problem; } #location 49 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; int numberZeros = 0; for (IntVar e : x) { if (e.min() == 1) numberOnes++; else if (e.max() == 0) numberZeros++; else nonGround = e; } if (numberOnes + numberZeros == x.length) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (nonGround != null && numberOnes + numberZeros == x.length - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); }
#vulnerable code @Override public void notConsistency(final Store store) { IntVar nonGround = null; int numberOnes = 0; for (IntVar e : x) if (e.min() == 1) numberOnes++; else if (e.max() != 0) nonGround = e; int numberZeros = 0; for (IntVar e : x) if (e.max() == 0) numberZeros++; else if (e.min() != 1) nonGround = e; if (numberOnes + numberZeros == l) if ((numberOnes & 1) == 1) y.domain.in(store.level, y, 0, 0); else y.domain.in(store.level, y, 1, 1); else if (numberOnes + numberZeros == l - 1) if (y.min() == 1) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 1, 1); else nonGround.domain.in(store.level, nonGround, 0, 0); else if (y.max() == 0) if ((numberOnes & 1) == 1) nonGround.domain.in(store.level, nonGround, 0, 0); else nonGround.domain.in(store.level, nonGround, 1, 1); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readAuction(String filename) { noGoods = 0; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8")); // the first line represents the input goods String line = br.readLine(); StringTokenizer tk = new StringTokenizer(line, "(),: "); initialQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { noGoods++; tk.nextToken(); initialQuantity.add(Integer.parseInt(tk.nextToken())); } // the second line represents the output goods line = br.readLine(); tk = new StringTokenizer(line, "(),: "); finalQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { tk.nextToken(); finalQuantity.add(Integer.parseInt(tk.nextToken())); } // until the word price is read, one is reading transformations. // Assume that the transformations are properly grouped line = br.readLine(); int bidCounter = 1; int bid_xorCounter = 1; int transformationCounter = 0; int goodsCounter = 0; int Id, in, out; int[] input; int[] output; bids = new ArrayList<ArrayList<ArrayList<Transformation>>>(); bids.add(new ArrayList<ArrayList<Transformation>>()); (bids.get(0)).add(new ArrayList<Transformation>()); while (!line.equals("price")) { tk = new StringTokenizer(line, "():, "); transformationCounter++; if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; bid_xorCounter = 1; transformationCounter = 1; bids.add(new ArrayList<ArrayList<Transformation>>()); bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } //System.out.println(bidCounter + " " + bid_xorCounter); if (Integer.parseInt(tk.nextToken()) > bid_xorCounter) { bid_xorCounter++; transformationCounter = 1; bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } // this token contains the number of the transformation tk.nextToken(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).add(new Transformation()); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds = new ArrayList<Integer>(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta = new ArrayList<Delta>(); input = new int[noGoods]; output = new int[noGoods]; goodsCounter = 0; while (tk.hasMoreTokens()) { goodsCounter++; //System.out.println(goodsCounter); if (goodsCounter <= noGoods) { Id = Integer.parseInt(tk.nextToken()) - 1; in = Integer.parseInt(tk.nextToken()); input[Id] = in; } else { Id = Integer.parseInt(tk.nextToken()) - 1; out = Integer.parseInt(tk.nextToken()); output[Id] = out; } } for (int i = 0; i < noGoods; i++) { //delta = output[i] - input[i]; if (output[i] > maxDelta) { maxDelta = output[i]; } else if (-input[i] < minDelta) { minDelta = -input[i]; } if (output[i] != 0 || input[i] != 0) { //System.out.print(i + " " + input[i] + ":" + output[i] + " "); //System.out.println(bidCounter + " " + bid_xorCounter + " " + transformationCounter + " " + i + " " + delta); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds.add(i); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta .add(new Delta(input[i], output[i])); } } System.out.print("\n"); line = br.readLine(); } // now read in the price for each xor bid costs = new ArrayList<ArrayList<Integer>>(); costs.add(new ArrayList<Integer>()); bidCounter = 1; line = br.readLine(); while (!(line == null)) { tk = new StringTokenizer(line, "(): "); if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; costs.add(new ArrayList<Integer>()); } // this token contains the xor_bid id. tk.nextToken(); costs.get(bidCounter - 1).add(Integer.parseInt(tk.nextToken())); line = br.readLine(); } } catch (FileNotFoundException ex) { System.err.println("You need to run this program in a directory that contains the required file."); System.err.println(ex); throw new RuntimeException("You need to run this program in a directory that contains the required file : " + filename); } catch (IOException ex) { System.err.println(ex); } finally { if (br != null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(this.maxCost); System.out.println(this.maxDelta); System.out.println(this.minDelta); }
#vulnerable code public void readAuction(String filename) { noGoods = 0; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8")); // the first line represents the input goods String line = br.readLine(); StringTokenizer tk = new StringTokenizer(line, "(),: "); initialQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { noGoods++; tk.nextToken(); initialQuantity.add(Integer.parseInt(tk.nextToken())); } // the second line represents the output goods line = br.readLine(); tk = new StringTokenizer(line, "(),: "); finalQuantity = new ArrayList<Integer>(); while (tk.hasMoreTokens()) { tk.nextToken(); finalQuantity.add(Integer.parseInt(tk.nextToken())); } // until the word price is read, one is reading transformations. // Assume that the transformations are properly grouped line = br.readLine(); int bidCounter = 1; int bid_xorCounter = 1; int transformationCounter = 0; int goodsCounter = 0; int Id, in, out; int[] input; int[] output; bids = new ArrayList<ArrayList<ArrayList<Transformation>>>(); bids.add(new ArrayList<ArrayList<Transformation>>()); (bids.get(0)).add(new ArrayList<Transformation>()); while (!line.equals("price")) { tk = new StringTokenizer(line, "():, "); transformationCounter++; if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; bid_xorCounter = 1; transformationCounter = 1; bids.add(new ArrayList<ArrayList<Transformation>>()); bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } //System.out.println(bidCounter + " " + bid_xorCounter); if (Integer.parseInt(tk.nextToken()) > bid_xorCounter) { bid_xorCounter++; transformationCounter = 1; bids.get(bidCounter - 1).add(new ArrayList<Transformation>()); } // this token contains the number of the transformation tk.nextToken(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).add(new Transformation()); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds = new ArrayList<Integer>(); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta = new ArrayList<Delta>(); input = new int[noGoods]; output = new int[noGoods]; goodsCounter = 0; while (tk.hasMoreTokens()) { goodsCounter++; //System.out.println(goodsCounter); if (goodsCounter <= noGoods) { Id = Integer.parseInt(tk.nextToken()) - 1; in = Integer.parseInt(tk.nextToken()); input[Id] = in; } else { Id = Integer.parseInt(tk.nextToken()) - 1; out = Integer.parseInt(tk.nextToken()); output[Id] = out; } } for (int i = 0; i < noGoods; i++) { //delta = output[i] - input[i]; if (output[i] > maxDelta) { maxDelta = output[i]; } else if (-input[i] < minDelta) { minDelta = -input[i]; } if (output[i] != 0 || input[i] != 0) { //System.out.print(i + " " + input[i] + ":" + output[i] + " "); //System.out.println(bidCounter + " " + bid_xorCounter + " " + transformationCounter + " " + i + " " + delta); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).goodsIds.add(i); bids.get(bidCounter - 1).get(bid_xorCounter - 1).get(transformationCounter - 1).delta .add(new Delta(input[i], output[i])); } } System.out.print("\n"); line = br.readLine(); } // now read in the price for each xor bid costs = new ArrayList<ArrayList<Integer>>(); costs.add(new ArrayList<Integer>()); bidCounter = 1; line = br.readLine(); while (!(line == null)) { tk = new StringTokenizer(line, "(): "); if (Integer.parseInt(tk.nextToken()) > bidCounter) { bidCounter++; costs.add(new ArrayList<Integer>()); } // this token contains the xor_bid id. tk.nextToken(); costs.get(bidCounter - 1).add(Integer.parseInt(tk.nextToken())); line = br.readLine(); } } catch (FileNotFoundException ex) { System.err.println("You need to run this program in a directory that contains the required file."); System.err.println(ex); System.exit(-1); } catch (IOException ex) { System.err.println(ex); } System.out.println(this.maxCost); System.out.println(this.maxDelta); System.out.println(this.minDelta); } #location 144 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code boolean validTuple(int index) { int[] t = tuple[index]; int n = t.length; int i = 0; while (i < n) { if (!x[i].dom().contains(t[i])) return false; i++; } return true; }
#vulnerable code void updateTable(HashSet<IntVar> fdvs) { for (IntVar v : fdvs) { // recent pruning IntDomain cd = v.dom(); IntDomain pd = cd.previousDomain(); IntDomain rp; int delta; if (pd == null) { rp = cd; delta = IntDomain.MaxInt; } else { rp = pd.subtract(cd); delta = rp.getSize(); if (delta == 0) continue; } mask = 0; // clear mask int xIndex = varMap.get(v); Map<Integer, Long> xSupport = supports[xIndex]; if (delta < cd.getSize()) { // incremental update ValueEnumeration e = rp.valueEnumeration(); while (e.hasMoreElements()) { Long bs = xSupport.get(e.nextElement()); if (bs != null) mask |= (bs.longValue()); } mask = ~mask; } else { // reset-based update ValueEnumeration e = cd.valueEnumeration(); while (e.hasMoreElements()) { Long bs = xSupport.get(e.nextElement()); if (bs != null) mask |= (bs.longValue()); } } boolean empty = intersectWithMask(); if (empty) throw store.failException; } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code AbstractBytes() { this(new VanillaBytesMarshallerFactory(), new AtomicInteger(1)); }
#vulnerable code StringInterner stringInterner() { if (stringInterner == null) stringInterner = new StringInterner(8 * 1024); return stringInterner; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String... args) throws IOException, InterruptedException { boolean toggleTo = Boolean.parseBoolean(args[0]); File tmpFile = new File(System.getProperty("java.io.tmpdir"), "lock-test.dat"); FileChannel fc = new RandomAccessFile(tmpFile, "rw").getChannel(); MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, RECORDS * RECORD_SIZE); ByteBufferBytes bytes = new ByteBufferBytes(mbb); long start = 0; for (int i = -WARMUP / RECORDS; i < (RUNS + RECORDS - 1) / RECORDS; i++) { if (i == 0) { start = System.nanoTime(); System.out.println("Started"); } for (int j = 0; j < RECORDS; j++) { int recordOffset = j * RECORD_SIZE; for (int t = 9999; t >= 0; t--) { if (t == 0) if (i >= 0) { throw new AssertionError("Didn't toggle in time !??"); } else { System.out.println("waiting"); t = 9999; Thread.sleep(200); } bytes.busyLockLong(recordOffset + LOCK); try { boolean flag = bytes.readBoolean(recordOffset + FLAG); if (flag == toggleTo) { if (t % 100 == 0) System.out.println("j: " + j + " is " + flag); continue; } bytes.writeBoolean(recordOffset + FLAG, toggleTo); break; } finally { bytes.unlockLong(recordOffset + LOCK); } } } } long time = System.nanoTime() - start; final int toggles = (RUNS + RECORDS - 1) / RECORDS * RECORDS * 2; // one for each of two processes. System.out.printf("Toogled %,d times with an average delay of %,d ns%n", toggles, time / toggles); fc.close(); tmpFile.deleteOnExit(); }
#vulnerable code public static void main(String... args) throws IOException, InterruptedException { boolean toggleTo = Boolean.parseBoolean(args[0]); File tmpFile = new File(System.getProperty("java.io.tmpdir"), "lock-test.dat"); FileChannel fc = new RandomAccessFile(tmpFile, "rw").getChannel(); MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, RECORDS * RECORD_SIZE); ByteBufferBytes bytes = new ByteBufferBytes(mbb); long start = 0; for (int i = -WARMUP / RECORDS; i < (RUNS + RECORDS - 1) / RECORDS; i++) { if (i == 0) { start = System.nanoTime(); System.out.println("Started"); } for (int j = 0; j < RECORDS; j++) { int recordOffset = j * RECORD_SIZE; for (int t = 9999; t >= 0; t--) { if (t == 0) if (i >= 0) { throw new AssertionError("Didn't toggle in time !??"); } else { System.out.println("waiting"); t = 9999; Thread.sleep(200); } bytes.busyLockLong(recordOffset + LOCK); try { boolean flag = bytes.readBoolean(recordOffset + FLAG); if (flag == toggleTo) { if (t % 100 == 0) System.out.println("j: " + j + " is " + flag); continue; } bytes.writeBoolean(recordOffset + FLAG, toggleTo); break; } finally { bytes.unlockLong(recordOffset + LOCK); } } } } long time = System.nanoTime() - start; final int toggles = (RUNS + RECORDS - 1) / RECORDS * RECORDS * 2; // one for each of two processes. System.out.printf("Toogled %,d times with an average delay of %,d ns%n", toggles, time / toggles); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testLocking() throws Exception { // a page long start = System.nanoTime(); final DirectStore store1 = DirectStore.allocate(1 << 12); final int lockCount = 20 * 1000000; Thread t = new Thread(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); System.out.println("Thread " + id); assertEquals(0, id >>> 24); try { DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 1) { slice1.writeInt(4, 0); } else { i--; } slice1.unlockInt(0); } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 0) { slice1.writeInt(4, 1); } else { i--; } slice1.unlockInt(0); } store1.free(); long time = System.nanoTime() - start; System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time)); }
#vulnerable code @Test public void testLocking() throws Exception { // a page final DirectStore store1 = DirectStore.allocate(1 << 12); final DirectStore store2 = DirectStore.allocate(1 << 12); final int lockCount = 10 * 1000000; Thread t = new Thread(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); System.out.println("Thread " + id); assertEquals(0, id >>> 24); int expected = (1 << 24) | (int) id; try { DirectBytes slice1 = store1.createSlice(); DirectBytes slice2 = store2.createSlice(); for (int i = 0; i < lockCount; i += 2) { slice1.busyLockInt(0); slice2.busyLockInt(0); int lockValue1 = slice1.readInt(0); if (lockValue1 != expected) assertEquals(expected, lockValue1); int lockValue2 = slice2.readInt(0); if (lockValue2 != expected) assertEquals(expected, lockValue2); int toggle1 = slice1.readInt(4); if (toggle1 == 1) { slice1.writeInt(4, 0); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int toggle2 = slice2.readInt(4); if (toggle2 == 1) { slice2.writeInt(4, 0); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int lockValue1A = slice1.readInt(0); int lockValue2A = slice1.readInt(0); try { slice2.unlockInt(0); slice1.unlockInt(0); } catch (IllegalStateException e) { int lockValue1B = slice1.readInt(0); int lockValue2B = slice2.readInt(0); System.err.println("i= " + i + " lock: " + Integer.toHexString(lockValue1A) + " / " + Integer.toHexString(lockValue2A) + " lock: " + Integer.toHexString(lockValue1B) + " / " + Integer.toHexString(lockValue2B)); throw e; } } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); int expected = (1 << 24) | (int) id; System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); DirectBytes slice2 = store2.createSlice(); for (int i = 0; i < lockCount; i += 2) { slice1.busyLockInt(0); slice2.busyLockInt(0); int lockValue1 = slice1.readInt(0); if (lockValue1 != expected) assertEquals(expected, lockValue1); int lockValue2 = slice2.readInt(0); if (lockValue2 != expected) assertEquals(expected, lockValue2); int toggle1 = slice1.readInt(4); if (toggle1 == 0) { slice1.writeInt(4, 1); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int toggle2 = slice2.readInt(4); if (toggle2 == 0) { slice2.writeInt(4, 1); // if (i % 10000== 0) // System.out.println("t: " + i); } else { i--; } int lockValue1A = slice1.readInt(0); int lockValue2A = slice1.readInt(0); try { slice2.unlockInt(0); slice1.unlockInt(0); } catch (IllegalStateException e) { int lockValue1B = slice1.readInt(0); int lockValue2B = slice2.readInt(0); System.err.println("i= " + i + " lock: " + Integer.toHexString(lockValue1A) + " / " + Integer.toHexString(lockValue2A) + " lock: " + Integer.toHexString(lockValue1B) + " / " + Integer.toHexString(lockValue2B)); throw e; } } store1.free(); store2.free(); } #location 51 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void manyToggles(DirectStore store1, int lockCount, int from, int to) { long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); int records = 8; for (int i = 0; i < lockCount; i += records) { for (long j = 0; j < records * 64; j += 64) { slice1.positionAndSize(j, 64); assertTrue( slice1.tryLockNanosInt(0L, 5 * 1000 * 1000)); int toggle1 = slice1.readInt(4); if (toggle1 == from) { slice1.writeInt(4L, to); } else { i--; } slice1.unlockInt(0L); } } }
#vulnerable code private void manyToggles(DirectStore store1, int lockCount, int from, int to) { long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { assertTrue( slice1.tryLockNanosInt(0L, 5 * 1000 * 1000)); int toggle1 = slice1.readInt(4); if (toggle1 == from) { slice1.writeInt(4L, to); } else { i--; } slice1.unlockInt(0L); System.nanoTime(); // do something small between locks } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void benchmarkByteLargeArray() { long length = 1L << 32; long start = System.nanoTime(); DirectBytes array = DirectStore.allocateLazy(length).bytes(); System.out.println("Constructor time: " + (System.nanoTime() - start) / 1e9 + " sec"); int iters = 2; byte one = 1; start = System.nanoTime(); for (int it = 0; it < iters; it++) { for (long i = 0; i < length; i++) { array.writeByte(i, one); array.writeByte(i, (byte) (array.readByte(i) + one)); } } System.out.println("Computation time: " + (System.nanoTime() - start) / 1e9 / iters + " sec"); }
#vulnerable code @Test @Ignore public void benchmarkByteLargeArray() { long length = 1L << 32; long start = System.nanoTime(); DirectBytes array = DirectStore.allocateLazy(length).createSlice(); System.out.println("Constructor time: " + (System.nanoTime() - start) / 1e9 + " sec"); int iters = 2; byte one = 1; start = System.nanoTime(); for (int it = 0; it < iters; it++) { for (long i = 0; i < length; i++) { array.writeByte(i, one); array.writeByte(i, (byte) (array.readByte(i) + one)); } } System.out.println("Computation time: " + (System.nanoTime() - start) / 1e9 / iters + " sec"); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSimpleLock() { DirectBytes bytes = new DirectStore(64).bytes(); bytes.writeLong(0, -1L); assertFalse(bytes.tryLockLong(0)); bytes.writeLong(0, 0L); assertTrue(bytes.tryLockLong(0)); long val1 = bytes.readLong(0); assertTrue(bytes.tryLockLong(0)); bytes.unlockLong(0); assertEquals(val1, bytes.readLong(0)); bytes.unlockLong(0); assertEquals(0L, bytes.readLong(0)); try { bytes.unlockLong(0); fail(); } catch (IllegalMonitorStateException e) { // expected. } }
#vulnerable code @Test public void testSimpleLock() { DirectBytes bytes = new DirectStore(64).createSlice(); bytes.writeLong(0, -1L); assertFalse(bytes.tryLockLong(0)); bytes.writeLong(0, 0L); assertTrue(bytes.tryLockLong(0)); long val1 = bytes.readLong(0); assertTrue(bytes.tryLockLong(0)); bytes.unlockLong(0); assertEquals(val1, bytes.readLong(0)); bytes.unlockLong(0); assertEquals(0L, bytes.readLong(0)); try { bytes.unlockLong(0); fail(); } catch (IllegalMonitorStateException e) { // expected. } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAllocate() throws Exception { long size = 1L << 24; // 31; don't overload cloud-bees DirectStore store = DirectStore.allocate(size); assertEquals(size, store.size()); DirectBytes slice = store.bytes(); slice.positionAndSize(0, size); slice.writeLong(0, size); slice.writeLong(size - 8, size); store.free(); }
#vulnerable code @Test public void testAllocate() throws Exception { long size = 1L << 24; // 31; don't overload cloud-bees DirectStore store = DirectStore.allocate(size); assertEquals(size, store.size()); DirectBytes slice = store.createSlice(); slice.positionAndSize(0, size); slice.writeLong(0, size); slice.writeLong(size - 8, size); store.free(); } #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 testUnmap() throws IOException, InterruptedException { String TMP = System.getProperty("java.io.tmpdir"); String basePath = TMP + "/testUnmap"; File file = new File(basePath); File dir = file.getParentFile(); long free0 = dir.getFreeSpace(); MappedFile mfile = new MappedFile(basePath, 1024 * 1024); MappedMemory map0 = mfile.acquire(0); fill(map0.buffer()); MappedMemory map1 = mfile.acquire(1); fill(map1.buffer().force()); long free1 = dir.getFreeSpace(); mfile.release(map1); mfile.release(map0); mfile.close(); // printMappings(); long free2 = dir.getFreeSpace(); delete(file); long free3 = 0; for (int i = 0; i < 100; i++) { free3 = dir.getFreeSpace(); System.out.println("Freed " + free0 + " ~ " + free1 + " ~ " + free2 + " ~ " + free3 + ", delete = " + file.delete()); if (free3 > free1) break; Thread.sleep(500); } assertTrue("free3-free1: " + (free3 - free1), free3 > free1); }
#vulnerable code @Test public void testUnmap() throws IOException, InterruptedException { String TMP = System.getProperty("java.io.tmpdir"); String basePath = TMP + "/testUnmap"; File file = new File(basePath); File dir = file.getParentFile(); long free0 = dir.getFreeSpace(); MappedFile mfile = new MappedFile(basePath, 1024 * 1024); MappedMemory map0 = mfile.acquire(0); fill(map0.buffer()); MappedMemory map1 = mfile.acquire(1); fill(map1.buffer().force()); long free1 = dir.getFreeSpace(); map1.release(); map0.release(); mfile.close(); // printMappings(); long free2 = dir.getFreeSpace(); delete(file); long free3 = 0; for (int i = 0; i < 100; i++) { free3 = dir.getFreeSpace(); System.out.println("Freed " + free0 + " ~ " + free1 + " ~ " + free2 + " ~ " + free3 + ", delete = " + file.delete()); if (free3 > free1) break; Thread.sleep(500); } assertTrue("free3-free1: " + (free3 - free1), free3 > free1); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAcquireOverlap() throws Exception { File path = newTempraryFile("vmf-acquire-overlap"); VanillaMappedFile vmf = VanillaMappedFile.readWrite(path); VanillaMappedBlocks blocks = VanillaMappedBlocks.readWrite(path,128); VanillaMappedBuffer b1 = blocks.acquire(0); b1.writeLong(1); b1.release(); assertEquals(0, b1.refCount()); assertTrue(b1.unmapped()); VanillaMappedBuffer b2 = blocks.acquire(1); b2.writeLong(2); b2.release(); assertEquals(0, b2.refCount()); assertTrue(b2.unmapped()); VanillaMappedBuffer b3 = blocks.acquire(2); b3.writeLong(3); b3.release(); assertEquals(0, b3.refCount()); assertTrue(b3.unmapped()); VanillaMappedBuffer b4 = vmf.sliceAt(0, 128 * 3); assertEquals(1, b4.refCount()); assertEquals(384, b4.size()); assertEquals(1L, b4.readLong(0)); assertEquals(2L, b4.readLong(128)); assertEquals(3L, b4.readLong(256)); vmf.close(); blocks.close(); }
#vulnerable code @Test public void testAcquireOverlap() throws Exception { VanillaMappedFile vmf = new VanillaMappedFile( newTempraryFile("vmf-acquire-overlap"), VanillaMappedMode.RW); VanillaMappedBlocks blocks = vmf.blocks(128); VanillaMappedBuffer b1 = blocks.acquire(0); b1.writeLong(1); b1.release(); assertEquals(0,b1.refCount()); assertTrue(b1.unmapped()); VanillaMappedBuffer b2 = blocks.acquire(1); b2.writeLong(2); b2.release(); assertEquals(0,b2.refCount()); assertTrue(b2.unmapped()); VanillaMappedBuffer b3 = blocks.acquire(2); b3.writeLong(3); b3.release(); assertEquals(0,b3.refCount()); assertTrue(b3.unmapped()); VanillaMappedBuffer b4 = vmf.sliceAt(0, 128 * 3); assertEquals( 1, b4.refCount()); assertEquals(384, b4.size()); assertEquals( 1L, b4.readLong(0)); assertEquals( 2L, b4.readLong(128)); assertEquals( 3L, b4.readLong(256)); vmf.close(); } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @NotNull @Override public String readUTF() { try { int len = readUnsignedShort(); StringBuilder utfReader = acquireStringBuilder(); readUTF0(utfReader, len); return utfReader.length() == 0 ? "" : SI.intern(utfReader); } catch (IOException unexpected) { throw new AssertionError(unexpected); } }
#vulnerable code @NotNull @Override public String readUTF() { try { int len = readUnsignedShort(); StringBuilder utfReader = acquireStringBuilder(); readUTF0(utfReader, len); return utfReader.length() == 0 ? "" : stringInterner().intern(utfReader); } catch (IOException unexpected) { throw new AssertionError(unexpected); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION