input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#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 11 #vulnerability type NULL_DEREFERENCE
#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"); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public static void main(final String[] args) throws Exception { final JmsQueueReceiver receiver = new JmsQueueReceiver(); receiver.doMain(args); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @GenerateMicroBenchmark public String test03_getCallerClassNameReflectively() { return ReflectiveCallerClassUtility.getCaller(3).getName(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @GenerateMicroBenchmark public String test03_getCallerClassNameReflectively() { return ReflectionUtil.getCallerClass(3).getName(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 16 #vulnerability type RESOURCE_LEAK
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void getStream() { final LoggerStream stream = logger.getStream(Level.DEBUG); stream.println("Debug message 1"); stream.print("Debug message 2"); stream.println(); stream.println(); // verify blank log message stream.print("Debug message 3\n"); stream.print("\r\n"); // verify windows EOL works assertEquals(5, results.size()); assertThat("Incorrect message", results.get(0), startsWith(" DEBUG Debug message 1")); assertThat("Incorrect message", results.get(1), startsWith(" DEBUG Debug message 2")); assertEquals("Message should be blank-ish", " DEBUG ", results.get(2)); assertThat("Incorrect message", results.get(3), startsWith(" DEBUG Debug message 3")); assertEquals("Message should be blank-ish", " DEBUG ", results.get(4)); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void getStream() { final PrintWriter stream = logger.printWriter(Level.DEBUG); stream.println("println"); stream.print("print followed by println"); stream.println(); stream.println("multiple\nlines"); stream.println(); // verify blank log message stream.print("print embedded newline\n"); stream.print("\r\n"); // verify windows EOL works stream.print("Last Line without newline"); stream.close(); assertEquals(8, results.size()); assertEquals("msg 1", " DEBUG println", results.get(0)); assertEquals("msg 2", " DEBUG print followed by println", results.get(1)); assertEquals("msg 3", " DEBUG multiple", results.get(2)); assertEquals("msg 4", " DEBUG lines", results.get(3)); assertEquals("msg 5 should be blank-ish", " DEBUG ", results.get(4)); assertEquals("msg 6", " DEBUG print embedded newline", results.get(5)); assertEquals("msg 7 should be blank-ish", " DEBUG ", results.get(6)); assertEquals("msg 8 Last line", " DEBUG Last Line without newline", results.get(7)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSubset() throws Exception { Properties props = new Properties(); props.load(new FileInputStream("target/test-classes/log4j2-properties.properties")); Properties subset = PropertiesUtil.extractSubset(props, "appender.Stdout.filter.marker"); assertNotNull("No subset returned", subset); assertTrue("Incorrect number of items. Expected 4, actual " + subset.size(), subset.size() == 4); assertTrue("Missing property", subset.containsKey("type")); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSubset() throws Exception { Properties props = new Properties(); props.load(ClassLoader.getSystemResourceAsStream("log4j2-properties.properties")); Properties subset = PropertiesUtil.extractSubset(props, "appender.Stdout.filter.marker"); assertNotNull("No subset returned", subset); assertTrue("Incorrect number of items. Expected 4, actual " + subset.size(), subset.size() == 4); assertTrue("Missing property", subset.containsKey("type")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void format(final LogEvent event, final StringBuilder toAppendTo) { final long timestamp = event.getTimeMillis(); synchronized (this) { if (timestamp != lastTimestamp) { lastTimestamp = timestamp; relative = Long.toString(timestamp - startTime); } } toAppendTo.append(relative); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void format(final LogEvent event, final StringBuilder toAppendTo) { final long timestamp = event.getTimeMillis(); toAppendTo.append(timestamp - startTime); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWrite_dataExceedingBufferSize() 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 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWrite_dataExceedingBufferSize() 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 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now }}
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()); }}
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 }}
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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")))))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void copyFile(final File source, final File destination) throws IOException { if (!destination.exists()) { destination.createNewFile(); } FileChannel srcChannel = null; FileChannel destChannel = null; FileInputStream srcStream = null; FileOutputStream destStream = null; try { srcStream = new FileInputStream(source); destStream = new FileOutputStream(destination); srcChannel = srcStream.getChannel(); destChannel = destStream.getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (srcStream != null) { srcStream.close(); } if (destChannel != null) { destChannel.close(); } if (destStream != null) { destStream.close(); } } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private static void copyFile(final File source, final File destination) throws IOException { if (!destination.exists()) { destination.createNewFile(); } Files.copy(source.toPath(), destination.toPath()); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 10 #vulnerability type THREAD_SAFETY_VIOLATION
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testJmsQueueAppenderCompatibility() throws Exception { assertEquals(0, queue.size()); final JmsAppender appender = (JmsAppender) ctx.getRequiredAppender("JmsQueueAppender"); final LogEvent expected = createLogEvent(); appender.append(expected); assertEquals(1, queue.size()); final Message message = queue.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
#fixed code @Test public void testJmsQueueAppenderCompatibility() throws Exception { final JmsAppender appender = (JmsAppender) ctx.getRequiredAppender("JmsQueueAppender"); 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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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 6 #vulnerability type RESOURCE_LEAK
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void verifyFile(final int count) throws Exception { // String expected = "[\\w]* \\[\\s*\\] INFO TestLogger - Test$"; final String expected = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} \\[[^\\]]*\\] INFO TestLogger - Test"; final Pattern pattern = Pattern.compile(expected); final FileInputStream fis = new FileInputStream(FILENAME); final BufferedReader is = new BufferedReader(new InputStreamReader(fis)); int counter = 0; String str = Strings.EMPTY; while (is.ready()) { str = is.readLine(); // System.out.println(str); ++counter; final Matcher matcher = pattern.matcher(str); assertTrue("Bad data: " + str, matcher.matches()); } fis.close(); assertTrue("Incorrect count: was " + counter + " should be " + count, count == counter); fis.close(); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code private void verifyFile(final int count) throws Exception { // String expected = "[\\w]* \\[\\s*\\] INFO TestLogger - Test$"; final String expected = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} \\[[^\\]]*\\] INFO TestLogger - Test"; final Pattern pattern = Pattern.compile(expected); int lines = 0; try (final BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME)))) { String str = Strings.EMPTY; while (is.ready()) { str = is.readLine(); // System.out.println(str); ++lines; final Matcher matcher = pattern.matcher(str); assertTrue("Unexpected data: " + str, matcher.matches()); } } Assert.assertEquals(count, lines); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 UdpSocketServer<ObjectInputStream> socketServer = UdpSocketServer.createSerializedSocketServer(port); final Thread server = new Log4jThread(socketServer); server.start(); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { final String line = reader.readLine(); if (line == null || line.equalsIgnoreCase("Quit") || line.equalsIgnoreCase("Stop") || line.equalsIgnoreCase("Exit")) { socketServer.shutdown(); server.join(); break; } } } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(final String[] args) throws Exception { final CommandLineArguments cla = parseCommandLine(args, UdpSocketServer.class, new CommandLineArguments()); if (cla.isHelp()) { return; } if (cla.getConfigLocation() != null) { ConfigurationFactory.setConfigurationFactory(new ServerConfigurationFactory(cla.getConfigLocation())); } final UdpSocketServer<ObjectInputStream> socketServer = UdpSocketServer .createSerializedSocketServer(cla.getPort()); final Thread serverThread = new Log4jThread(socketServer); serverThread.start(); if (cla.isInteractive()) { final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { final String line = reader.readLine(); if (line == null || line.equalsIgnoreCase("Quit") || line.equalsIgnoreCase("Stop") || line.equalsIgnoreCase("Exit")) { socketServer.shutdown(); serverThread.join(); break; } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); Logger logger = LogManager.getLogger(); if (!(logger instanceof AsyncLogger)) { throw new IllegalStateException(); } logger.info("Starting..."); Thread.sleep(100); final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); // warmup final int ITERATIONS = 100000; long startMs = System.currentTimeMillis(); long end = startMs + TimeUnit.SECONDS.toMillis(10); long total = 0; int count = 0; StringBuilder sb = new StringBuilder(512); do { sb.setLength(0); long startNanos = System.nanoTime(); long uptime = runtimeMXBean.getUptime(); loop(logger, ITERATIONS); long endNanos = System.nanoTime(); long durationNanos = endNanos - startNanos; final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos; sb.append(uptime).append(" Warmup: Throughput: ").append(opsPerSec).append(" ops/s"); System.out.println(sb); total += opsPerSec; count++; // Thread.sleep(1000);// drain buffer } while (System.currentTimeMillis() < end); System.out.printf("Average warmup throughput: %,d ops/s%n", total/count); final int COUNT = 10; final long[] durationNanos = new long[10]; for (int i = 0; i < COUNT; i++) { final long startNanos = System.nanoTime(); loop(logger, ITERATIONS); long endNanos = System.nanoTime(); durationNanos[i] = endNanos - startNanos; // Thread.sleep(1000);// drain buffer } total = 0; for (int i = 0; i < COUNT; i++) { final long opsPerSec = (1000L * 1000L * 1000L * ITERATIONS) / durationNanos[i]; System.out.printf("Throughput: %,d ops/s%n", opsPerSec); total += opsPerSec; } System.out.printf("Average throughput: %,d ops/s%n", total/COUNT); } #location 48 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); Logger logger = LogManager.getLogger(); if (!(logger instanceof AsyncLogger)) { throw new IllegalStateException(); } // work around a bug in Log4j-2.5 workAroundLog4j2_5Bug(); logger.error("Starting..."); System.out.println("Starting..."); Thread.sleep(100); final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); final long testStartNanos = System.nanoTime(); final long[] UPTIMES = new long[1024]; final long[] DURATIONS = new long[1024]; // warmup long startMs = System.currentTimeMillis(); long end = startMs + TimeUnit.SECONDS.toMillis(10); int warmupCount = 0; do { runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, warmupCount); warmupCount++; // Thread.sleep(1000);// drain buffer } while (System.currentTimeMillis() < end); final int COUNT = 10; for (int i = 0; i < COUNT; i++) { int count = warmupCount + i; runTest(logger, runtimeMXBean, UPTIMES, DURATIONS, count); // Thread.sleep(1000);// drain buffer } double testDurationNanos = System.nanoTime() - testStartNanos; System.out.println("Done. Calculating stats..."); printReport("Warmup", UPTIMES, DURATIONS, 0, warmupCount); printReport("Test", UPTIMES, DURATIONS, warmupCount, COUNT); StringBuilder sb = new StringBuilder(512); sb.append("Test took: ").append(testDurationNanos/(1000.0*1000.0*1000.0)).append(" sec"); System.out.println(sb); final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); for (int i = 0; i < gcBeans.size(); i++) { GarbageCollectorMXBean gcBean = gcBeans.get(i); sb.setLength(0); sb.append("GC[").append(gcBean.getName()).append("] "); sb.append(gcBean.getCollectionCount()).append(" collections, collection time="); sb.append(gcBean.getCollectionTime()).append(" millis."); System.out.println(sb); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toSerializable(final LogEvent event) { 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.print(event.getNanoTime()); printer.print(event.getTimeMillis()); printer.print(event.getLevel()); printer.print(event.getThreadName()); printer.print(event.getMessage().getFormattedMessage()); printer.print(event.getLoggerFqcn()); printer.print(event.getLoggerName()); printer.print(event.getMarker()); printer.print(event.getThrownProxy()); printer.print(event.getSource()); printer.print(event.getContextMap()); printer.print(event.getContextStack()); printer.println(); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(event.toString(), e); return getFormat().getCommentMarker() + " " + e; } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String toSerializable(final LogEvent event) { 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.print(event.getNanoTime()); printer.print(event.getTimeMillis()); printer.print(event.getLevel()); printer.print(event.getThreadName()); printer.print(event.getMessage().getFormattedMessage()); printer.print(event.getLoggerFqcn()); printer.print(event.getLoggerName()); printer.print(event.getMarker()); printer.print(event.getThrownProxy()); printer.print(event.getSource()); printer.print(event.getContextMap()); printer.print(event.getContextStack()); printer.println(); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(event.toString(), e); return getFormat().getCommentMarker() + " " + e; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toString() { return "JeroMqAppender [context=" + context + ", publisher=" + publisher + ", endpoints=" + endpoints + "]"; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String toString() { return "JeroMqAppender{" + "name=" + getName() + ", state=" + getState() + ", manager=" + manager + ", endpoints=" + endpoints + '}'; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void stop() { LOGGER.debug("Stopping LoggerContext[name={}, {}]...", getName(), this); configLock.lock(); try { if (this.isStopped()) { return; } this.setStopping(); try { Server.unregisterLoggerContext(getName()); // LOG4J2-406, LOG4J2-500 } catch (final Exception ex) { LOGGER.error("Unable to unregister MBeans", ex); } if (shutdownCallback != null) { shutdownCallback.cancel(); shutdownCallback = null; } final Configuration prev = configuration; configuration = NULL_CONFIGURATION; updateLoggers(); prev.stop(); externalContext = null; LogManager.getFactory().removeContext(this); this.setStopped(); } finally { configLock.unlock(); } LOGGER.debug("Stopped LoggerContext[name={}, {}]...", getName(), this); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void stop() { stop(0, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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 4 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(final String[] args) throws Exception { final JmsTopicReceiver receiver = new JmsTopicReceiver(); receiver.doMain(args); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = IOException.class) public void connectionFailsWithoutValidServerCertificate() throws SslConfigurationException, IOException { TrustStoreConfiguration tsc = new TrustStoreConfiguration(TestConstants.TRUSTSTORE_FILE, null); SslConfiguration sc = SslConfiguration.createSSLConfiguration(null, tsc); SSLSocketFactory factory = sc.getSslSocketFactory(); SSLSocket clientSocket = (SSLSocket) factory.createSocket(TLS_TEST_HOST, TLS_TEST_PORT); OutputStream os = clientSocket.getOutputStream(); os.write("GET config/login_verify2?".getBytes()); Assert.assertTrue(false); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = IOException.class) public void connectionFailsWithoutValidServerCertificate() throws IOException, StoreConfigurationException { TrustStoreConfiguration tsc = new TrustStoreConfiguration(TestConstants.TRUSTSTORE_FILE, null, null, null); SslConfiguration sc = SslConfiguration.createSSLConfiguration(null, null, tsc); SSLSocketFactory factory = sc.getSslSocketFactory(); SSLSocket clientSocket = (SSLSocket) factory.createSocket(TLS_TEST_HOST, TLS_TEST_PORT); OutputStream os = clientSocket.getOutputStream(); os.write("GET config/login_verify2?".getBytes()); Assert.assertTrue(false); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") protected void doConfigure() { boolean setRoot = false; boolean setLoggers = false; for (final Node child : rootNode.getChildren()) { createConfiguration(child, null); if (child.getObject() == null) { continue; } if (child.getName().equalsIgnoreCase("properties")) { if (tempLookup == subst.getVariableResolver()) { subst.setVariableResolver((StrLookup) child.getObject()); } else { LOGGER.error("Properties declaration must be the first element in the configuration"); } continue; } else if (tempLookup == subst.getVariableResolver()) { final Map<String, String> map = (Map<String, String>) componentMap.get(CONTEXT_PROPERTIES); final StrLookup lookup = map == null ? null : new MapLookup(map); subst.setVariableResolver(new Interpolator(lookup)); } if (child.getName().equalsIgnoreCase("appenders")) { appenders = (ConcurrentMap<String, Appender<?>>) child.getObject(); } else if (child.getObject() instanceof Filter) { addFilter((Filter) child.getObject()); } else if (child.getName().equalsIgnoreCase("loggers")) { final Loggers l = (Loggers) child.getObject(); loggers = l.getMap(); setLoggers = true; if (l.getRoot() != null) { root = l.getRoot(); setRoot = true; } } else { LOGGER.error("Unknown object \"" + child.getName() + "\" of type " + child.getObject().getClass().getName() + " is ignored"); } } if (!setLoggers) { LOGGER.warn("No Loggers were configured, using default. Is the Loggers element missing?"); setToDefault(); return; } else if (!setRoot) { LOGGER.warn("No Root logger was configured, using default"); setToDefault(); return; } for (final Map.Entry<String, LoggerConfig> entry : loggers.entrySet()) { final LoggerConfig l = entry.getValue(); for (final AppenderRef ref : l.getAppenderRefs()) { final Appender app = appenders.get(ref.getRef()); if (app != null) { l.addAppender(app, ref.getLevel(), ref.getFilter()); } else { LOGGER.error("Unable to locate appender " + ref.getRef() + " for logger " + l.getName()); } } } setParents(); } #location 63 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") protected void doConfigure() { boolean setRoot = false; boolean setLoggers = false; for (final Node child : rootNode.getChildren()) { createConfiguration(child, null); if (child.getObject() == null) { continue; } if (child.getName().equalsIgnoreCase("properties")) { if (tempLookup == subst.getVariableResolver()) { subst.setVariableResolver((StrLookup) child.getObject()); } else { LOGGER.error("Properties declaration must be the first element in the configuration"); } continue; } else if (tempLookup == subst.getVariableResolver()) { final Map<String, String> map = (Map<String, String>) componentMap.get(CONTEXT_PROPERTIES); final StrLookup lookup = map == null ? null : new MapLookup(map); subst.setVariableResolver(new Interpolator(lookup)); } if (child.getName().equalsIgnoreCase("appenders")) { appenders = (ConcurrentMap<String, Appender<?>>) child.getObject(); } else if (child.getObject() instanceof Filter) { addFilter((Filter) child.getObject()); } else if (child.getName().equalsIgnoreCase("loggers")) { final Loggers l = (Loggers) child.getObject(); loggers = l.getMap(); setLoggers = true; if (l.getRoot() != null) { root = l.getRoot(); setRoot = true; } } else { LOGGER.error("Unknown object \"" + child.getName() + "\" of type " + child.getObject().getClass().getName() + " is ignored"); } } if (!setLoggers) { LOGGER.warn("No Loggers were configured, using default. Is the Loggers element missing?"); setToDefault(); return; } else if (!setRoot) { LOGGER.warn("No Root logger was configured, creating default ERROR-level Root logger with Console appender"); setToDefault(); // return; // LOG4J2-219: creating default root=ok, but don't exclude configured Loggers } for (final Map.Entry<String, LoggerConfig> entry : loggers.entrySet()) { final LoggerConfig l = entry.getValue(); for (final AppenderRef ref : l.getAppenderRefs()) { final Appender app = appenders.get(ref.getRef()); if (app != null) { l.addAppender(app, ref.getLevel(), ref.getFilter()); } else { LOGGER.error("Unable to locate appender " + ref.getRef() + " for logger " + l.getName()); } } } setParents(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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 }}
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); System.setProperty("log4j.configurationFile", "perf3PlainNoLoc.xml"); Logger logger = LogManager.getLogger(); logger.info("Starting..."); // initializes Log4j Thread.sleep(100); final long nanoTimeCost = PerfTest.calcNanoTimeCost(); System.out.println(nanoTimeCost); long maxOpsPerSec = 1000 * 1000; // just assume... TODO make parameter double targetLoadLevel = 0.05; // TODO make parameter long oneOpDurationNanos = TimeUnit.SECONDS.toNanos(1) / maxOpsPerSec; long idleTimeNanos = (long) ((1.0 - targetLoadLevel) * oneOpDurationNanos); System.out.printf("Idle time is %d nanos at %,f load level%n", idleTimeNanos, targetLoadLevel); final int WARMUP_ITERATIONS = 5; final int threadCount = 8; List<List<Histogram>> warmups = new ArrayList<>(); for (int i = 0; i < WARMUP_ITERATIONS; i++) { List<Histogram> warmupHistograms = new ArrayList<>(threadCount); final int WARMUP_COUNT = 500000; final long interval = idleTimeNanos; final IdleStrategy idleStrategy = new NoOpIdleStrategy(); runLatencyTest(logger, WARMUP_COUNT, interval, idleStrategy, warmupHistograms, nanoTimeCost, threadCount); warmups.add(warmupHistograms); } long start = System.currentTimeMillis(); final int MEASURED_ITERATIONS = 5; List<List<Histogram>> tests = new ArrayList<>(); for (int i = 0; i < MEASURED_ITERATIONS; i++) { List<Histogram> histograms = new ArrayList<>(threadCount); final int COUNT = 5000000; final long interval = idleTimeNanos; final IdleStrategy idleStrategy = new NoOpIdleStrategy(); runLatencyTest(logger, COUNT, interval, idleStrategy, histograms, nanoTimeCost, threadCount); tests.add(histograms); } long end = System.currentTimeMillis(); final Histogram result = new Histogram(TimeUnit.SECONDS.toNanos(10), 3); for (List<Histogram> done : tests) { for (Histogram hist : done) { result.add(hist); } } result.outputPercentileDistribution(System.out, 1000.0); System.out.println("Test duration: " + (end - start) / 1000.0 + " seconds"); } #location 17 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code public static void main(String[] args) throws Exception { if (args.length < 2) { System.out.println("Please specify thread count and interval (us)"); return; } // double targetLoadLevel = Double.parseDouble(args[0]); final int threadCount = Integer.parseInt(args[0]); final int intervalMicros = Integer.parseInt(args[1]); System.setProperty("log4j2.AsyncEventRouter", PrintingDefaultAsyncEventRouter.class.getName()); System.setProperty("AsyncLogger.RingBufferSize", String.valueOf(256 * 1024)); System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName()); System.setProperty("log4j.configurationFile", "perf3PlainNoLoc.xml"); Logger logger = LogManager.getLogger(); logger.info("Starting..."); // initializes Log4j Thread.sleep(100); final long nanoTimeCost = PerfTest.calcNanoTimeCost(); System.out.println("nanoTimeCost=" + nanoTimeCost); // long maxOpsPerSec = 1000 * 1000; // just assume... TODO make parameter // // long oneOpDurationNanos = TimeUnit.SECONDS.toNanos(1) / maxOpsPerSec; // long idleTimeNanos = (long) ((1.0 - targetLoadLevel) * oneOpDurationNanos); // idleTimeNanos *= 10; // System.out.printf("Idle time is %d nanos at %,f load level%n", idleTimeNanos, targetLoadLevel); final long interval = TimeUnit.MICROSECONDS.toNanos(intervalMicros);// * threadCount; System.out.printf("%d threads, interval is %d nanos%n", threadCount, interval); final long WARMUP_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(1); List<Histogram> warmupHistograms = new ArrayList<>(threadCount); final int WARMUP_COUNT = 50000 / threadCount; final IdleStrategy idleStrategy = new YieldIdleStrategy(); runLatencyTest(logger, WARMUP_DURATION_MILLIS, WARMUP_COUNT, interval, idleStrategy, warmupHistograms, nanoTimeCost, threadCount); Thread.sleep(1000); long start = System.currentTimeMillis(); List<Histogram> histograms = new ArrayList<>(threadCount); final long TEST_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(4); final int COUNT = 5000000 / threadCount; runLatencyTest(logger, TEST_DURATION_MILLIS, COUNT, interval, idleStrategy, histograms, nanoTimeCost, threadCount); long end = System.currentTimeMillis(); final Histogram result = new Histogram(TimeUnit.SECONDS.toNanos(10), 3); for (Histogram hist : histograms) { result.add(hist); } result.outputPercentileDistribution(System.out, 1000.0); System.out.println("Test duration: " + (end - start) / 1000.0 + " seconds"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void releaseSub() { try { if (info != null) { info.session.close(); info.conn.close(); } } catch (final JMSException ex) { LOGGER.error("Error closing " + getName(), ex); } finally { info = null; } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void releaseSub() { if (info != null) { cleanup(false); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)))))); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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]); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()); }}
Below is the vulnerable code, please generate the patch based on the following information.
#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 8 #vulnerability type NULL_DEREFERENCE
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEnvironment() throws Exception { ctx = Configurator.initialize("-config", null); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); assertNotNull("No configuration", config); assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName()); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders map should not be null.", map); assertTrue("Appenders map should not be empty.", map.size() > 0); Appender app = null; for (final Map.Entry<String, Appender> entry: map.entrySet()) { if (entry.getKey().equals("List2")) { app = entry.getValue(); break; } } assertNotNull("No ListAppender named List2", app); final Layout<? extends Serializable> layout = app.getLayout(); assertNotNull("Appender List2 does not have a Layout", layout); assertTrue("Appender List2 is not configured with a PatternLayout", layout instanceof PatternLayout); final String pattern = ((PatternLayout) layout).getConversionPattern(); assertNotNull("No conversion pattern for List2 PatternLayout", pattern); assertFalse("Environment variable was not substituted", pattern.startsWith("${env:PATH}")); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEnvironment() throws Exception { ctx = Configurator.initialize("-config", null); LogManager.getLogger("org.apache.test.TestConfigurator"); final Configuration config = ctx.getConfiguration(); assertNotNull("No configuration", config); assertEquals("Incorrect Configuration.", CONFIG_NAME, config.getName()); final Map<String, Appender> map = config.getAppenders(); assertNotNull("Appenders map should not be null.", map); assertThat(map, hasSize(greaterThan(0))); assertThat("No ListAppender named List2", map, hasKey("List2")); Appender app = map.get("List2"); final Layout<? extends Serializable> layout = app.getLayout(); assertNotNull("Appender List2 does not have a Layout", layout); assertThat("Appender List2 is not configured with a PatternLayout", layout, instanceOf(PatternLayout.class)); final String pattern = ((PatternLayout) layout).getConversionPattern(); assertNotNull("No conversion pattern for List2 PatternLayout", pattern); assertFalse("Environment variable was not substituted", pattern.startsWith("${env:PATH}")); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testThresholds() { RegexFilter filter = RegexFilter.createFilter(Pattern.compile(".* test .*"), false, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, "This is a test message", (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, "This is not a test", (Throwable) null)); LogEvent event = new Log4jLogEvent(null, null, null, Level.DEBUG, new SimpleMessage("Another test message"), null); assertSame(Filter.Result.NEUTRAL, filter.filter(event)); event = new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage("test"), null); assertSame(Filter.Result.DENY, filter.filter(event)); filter = RegexFilter.createFilter((Pattern) TypeConverters.convert("* test *", Pattern.class, null), false, null, null); assertNull(filter); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testThresholds() throws Exception { RegexFilter filter = RegexFilter.createFilter(".* test .*", null, false, null, null); filter.start(); assertTrue(filter.isStarted()); assertSame(Filter.Result.NEUTRAL, filter.filter(null, Level.DEBUG, null, "This is a test message", (Throwable) null)); assertSame(Filter.Result.DENY, filter.filter(null, Level.ERROR, null, "This is not a test", (Throwable) null)); LogEvent event = new Log4jLogEvent(null, null, null, Level.DEBUG, new SimpleMessage("Another test message"), null); assertSame(Filter.Result.NEUTRAL, filter.filter(event)); event = new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage("test"), null); assertSame(Filter.Result.DENY, filter.filter(event)); filter = RegexFilter.createFilter(null, null, false, null, null); assertNull(filter); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected ConfigurationSource getInputFromString(final String config, final ClassLoader loader) { try { final URL url = new URL(config); return new ConfigurationSource(url.openStream(), FileUtils.fileFromURI(url.toURI())); } catch (final Exception ex) { final ConfigurationSource source = getInputFromResource(config, loader); if (source == null) { try { final File file = new File(config); return new ConfigurationSource(new FileInputStream(file), file); } catch (final FileNotFoundException fnfe) { // Ignore the exception LOGGER.catching(Level.DEBUG, fnfe); } } return source; } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code protected ConfigurationSource getInputFromString(final String config, final ClassLoader loader) { try { final URL url = new URL(config); return new ConfigurationSource(url.openStream(), FileUtils.fileFromUri(url.toURI())); } catch (final Exception ex) { final ConfigurationSource source = getInputFromResource(config, loader); if (source == null) { try { final File file = new File(config); return new ConfigurationSource(new FileInputStream(file), file); } catch (final FileNotFoundException fnfe) { // Ignore the exception LOGGER.catching(Level.DEBUG, fnfe); } } return source; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConfigurableBufferSize() 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 = 4 * 1024; assertNotEquals(bufferSize, RandomAccessFileManager.DEFAULT_BUFFER_SIZE); final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, bufferSize, null, null); // check the resulting buffer size is what was requested assertEquals(bufferSize, manager.getBufferSize()); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConfigurableBufferSize() 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 = 4 * 1024; assertNotEquals(bufferSize, RandomAccessFileManager.DEFAULT_BUFFER_SIZE); final RandomAccessFileManager manager = new RandomAccessFileManager(raf, file.getName(), os, false, bufferSize, null, null); // check the resulting buffer size is what was requested assertEquals(bufferSize, manager.getBufferSize()); }}
Below is the vulnerable code, please generate the patch based on the following information.
#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)); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); } #location 5 #vulnerability type RESOURCE_LEAK
#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)); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); receiver = new JmsQueueReceiver(FACTORY_NAME, QUEUE_NAME, null, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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)); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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... } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String readContents(final URI uri, final Charset charset) throws IOException { InputStream in = null; try { in = uri.toURL().openStream(); final Reader reader = new InputStreamReader(in, charset); final StringBuilder result = new StringBuilder(TEXT_BUFFER); final char[] buff = new char[PAGE]; int count = -1; while ((count = reader.read(buff)) >= 0) { result.append(buff, 0, count); } return result.toString(); } finally { try { in.close(); } catch (final Exception ignored) { // ignored } } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private String readContents(final URI uri, final Charset charset) throws IOException { if (charset == null) { throw new IllegalArgumentException("charset must not be null"); } Reader reader = null; try { InputStream in = uri.toURL().openStream(); // The stream is open and charset is not null, we can create the reader safely without a possible NPE. reader = new InputStreamReader(in, charset); final StringBuilder result = new StringBuilder(TEXT_BUFFER); final char[] buff = new char[PAGE]; int count = -1; while ((count = reader.read(buff)) >= 0) { result.append(buff, 0, count); } return result.toString(); } finally { try { if (reader != null) { reader.close(); } } catch (final Exception ignored) { // ignored } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTcpAppenderDeadlock() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(DYN_PORT) .withReconnectDelayMillis(100) .withName("test") .withImmediateFail(false) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug root.addAppender(appender); root.setAdditive(false); root.setLevel(Level.DEBUG); new TCPSocketServer(DYN_PORT).start(); root.debug("This message is written because a deadlock never."); final LogEvent event = list.poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testTcpAppenderDeadlock() throws Exception { // @formatter:off final SocketAppender appender = SocketAppender.newBuilder() .withHost("localhost") .withPort(DYN_PORT) .withReconnectDelayMillis(100) .withName("test") .withImmediateFail(false) .build(); // @formatter:on appender.start(); // set appender on root and set level to debug root.addAppender(appender); root.setAdditive(false); root.setLevel(Level.DEBUG); final TCPSocketServer tcpSocketServer = new TCPSocketServer(DYN_PORT); try { tcpSocketServer.start(); root.debug("This message is written because a deadlock never."); final LogEvent event = tcpSocketServer.getQueue().poll(3, TimeUnit.SECONDS); assertNotNull("No event retrieved", event); } finally { tcpSocketServer.shutdown(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); // Trigger the rollover for (int i = 0; i < 10; ++i) { // 30 chars per message: each message triggers a rollover logger.debug("This is a test message number " + i); // 30 chars: } Thread.sleep(100); // Allow time for rollover to complete 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(); for (File file : files) { System.out.println(file); } if (files.length == 3) { for (File file : files) { assertTrue("test-4.log.gz should have been deleted", Arrays.asList("test-1.log.gz", "test-2.log.gz", "test-3.log.gz").contains(file.getName())); } return; // test succeeded } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No rollover files found"); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAppender() throws Exception { final Logger logger = ctx.getLogger(); // Trigger the rollover for (int i = 0; i < 10; ++i) { // 30 chars per message: each message triggers a rollover logger.debug("This is a test message number " + i); // 30 chars: } Thread.sleep(100); // Allow time for rollover to complete final File dir = new File(DIR); assertTrue("Dir " + DIR + " should exist", dir.exists()); assertTrue("Dir " + DIR + " should contain files", dir.listFiles().length > 0); final int MAX_TRIES = 20; for (int i = 0; i < MAX_TRIES; i++) { final File[] files = dir.listFiles(); for (File file : files) { System.out.println(file); } if (files.length == 3) { for (File file : files) { assertTrue("test-4.log should have been deleted", Arrays.asList("test-1.log", "test-2.log", "test-3.log").contains(file.getName())); } return; // test succeeded } logger.debug("Adding additional event " + i); Thread.sleep(100); // Allow time for rollover to complete } fail("No rollover files found"); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code public void log(final LogEvent event) { beforeLogEvent(); try { if (!isFiltered(event)) { processLogEvent(event); } } finally { afterLogEvent(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void format(final LogEvent event, final StringBuilder output) { final long timestamp = event.getMillis(); synchronized (this) { if (timestamp != lastTimestamp) { lastTimestamp = timestamp; cachedDate = simpleFormat.format(timestamp); } } output.append(cachedDate); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void format(final LogEvent event, final StringBuilder output) { final long timestamp = event.getMillis(); synchronized (this) { if (timestamp != lastTimestamp) { lastTimestamp = timestamp; cachedDateString = simpleFormat.format(timestamp); } } output.append(cachedDateString); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected ConfigurationSource getInputFromResource(final String resource, final ClassLoader loader) { final URL url = Loader.getResource(resource, loader); if (url == null) { return null; } InputStream is = null; try { is = url.openStream(); } catch (final IOException ioe) { LOGGER.catching(Level.DEBUG, ioe); return null; } if (is == null) { return null; } if (FileUtils.isFile(url)) { try { return new ConfigurationSource(is, FileUtils.fileFromURI(url.toURI())); } catch (final URISyntaxException ex) { // Just ignore the exception. LOGGER.catching(Level.DEBUG, ex); } } return new ConfigurationSource(is, resource); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code protected ConfigurationSource getInputFromResource(final String resource, final ClassLoader loader) { final URL url = Loader.getResource(resource, loader); if (url == null) { return null; } InputStream is = null; try { is = url.openStream(); } catch (final IOException ioe) { LOGGER.catching(Level.DEBUG, ioe); return null; } if (is == null) { return null; } if (FileUtils.isFile(url)) { try { return new ConfigurationSource(is, FileUtils.fileFromUri(url.toURI())); } catch (final URISyntaxException ex) { // Just ignore the exception. LOGGER.catching(Level.DEBUG, ex); } } return new ConfigurationSource(is, resource); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toSerializable(final LogEvent event) { 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.print(event.getNanoTime()); printer.print(event.getTimeMillis()); printer.print(event.getLevel()); printer.print(event.getThreadName()); printer.print(event.getMessage().getFormattedMessage()); printer.print(event.getLoggerFqcn()); printer.print(event.getLoggerName()); printer.print(event.getMarker()); printer.print(event.getThrownProxy()); printer.print(event.getSource()); printer.print(event.getContextMap()); printer.print(event.getContextStack()); printer.println(); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(event.toString(), e); return getFormat().getCommentMarker() + " " + e; } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String toSerializable(final LogEvent event) { 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.print(event.getNanoTime()); printer.print(event.getTimeMillis()); printer.print(event.getLevel()); printer.print(event.getThreadName()); printer.print(event.getMessage().getFormattedMessage()); printer.print(event.getLoggerFqcn()); printer.print(event.getLoggerName()); printer.print(event.getMarker()); printer.print(event.getThrownProxy()); printer.print(event.getSource()); printer.print(event.getContextMap()); printer.print(event.getContextStack()); printer.println(); return buffer.toString(); } catch (final IOException e) { StatusLogger.getLogger().error(event.toString(), e); return getFormat().getCommentMarker() + " " + e; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWrite_dataExceedingBufferSize() 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 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testWrite_dataExceedingBufferSize() 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 + 1; final byte[] data = new byte[size]; manager.write(data); // no exception assertEquals(RandomAccessFileManager.DEFAULT_BUFFER_SIZE * 3, raf.length()); manager.flush(); assertEquals(size, raf.length()); // all data written to file now }}
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void executeProxyRequest( HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (doLog) { log("proxy: "+httpServletRequest.getRequestURI()+" -- "+httpMethodProxyRequest.getURI()); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation.replace(getProxyHostAndPort() + this.stringProxyPath, stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private void executeProxyRequest( HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (doLog) { log("proxy: "+httpServletRequest.getRequestURI()+" -- "+httpMethodProxyRequest.getURI()); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation.replace(getProxyHostAndPort() + this.stringProxyPath, stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); Streams.copy(inputStreamProxyResponse,outputStreamClientResponse,false);//copy; don't close streams }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toString() { return toStringHelper().toString(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String toString() { return MoreObjects.toStringHelper(this) .add("requestMetadata", requestMetadata) .add("temporaryAccess", temporaryAccess).toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public AccessToken refreshAccessToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); socket.setSoTimeout(READ_TIMEOUT_MS); AccessToken token; try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(GET_AUTH_TOKEN_REQUEST); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); input.readLine(); // Skip over the first line JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(input); List<Object> messageArray = (List<Object>) parser.parseArray(ArrayList.class, Object.class); String accessToken = messageArray.get(ACCESS_TOKEN_INDEX).toString(); token = new AccessToken(accessToken, null); } finally { socket.close(); } return token; } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Override public AccessToken refreshAccessToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); socket.setSoTimeout(READ_TIMEOUT_MS); AccessToken token; try { OutputStream os = socket.getOutputStream(); os.write(GET_AUTH_TOKEN_REQUEST_BYTES); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); input.readLine(); // Skip over the first line JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(input); List<Object> messageArray = (List<Object>) parser.parseArray(ArrayList.class, Object.class); String accessToken = messageArray.get(ACCESS_TOKEN_INDEX).toString(); token = new AccessToken(accessToken, null); } finally { socket.close(); } return token; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void refreshAccessToken() throws IOException{ final ServerSocket authSocket = new ServerSocket(0); Runnable serverTask = new Runnable() { @Override public void run() { try { Socket clientSocket = authSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String lines = input.readLine(); lines += '\n' + input.readLine(); assertEquals(lines, CloudShellCredentials.GET_AUTH_TOKEN_REQUEST); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); out.println("32\n[\"email\", \"project-id\", \"token\"]"); } catch (Exception reThrown) { throw new RuntimeException(reThrown); } } }; Thread serverThread = new Thread(serverTask); serverThread.start(); GoogleCredentials creds = new CloudShellCredentials(authSocket.getLocalPort()); assertEquals("token", creds.refreshAccessToken().getTokenValue()); } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void refreshAccessToken() throws IOException{ final ServerSocket authSocket = new ServerSocket(0); try { Runnable serverTask = new Runnable() { @Override public void run() { try { Socket clientSocket = authSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String lines = input.readLine(); lines += '\n' + input.readLine(); assertEquals(lines, CloudShellCredentials.GET_AUTH_TOKEN_REQUEST); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); out.println("32\n[\"email\", \"project-id\", \"token\"]"); } catch (Exception reThrown) { throw new RuntimeException(reThrown); } } }; Thread serverThread = new Thread(serverTask); serverThread.start(); GoogleCredentials creds = new CloudShellCredentials(authSocket.getLocalPort()); assertEquals("token", creds.refreshAccessToken().getTokenValue()); } finally { authSocket.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public AccessToken refreshAccessToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); socket.setSoTimeout(READ_TIMEOUT_MS); AccessToken token; try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(GET_AUTH_TOKEN_REQUEST); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); input.readLine(); // Skip over the first line JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(input); List<Object> messageArray = (List<Object>) parser.parseArray(ArrayList.class, Object.class); String accessToken = messageArray.get(ACCESS_TOKEN_INDEX).toString(); token = new AccessToken(accessToken, null); } finally { socket.close(); } return token; } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Override public AccessToken refreshAccessToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); socket.setSoTimeout(READ_TIMEOUT_MS); AccessToken token; try { OutputStream os = socket.getOutputStream(); os.write(GET_AUTH_TOKEN_REQUEST_BYTES); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); input.readLine(); // Skip over the first line JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(input); List<Object> messageArray = (List<Object>) parser.parseArray(ArrayList.class, Object.class); String accessToken = messageArray.get(ACCESS_TOKEN_INDEX).toString(); token = new AccessToken(accessToken, null); } finally { socket.close(); } return token; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addClient(CLIENT_ID, CLIENT_SECRET); transport.addRefreshToken(REFRESH_TOKEN, accessToken1); OAuth2Credentials userCredentials = new UserCredentials( CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null); // Use a fixed clock so tokens don't exire userCredentials.clock = new TestClock(); // Get a first token Map<String, List<String>> metadata = userCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, accessToken1); // Change server to a different token transport.addRefreshToken(REFRESH_TOKEN, accessToken2); // Confirm token being cached TestUtils.assertContainsBearerToken(metadata, accessToken1); // Refresh to force getting next token userCredentials.refresh(); metadata = userCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, accessToken2); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void refresh_refreshesToken() throws IOException { final String accessToken1 = "1/MkSJoj1xsli0AccessToken_NKPY2"; final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2"; MockTokenServerTransport transport = new MockTokenServerTransport(); transport.addClient(CLIENT_ID, CLIENT_SECRET); transport.addRefreshToken(REFRESH_TOKEN, accessToken1); OAuth2Credentials userCredentials = new UserCredentials( CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null); // Use a fixed clock so tokens don't exire userCredentials.clock = new TestClock(); // Get a first token Map<String, List<String>> metadata = userCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, accessToken1); assertEquals(1, transport.buildRequestCount--); // Change server to a different token transport.addRefreshToken(REFRESH_TOKEN, accessToken2); // Confirm token being cached TestUtils.assertContainsBearerToken(metadata, accessToken1); assertEquals(0, transport.buildRequestCount); // Refresh to force getting next token userCredentials.refresh(); metadata = userCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, accessToken2); assertEquals(1, transport.buildRequestCount--); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void readDictionaryFromFile(String file, ArrayList<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 FileReader(file)); String str; // int lineCount = 0; 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 47 #vulnerability type RESOURCE_LEAK
#fixed code public void readDictionaryFromFile(String file, ArrayList<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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void queueVariable(int level, Var var) { int i = varToIndex.get(var); indexQueue.add(i); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void queueVariable(int level, Var var) { Integer iVal = varXToIndex.get(var); if (iVal == null) iVal = varYToIndex.get(var); int i = iVal.intValue(); indexQueue.add(i); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void commonInitialization(Store store, IntVar[] list, int[] weights, int sum) { assert ( list.length == weights.length ) : "\nLength of two vectors different in Propagations"; this.store = store; this.b = 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 Propagations constraint is null"; if (weights[i] != 0) { if (list[i].singleton()) this.b -= list[i].value() * weights[i]; else if (parameters.get(list[i]) != null) { // variable ordered in the scope of the Propagations constraint. Integer coeff = parameters.get(list[i]); Integer sumOfCoeff = coeff + weights[i]; parameters.put(list[i], sumOfCoeff); } else parameters.put(list[i], weights[i]); } } this.x = new IntVar[parameters.size()]; this.a = new int[parameters.size()]; int i = 0; for (IntVar var : parameters.keySet()) { int coeff = parameters.get(var); if (coeff > 0) { this.x[i] = var; this.a[i] = coeff; i++; } } pos = i; for (IntVar var : parameters.keySet()) { int coeff = parameters.get(var); if (coeff < 0) { this.x[i] = var; this.a[i] = coeff; i++; } } this.l = x.length; this.I = new int[l]; checkForOverflow(); if (l <= 3) queueIndex = 0; else queueIndex = 1; } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code private void commonInitialization(Store store, IntVar[] list, int[] weights, int sum) { assert ( list.length == weights.length ) : "\nLength of two vectors different in Propagations"; this.store = store; this.b = sum; numberId = idNumber++; LinkedHashMap<IntVar, Integer> parameters = new LinkedHashMap<IntVar, Integer>(); for (int i = 0; i < list.length; i++) { assert (list[i] != null) : i + "-th element of list in Propagations constraint is null"; if (weights[i] != 0) { if (list[i].singleton()) this.b -= list[i].value() * weights[i]; else if (parameters.get(list[i]) != null) { // variable ordered in the scope of the Propagations constraint. Integer coeff = parameters.get(list[i]); Integer sumOfCoeff = coeff + weights[i]; parameters.put(list[i], sumOfCoeff); } else parameters.put(list[i], weights[i]); } } this.x = new IntVar[parameters.size()]; this.a = new int[parameters.size()]; int i = 0; for (IntVar var : parameters.keySet()) { int coeff = parameters.get(var); if (coeff > 0) { this.x[i] = var; this.a[i] = coeff; i++; } } pos = i; for (IntVar var : parameters.keySet()) { int coeff = parameters.get(var); if (coeff < 0) { this.x[i] = var; this.a[i] = coeff; i++; } } this.l = x.length; this.I = new int[l]; checkForOverflow(); if (l <= 3) queueIndex = 0; else queueIndex = 1; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(timeCategory); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void impose(Store store) { store.registerRemoveLevelListener(this); for (int i = 0; i < list.length; i++) { list[i].putModelConstraint(this, getConsistencyPruningEvent(list[i])); } store.addChanged(this); store.countConstraint(); this.store = store; if (debugAll) { for (Var var : list) System.out.println("Variable " + var); } // TO DO, adjust (even simplify) all internal data structures // to current domains of variables. // filter which ignores all tuples which already are not supports. boolean[] stillConflict = new boolean[tuplesFromConstructor.length]; int noConflicts = 0; int[][] supportCount = new int[list.length][]; int i = 0; for (int[] t : tuplesFromConstructor) { stillConflict[i] = true; int j = 0; if (debugAll) { System.out.print("conflict for analysis["); for (int val : t) System.out.print(val + " "); System.out.println("]"); } for (int val : t) { // if (debugAll) { // System.out.print("Checking " + x[j]); // System.out.print(" " + val); // System.out.println(Domain.domain.contains(x[j].dom(), val)); // } if (!list[j].dom().contains(val)) { // if (!Domain.domain.contains(x[j].dom(), val)) { stillConflict[i] = false; break; } j++; } if (stillConflict[i]) noConflicts++; if (debugAll) { if (!stillConflict[i]) { System.out.print("Not support ["); for (int val : t) System.out.print(val + " "); System.out.println("]"); } } i++; } if (debugAll) { System.out.println("No. still conflicts " + noConflicts); } int[][] temp4Shrinking = new int[noConflicts][]; i = 0; int k = 0; for (int[] t : tuplesFromConstructor) { if (stillConflict[k]) { temp4Shrinking[i] = t; i++; if (debugAll) { System.out.print("Still support ["); for (int val : t) System.out.print(val + " "); System.out.println("]"); } } k++; } // Only still conflicts are kept. tuplesFromConstructor = temp4Shrinking; numberTuples = tuplesFromConstructor.length; // TO DO, just store parameters for later use in impose // function, move all code below to impose function. this.tuples = new int[list.length][][][]; this.values = new int[list.length][]; lastofsequence = new int[list.length][][]; for (i = 0; i < list.length; i++) { HashMap<Integer, Integer> val = new HashMap<Integer, Integer>(); for (int[] t : tuplesFromConstructor) { Integer value = t[i]; Integer key = val.get(value); if (key == null) val.put(value, 1); else val.put(value, key + 1); } if (debugAll) System.out.println("values " + val.keySet()); PriorityQueue<Integer> sortedVal = new PriorityQueue<Integer>(val.keySet()); if (debugAll) System.out.println("Sorted val size " + sortedVal.size()); values[i] = new int[sortedVal.size()]; supportCount[i] = new int[sortedVal.size()]; this.tuples[i] = new int[sortedVal.size()][][]; if (debugAll) System.out.println("values length " + values[i].length); for (int j = 0; j < values[i].length; j++) { if (debugAll) System.out.println("sortedVal " + sortedVal); values[i][j] = sortedVal.poll(); supportCount[i][j] = val.get(Integer.valueOf(values[i][j])); this.tuples[i][j] = new int[supportCount[i][j]][]; } // int m = 0; for (int[] t : tuplesFromConstructor) { int value = t[i]; int position = findPosition(value, values[i]); this.tuples[i][position][--supportCount[i][position]] = t; // m++; } // @todo, check & improve sorting functionality (possibly reuse existing sorting functionality). for (int j = 0; j < tuples[i].length; j++) TupleUtils.sortTuplesWithin(tuples[i][j]); lastofsequence[i] = new int[tuples[i].length][]; // compute lastOfSequence for each i,j and tuple. // i - for each variable for (int j = 0; j < tuples[i].length; j++) { // for each value lastofsequence[i][j] = new int[tuples[i][j].length]; for (int l = 0; l < tuples[i][j].length; l++) // for each tuple lastofsequence[i][j][l] = computeLastOfSequence(tuples[i][j], i, l); } } tuplesFromConstructor = null; store.raiseLevelBeforeConsistency = true; } #location 156 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void impose(Store store) { super.impose(store); store.registerRemoveLevelListener(this); this.store = store; if (debugAll) { for (Var var : list) System.out.println("Variable " + var); } // TO DO, adjust (even simplify) all internal data structures // to current domains of variables. // filter which ignores all tuples which already are not supports. boolean[] stillConflict = new boolean[tuplesFromConstructor.length]; int noConflicts = 0; int[][] supportCount = new int[list.length][]; int i = 0; for (int[] t : tuplesFromConstructor) { stillConflict[i] = true; int j = 0; if (debugAll) { System.out.print("conflict for analysis["); for (int val : t) System.out.print(val + " "); System.out.println("]"); } for (int val : t) { // if (debugAll) { // System.out.print("Checking " + x[j]); // System.out.print(" " + val); // System.out.println(Domain.domain.contains(x[j].dom(), val)); // } if (!list[j].dom().contains(val)) { // if (!Domain.domain.contains(x[j].dom(), val)) { stillConflict[i] = false; break; } j++; } if (stillConflict[i]) noConflicts++; if (debugAll) { if (!stillConflict[i]) { System.out.print("Not support ["); for (int val : t) System.out.print(val + " "); System.out.println("]"); } } i++; } if (debugAll) { System.out.println("No. still conflicts " + noConflicts); } int[][] temp4Shrinking = new int[noConflicts][]; i = 0; int k = 0; for (int[] t : tuplesFromConstructor) { if (stillConflict[k]) { temp4Shrinking[i] = t; i++; if (debugAll) { System.out.print("Still support ["); for (int val : t) System.out.print(val + " "); System.out.println("]"); } } k++; } // Only still conflicts are kept. tuplesFromConstructor = temp4Shrinking; numberTuples = tuplesFromConstructor.length; // TO DO, just store parameters for later use in impose // function, move all code below to impose function. this.tuples = new int[list.length][][][]; this.values = new int[list.length][]; lastofsequence = new int[list.length][][]; for (i = 0; i < list.length; i++) { HashMap<Integer, Integer> val = new HashMap<Integer, Integer>(); for (int[] t : tuplesFromConstructor) { Integer value = t[i]; Integer key = val.get(value); if (key == null) val.put(value, 1); else val.put(value, key + 1); } if (debugAll) System.out.println("values " + val.keySet()); PriorityQueue<Integer> sortedVal = new PriorityQueue<Integer>(val.keySet()); if (debugAll) System.out.println("Sorted val size " + sortedVal.size()); values[i] = new int[sortedVal.size()]; supportCount[i] = new int[sortedVal.size()]; this.tuples[i] = new int[sortedVal.size()][][]; if (debugAll) System.out.println("values length " + values[i].length); for (int j = 0; j < values[i].length; j++) { if (debugAll) System.out.println("sortedVal " + sortedVal); values[i][j] = sortedVal.poll(); supportCount[i][j] = val.get(Integer.valueOf(values[i][j])); this.tuples[i][j] = new int[supportCount[i][j]][]; } // int m = 0; for (int[] t : tuplesFromConstructor) { int value = t[i]; int position = findPosition(value, values[i]); this.tuples[i][position][--supportCount[i][position]] = t; // m++; } // @todo, check & improve sorting functionality (possibly reuse existing sorting functionality). for (int j = 0; j < tuples[i].length; j++) TupleUtils.sortTuplesWithin(tuples[i][j]); lastofsequence[i] = new int[tuples[i].length][]; // compute lastOfSequence for each i,j and tuple. // i - for each variable for (int j = 0; j < tuples[i].length; j++) { // for each value lastofsequence[i][j] = new int[tuples[i][j].length]; for (int l = 0; l < tuples[i][j].length; l++) // for each tuple lastofsequence[i][j][l] = computeLastOfSequence(tuples[i][j], i, l); } } tuplesFromConstructor = null; store.raiseLevelBeforeConsistency = true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void uppendToLatexFile(String desc, String fileName) { try { System.out.println("save latex file " + fileName); OutputStreamWriter char_output = new OutputStreamWriter( new FileOutputStream(fileName), Charset.forName("UTF-8").newEncoder() ); BufferedWriter fs; fs = new BufferedWriter(char_output); fs.append(this.toLatex(desc)); fs.flush(); fs.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public void uppendToLatexFile(String desc, String fileName) { try(OutputStreamWriter char_output = new OutputStreamWriter(new FileOutputStream(fileName), Charset.forName("UTF-8").newEncoder()); BufferedWriter fs = new BufferedWriter(char_output)) { System.out.println("save latex file " + fileName); fs.append(this.toLatex(desc)); fs.flush(); fs.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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]; } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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()]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void queueVariable(int level, Var var) { Integer iVal = varXToIndex.get(var); if (iVal == null) iVal = varYToIndex.get(var); int i = iVal.intValue(); indexQueue.add(i); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void queueVariable(int level, Var var) { ArrayList<Integer> iValX = varXToIndex.get(var); ArrayList<Integer> iValY = varYToIndex.get(var); if (iValX != null) for (int i : iValX) indexQueue.add(i); if (iValY != null) for (int i : iValY) indexQueue.add(i); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @Parameterized.Parameters public static Collection<String> parametricTest() throws IOException { return fileReader(timeCategory); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void commonInitialization(IntVar[] list, int[] weights, int sum) { queueIndex = 4; assert (list.length == weights.length) : "\nLength of two vectors different in SumWeightDom"; 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 SumWeightDom constraint is null"; if (weights[i] == 0) continue; 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]); } 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 38 #vulnerability type NULL_DEREFERENCE
#fixed code private void commonInitialization(IntVar[] list, int[] weights, int sum) { queueIndex = 4; assert (list.length == weights.length) : "\nLength of two vectors different in SumWeightDom"; 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 SumWeightDom constraint is null"; if (weights[i] == 0) continue; 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]); } 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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void model() { String lines[] = new String[100]; /* read from file args[0] or qcp.txt */ try { BufferedReader in = new BufferedReader(new FileReader(filename)); String str; while ((str = in.readLine()) != null) { lines[n] = str; n++; } in.close(); } catch (FileNotFoundException e) { System.err.println("You need to run this program in a directory that contains the required file."); System.err.println("I can not find file " + filename); System.exit(-1); } catch (IOException e) { System.err.println("Something is wrong with file" + filename); } n = n - 1; /* Creating constraint store */ int numbers[][] = new int[n][n]; // Transforms strings into ints for (int i = 1; i < n + 1; i++) { Pattern pat = Pattern.compile(" "); String[] result = pat.split(lines[i]); int current = 0; for (int j = 0; j < result.length; j++) try { int currentNo = Integer.parseInt(result[j]); numbers[i - 1][current++] = currentNo; } catch (Exception ex) { } } store = new Store(); store.queueNo = 4; vars = new ArrayList<IntVar>(); // Get problem size n from second program argument. IntVar[][] x = new IntVar[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (numbers[i][j] == -1) { x[i][j] = new IntVar(store, "x" + i + "_" + j, 0, n - 1); vars.add(x[i][j]); } else x[i][j] = new IntVar(store, "x" + i + "_" + j, numbers[i][j], numbers[i][j]); vars.add(x[i][j]); } // Create variables and state constraints. for (int i = 0; i < n; i++) { Constraint cx = new Alldistinct(x[i]); store.impose(cx); shavingConstraints.add(cx); IntVar[] y = new IntVar[n]; for (int j = 0; j < n; j++) y[j] = x[j][i]; Constraint cy = new Alldistinct(y); store.impose(cy); shavingConstraints.add(cy); } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void model() { String lines[] = new String[100]; /* read from file args[0] or qcp.txt */ try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8")); String str; while ((str = in.readLine()) != null) { lines[n] = str; n++; } in.close(); } catch (FileNotFoundException e) { System.err.println("You need to run this program in a directory that contains the required file."); System.err.println("I can not find file " + filename); System.exit(-1); } catch (IOException e) { System.err.println("Something is wrong with file" + filename); } n = n - 1; /* Creating constraint store */ int numbers[][] = new int[n][n]; // Transforms strings into ints for (int i = 1; i < n + 1; i++) { Pattern pat = Pattern.compile(" "); String[] result = pat.split(lines[i]); int current = 0; for (int j = 0; j < result.length; j++) try { int currentNo = Integer.parseInt(result[j]); numbers[i - 1][current++] = currentNo; } catch (Exception ex) { } } store = new Store(); store.queueNo = 4; vars = new ArrayList<IntVar>(); // Get problem size n from second program argument. IntVar[][] x = new IntVar[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (numbers[i][j] == -1) { x[i][j] = new IntVar(store, "x" + i + "_" + j, 0, n - 1); vars.add(x[i][j]); } else x[i][j] = new IntVar(store, "x" + i + "_" + j, numbers[i][j], numbers[i][j]); vars.add(x[i][j]); } // Create variables and state constraints. for (int i = 0; i < n; i++) { Constraint cx = new Alldistinct(x[i]); store.impose(cx); shavingConstraints.add(cx); IntVar[] y = new IntVar[n]; for (int j = 0; j < n; j++) y[j] = x[j][i]; Constraint cy = new Alldistinct(y); store.impose(cy); shavingConstraints.add(cy); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.