output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new File(file)).register(); DefaultExports.initialize(); server = new Server(socket); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); server.setThreadPool(pool); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); }
#vulnerable code public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { String[] args = agentArgument.split(":"); if (args.length < 2 || args.length > 3) { System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); System.exit(1); } int port; InetSocketAddress socket; String file; if (args.length == 3) { port = Integer.parseInt(args[1]); socket = new InetSocketAddress(args[0], port); file = args[2]; } else { port = Integer.parseInt(args[0]); socket = new InetSocketAddress(port); file = args[1]; } new JmxCollector(new FileReader(file)).register(); DefaultExports.initialize(); server = new Server(socket); QueuedThreadPool pool = new QueuedThreadPool(); pool.setDaemon(true); server.setThreadPool(pool); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics"); server.start(); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @BeforeClass public static void beforeClass() { File[] traceFiles = customFileLog("").listFiles(); if (traceFiles == null) { return; } for (File file : traceFiles) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { continue; } FileUtils.deleteQuietly(file); } }
#vulnerable code @BeforeClass public static void beforeClass() { for (File file : customFileLog("").listFiles()) { if (file.getPath().contains("tracer-self.log") || file.getPath().contains("sync.log") || file.getPath().contains("rpc-profile.log") || file.getPath().contains("middleware_error.log")) { continue; } FileUtils.deleteQuietly(file); } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected Map<String, Object> customSettingsFlat() { return customSettingsFlat(IlpOverHttpLinkSettings.AuthType.JWT_HS_256, IlpOverHttpLinkSettings.AuthType.JWT_HS_256); }
#vulnerable code protected Map<String, Object> customSettingsFlat() { return ImmutableMap.<String, Object>builder() .put(HTTP_INCOMING_AUTH_TYPE, IlpOverHttpLinkSettings.AuthType.JWT_HS_256.name()) .put(HTTP_INCOMING_TOKEN_ISSUER, "https://incoming-issuer.example.com/") .put(HTTP_INCOMING_SHARED_SECRET, "incoming-credential") .put(HTTP_INCOMING_TOKEN_AUDIENCE, "https://incoming-audience.example.com/") .put(HTTP_OUTGOING_AUTH_TYPE, IlpOverHttpLinkSettings.AuthType.SIMPLE.name()) .put(HTTP_OUTGOING_TOKEN_SUBJECT, "outgoing-subject") .put(HTTP_OUTGOING_SHARED_SECRET, "outgoing-credential") .put(HTTP_OUTGOING_TOKEN_ISSUER, "https://outgoing-issuer.example.com/") .put(HTTP_OUTGOING_TOKEN_AUDIENCE, "https://outgoing-audience.example.com/") .put(HTTP_OUTGOING_TOKEN_EXPIRY, Duration.ofDays(1).toString()) .put(HTTP_OUTGOING_URL, "https://outgoing.example.com") .build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Node<S> next(){ if (next != null){ Node<S> e = next; next = nextUnvisited(); return e; } else { return nextUnvisited(); } }
#vulnerable code public Node<S> next() { // Take the next node from the stack. Node<S> current = popUnvisited(); // Take the associated state S currentState = current.transition().to(); // Explore the adjacent neighbors for(Transition<S> successor : this.successors.from(currentState)){ // If the neighbor is still unexplored if (!this.visited.containsKey(successor.to())){ // Create the associated neighbor Node<S> successorNode = factory.node(current, successor); this.stack.push(successorNode); } } this.visited.put(currentState, current); return current; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public GraphEdge<V,E> connect(V v1, V v2, E value){ // Check non-null arguments if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); // Ensure that the vertices are in the graph add(v1); add(v2); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> reversedEdge = new GraphEdge<V, E>(v2, v1, value); // Add edges to the graph connected.get(v1).add(edge); connected.get(v2).add(reversedEdge); return edge; }
#vulnerable code public GraphEdge<V,E> connect(V v1, V v2, E value){ //check input if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> edgeReverse = new GraphEdge<V, E>(v2, v1, value); //add edges to the graph (if not present before) connected.get(v1).add(edge); connected.get(v2).add(edgeReverse); return edge; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() { String[] testMaze = { "XX@XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "XX XXXXXXXXXXXXX XXXXXXXXXXX", "XX XXXXXXXXXX XXX XX XXXX", "XXXXX XXXXXX XXX XX XXX XXXX", "XXX XX XXXXXX XX XXX XX XX XXXX", "XXX XXXXX XXXXXX XXXXXX XXXX", "XXXXXXX XXXXXX XXXX", "XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX", "XXXXXXXXXX XX XXXXX XXXX", "XXXXXXXXXX XXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXX XXXX", "XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX", "XXXXXX XXXX XX XXXX", "XXXXXX XXXXXXXXXXXX XX XXXX", "XXXXXX XXO XXXXXX XXXX XXXXXXX", "XXXXXX XXXXX XXX XX", "XXXXXX XXXXXXX XXXXXXXXXXX XXXXX", "XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX", "XXXXXX XXXXXXXXXXXXXX"}; StringMaze maze = new StringMaze(testMaze); // Valid cells assertTrue(maze.validLocation(new Point(2,1))); assertTrue(maze.validLocation(new Point(2,0))); assertTrue(maze.validLocation(new Point(4,5))); // Invalid cells assertTrue(!maze.validLocation(new Point(0,0))); assertTrue(!maze.validLocation(new Point(1,1))); assertTrue(!maze.validLocation(new Point(12,5))); // Initial loc assertEquals(maze.getInitialLoc(), new Point(2, 0)); assertEquals(maze.getGoalLoc(), new Point(9, 15)); // Print valid moves from initial and goal System.out.println(maze.validLocationsFrom(maze.getInitialLoc())); System.out.println(maze.validLocationsFrom(maze.getGoalLoc())); System.out.println(maze.validLocationsFrom(new Point(14, 3))); }
#vulnerable code @Test public void test() { String[] testMaze = { "XX@XXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "XX XXXXXXXXXXXXX XXXXXXXXXXX", "XX XXXXXXXXXX XXX XX XXXX", "XXXXX XXXXXX XXX XX XXX XXXX", "XXX XX XXXXXX XX XXX XX XX XXXX", "XXX XXXXX XXXXXX XXXXXX XXXX", "XXXXXXX XXXXXX XXXX", "XXXXXXXXXX XXXXX XXXXXXXXXXXXXXX", "XXXXXXXXXX XX XXXXX XXXX", "XXXXXXXXXX XXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXXXXXXXX XXXX XXXX", "XXXXXXXXXXX XXXX XXXX", "XXXXXXXXXXXXXXXXXXXXXXXX XX XXXX", "XXXXXX XXXX XX XXXX", "XXXXXX XXXXXXXXXXXX XX XXXX", "XXXXXX XXO XXXXXX XXXX XXXXXXX", "XXXXXX XXXXX XXX XX", "XXXXXX XXXXXXX XXXXXXXXXXX XXXXX", "XXXXXX XXXXXXX XXXXXXXXXXXXXXXXX", "XXXXXX XXXXXXXXXXXXXX"}; StringMaze maze = new StringMaze(testMaze); // Valid cells assertTrue(maze.getMaze()[1][2]); assertTrue(maze.getMaze()[0][2]); assertTrue(maze.getMaze()[5][4]); // Invalid cells assertFalse(maze.getMaze()[0][0]); assertFalse(maze.getMaze()[1][1]); assertFalse(maze.getMaze()[5][12]); // Initial loc assertEquals(maze.getInitialLoc(), new Point(2, 0)); assertEquals(maze.getGoalLoc(), new Point(9, 15)); // Print valid moves from initial and goal System.out.println(maze.validLocationsFrom(maze.getInitialLoc())); System.out.println(maze.validLocationsFrom(maze.getGoalLoc())); System.out.println(maze.validLocationsFrom(new Point(14, 3))); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public GraphEdge<V,E> connect(V v1, V v2, E value){ // Check non-null arguments if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); // Ensure that the vertices are in the graph add(v1); add(v2); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> reversedEdge = new GraphEdge<V, E>(v2, v1, value); // Add edges to the graph connected.get(v1).add(edge); connected.get(v2).add(reversedEdge); return edge; }
#vulnerable code public GraphEdge<V,E> connect(V v1, V v2, E value){ //check input if(v1 == null || v2 == null) throw new IllegalArgumentException("Vertices cannot be null"); GraphEdge<V,E> edge = new GraphEdge<V, E>(v1, v2, value); GraphEdge<V,E> edgeReverse = new GraphEdge<V, E>(v2, v1, value); //add edges to the graph (if not present before) connected.get(v1).add(edge); connected.get(v2).add(edgeReverse); return edge; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void benchmark() throws InterruptedException { Benchmark bench = new Benchmark(); // Hipster-Dijkstra bench.add("Hipster-Dijkstra", new Algorithm() { AStar<Point> it; Maze2D maze; public void initialize(Maze2D maze) { it= AlgorithmIteratorFromMazeCreator.astar(maze, false); this.maze = maze; } public Result evaluate() { return MazeSearch.executeIteratorSearch(it, maze); } }); // JUNG-Dijkstra bench.add("JUNG-Dijkstra", new Algorithm() { Maze2D maze;DirectedGraph<Point, JungEdge<Point>> graph; public void initialize(Maze2D maze) { this.maze = maze; this.graph = JungDirectedGraphFromMazeCreator.create(maze); } public Result evaluate() { return MazeSearch.executeJungSearch(graph, maze); } }); int index = 0; for(String algName : bench.algorithms.keySet()){ System.out.println((++index) + " = " + algName); } for (int i = 10; i < 300; i += 10) { Maze2D maze = Maze2D.empty(i); // Test over an empty maze Map<String, Benchmark.Score> results = bench.run(maze); // Check results and print scores. We take JUNG as baseline Benchmark.Score jungScore = results.get("JUNG-Dijkstra"); String scores = ""; for(String algName : bench.algorithms.keySet()){ Benchmark.Score score = results.get(algName); assertEquals(jungScore.result.getCost(),score.result.getCost(), 0.0001); scores += score.time + " ms\t"; } System.out.println(scores); } }
#vulnerable code @Test public void benchmark() throws InterruptedException { System.out.println("Maze | Hipster-Dijkstra (ms) | JUNG-Dijkstra (ms)"); System.out.println("-------------------------------------------------"); final int times = 5; for (int i = 10; i < 300; i += 10) { Maze2D maze = Maze2D.random(i, 0.9); // Repeat 5 times //Double mean1 = 0d, mean2 = 0d; double min2 = Double.MAX_VALUE, min1 = Double.MAX_VALUE; DirectedGraph<Point, JungEdge<Point>> graph = JungDirectedGraphFromMazeCreator.create(maze); for (int j = 0; j < times; j++) { //AStar<Point> it = AStarIteratorFromMazeCreator.create(maze, false); AStar<Point> it = AlgorithmIteratorFromMazeCreator.astar(maze, false); Stopwatch w1 = new Stopwatch().start(); MazeSearch.Result resultJung = MazeSearch.executeJungSearch(graph, maze); //In case there is no possible result in the random maze if(resultJung.equals(MazeSearch.Result.NO_RESULT)){ maze = Maze2D.random(i, 0.9); graph = JungDirectedGraphFromMazeCreator.create(maze); j--; continue; } long result1 = w1.stop().elapsed(TimeUnit.MILLISECONDS); if (result1 < min1) { min1 = result1; } Stopwatch w2 = new Stopwatch().start(); MazeSearch.Result resultIterator = MazeSearch.executeIteratorSearch(it, maze); long result2 = w2.stop().elapsed(TimeUnit.MILLISECONDS); if (result2 < min2) { min2 = result2; } assertEquals(resultIterator.getCost(), resultJung.getCost(), 0.001); } System.out.println(String.format("%d \t\t %.5g \t\t %.5g", i, min2, min1)); } } #location 34 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRestartAuditorBookieAfterCrashing() throws Exception { BookieServer auditor = verifyAuditor(); shudownBookie(auditor); // restarting Bookie with same configurations. int indexOfDownBookie = bs.indexOf(auditor); ServerConfiguration serverConfiguration = bsConfs .get(indexOfDownBookie); bs.remove(indexOfDownBookie); bsConfs.remove(indexOfDownBookie); tmpDirs.remove(indexOfDownBookie); startBookie(serverConfiguration); // starting corresponding auditor elector String addr = StringUtils.addrToString(auditor.getLocalAddress()); LOG.debug("Performing Auditor Election:" + addr); auditorElectors.get(addr).doElection(); // waiting for new auditor to come BookieServer newAuditor = waitForNewAuditor(auditor); Assert.assertNotSame( "Auditor re-election is not happened for auditor failure!", auditor, newAuditor); Assert.assertFalse("No relection after old auditor rejoins", auditor .getLocalAddress().getPort() == newAuditor.getLocalAddress() .getPort()); }
#vulnerable code @Test public void testRestartAuditorBookieAfterCrashing() throws Exception { BookieServer auditor = verifyAuditor(); shudownBookie(auditor); // restarting Bookie with same configurations. int indexOfDownBookie = bs.indexOf(auditor); ServerConfiguration serverConfiguration = bsConfs .get(indexOfDownBookie); bs.remove(indexOfDownBookie); bsConfs.remove(indexOfDownBookie); tmpDirs.remove(indexOfDownBookie); startBookie(serverConfiguration); // starting corresponding auditor elector StringBuilder sb = new StringBuilder(); StringUtils.addrToString(sb, auditor.getLocalAddress()); LOG.debug("Performing Auditor Election:" + sb.toString()); auditorElectors.get(sb.toString()).doElection(); // waiting for new auditor to come BookieServer newAuditor = waitForNewAuditor(auditor); Assert.assertNotSame( "Auditor re-election is not happened for auditor failure!", auditor, newAuditor); Assert.assertFalse("No relection after old auditor rejoins", auditor .getLocalAddress().getPort() == newAuditor.getLocalAddress() .getPort()); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleSubscribeMessage(PubSubResponse response) { if (logger.isDebugEnabled()) { logger.debug("Handling a Subscribe message in response: {}, topic: {}, subscriberId: {}", new Object[] { response, getOrigSubData().topic.toStringUtf8(), getOrigSubData().subscriberId.toStringUtf8() }); } Message message = response.getMessage(); synchronized (this) { // Consume the message asynchronously that the client is subscribed // to. Do this only if delivery for the subscription has started and // a MessageHandler has been registered for the TopicSubscriber. if (messageHandler != null) { asyncMessageConsume(message); } else { // MessageHandler has not yet been registered so queue up these // messages for the Topic Subscription. Make the initial lazy // creation of the message queue thread safe just so we don't // run into a race condition where two simultaneous threads process // a received message and both try to create a new instance of // the message queue. Performance overhead should be okay // because the delivery of the topic has not even started yet // so these messages are not consumed and just buffered up here. if (subscribeMsgQueue == null) subscribeMsgQueue = new LinkedList<Message>(); if (logger.isDebugEnabled()) logger .debug("Message has arrived but Subscribe channel does not have a registered MessageHandler yet so queueing up the message: " + message); subscribeMsgQueue.add(message); } } }
#vulnerable code public void handleSubscribeMessage(PubSubResponse response) { if (logger.isDebugEnabled()) logger.debug("Handling a Subscribe message in response: " + response + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); Message message = response.getMessage(); synchronized (this) { // Consume the message asynchronously that the client is subscribed // to. Do this only if delivery for the subscription has started and // a MessageHandler has been registered for the TopicSubscriber. if (messageHandler != null) { asyncMessageConsume(message); } else { // MessageHandler has not yet been registered so queue up these // messages for the Topic Subscription. Make the initial lazy // creation of the message queue thread safe just so we don't // run into a race condition where two simultaneous threads process // a received message and both try to create a new instance of // the message queue. Performance overhead should be okay // because the delivery of the topic has not even started yet // so these messages are not consumed and just buffered up here. if (subscribeMsgQueue == null) subscribeMsgQueue = new LinkedList<Message>(); if (logger.isDebugEnabled()) logger .debug("Message has arrived but Subscribe channel does not have a registered MessageHandler yet so queueing up the message: " + message); subscribeMsgQueue.add(message); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { closeInternal(true); }
#vulnerable code public void close() { synchronized (this) { state = ConnectionState.DISCONNECTED; } if (channel != null) { channel.close().awaitUninterruptibly(); } if (readTimeoutTimer != null) { readTimeoutTimer.stop(); readTimeoutTimer = null; } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (running) { synchronized (this) { try { wait(gcWaitTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); continue; } } // Dependency check. if (null == zk) { continue; } // Extract all of the ledger ID's that comprise all of the entry logs // (except for the current new one which is still being written to). try { entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); } catch (IOException ie) { LOG.warn("Exception when extracting entry log meta from entry logs : ", ie); } // gc inactive/deleted ledgers doGcLedgers(); // gc entry logs doGcEntryLogs(); long curTime = System.currentTimeMillis(); if (enableMajorCompaction && curTime - lastMajorCompactionTime > majorCompactionInterval) { // enter major compaction LOG.info("Enter major compaction"); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = System.currentTimeMillis(); // also move minor compaction time lastMinorCompactionTime = lastMajorCompactionTime; continue; } if (enableMinorCompaction && curTime - lastMinorCompactionTime > minorCompactionInterval) { // enter minor compaction LOG.info("Enter minor compaction"); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = System.currentTimeMillis(); } } }
#vulnerable code @Override public void run() { while (running) { synchronized (this) { try { wait(gcWaitTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); continue; } } // Dependency check. if (null == zk) { continue; } // Extract all of the ledger ID's that comprise all of the entry logs // (except for the current new one which is still being written to). try { entryLogMetaMap = entryLogger.extractMetaFromEntryLogs(entryLogMetaMap); } catch (IOException ie) { LOG.warn("Exception when extracting entry log meta from entry logs : ", ie); } // gc inactive/deleted ledgers doGcLedgers(); // gc entry logs doGcEntryLogs(); long curTime = System.currentTimeMillis(); if (enableMajorCompaction && curTime - lastMajorCompactionTime > majorCompactionInterval) { // enter major compaction LOG.info("Enter major compaction"); doCompactEntryLogs(majorCompactionThreshold); lastMajorCompactionTime = System.currentTimeMillis(); // also move minor compaction time lastMinorCompactionTime = lastMajorCompactionTime; continue; } if (enableMinorCompaction && curTime - lastMinorCompactionTime > minorCompactionInterval) { // enter minor compaction LOG.info("Enter minor compaction"); doCompactEntryLogs(minorCompactionThreshold); lastMinorCompactionTime = System.currentTimeMillis(); } } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public byte[] readMasterKey(long ledgerId) throws IOException, BookieException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledgerId); if (fi == null) { File lf = findIndexFile(ledgerId); if (lf == null) { throw new Bookie.NoLedgerException(ledgerId); } evictFileInfoIfNecessary(); fi = new FileInfo(lf, null); byte[] key = fi.getMasterKey(); fileInfoCache.put(ledgerId, fi); openLedgers.add(ledgerId); return key; } return fi.getMasterKey(); } }
#vulnerable code @Override public byte[] readMasterKey(long ledgerId) throws IOException, BookieException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledgerId); if (fi == null) { File lf = findIndexFile(ledgerId); if (lf == null) { throw new Bookie.NoLedgerException(ledgerId); } if (openLedgers.size() > openFileLimit) { fileInfoCache.remove(openLedgers.removeFirst()).close(); } fi = new FileInfo(lf, null); byte[] key = fi.getMasterKey(); fileInfoCache.put(ledgerId, fi); openLedgers.add(ledgerId); return key; } return fi.getMasterKey(); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void writeIndexFileForLedger(File indexDir, long ledgerId, byte[] masterKey) throws Exception { File fn = new File(indexDir, LedgerCache.getLedgerName(ledgerId)); fn.getParentFile().mkdirs(); FileInfo fi = new FileInfo(fn, masterKey); // force creation of index file fi.write(new ByteBuffer[]{ ByteBuffer.allocate(0) }, 0); fi.close(); }
#vulnerable code private void writeIndexFileForLedger(File indexDir, long ledgerId, byte[] masterKey) throws Exception { File fn = new File(indexDir, LedgerCache.getLedgerName(ledgerId)); fn.getParentFile().mkdirs(); FileInfo fi = new FileInfo(fn); fi.writeMasterKey(masterKey); fi.close(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.info("Disconnected from bookie: " + addr); errorOutOutstandingEntries(); channel.close(); synchronized (this) { state = ConnectionState.DISCONNECTED; } // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. }
#vulnerable code @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { LOG.info("Disconnected from bookie: " + addr); errorOutOutstandingEntries(); channel.close(); state = ConnectionState.DISCONNECTED; // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteSyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); } lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); Integer origEntry = origbb.getInt(); ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteSyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); lh.addEntry(entry.array()); } lh.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); Integer origEntry = origbb.getInt(); ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout=60000) public void testLastConfirmedAdd() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test(timeout=60000) public void testLastConfirmedAdd() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 48 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close() { closeInternal(true); }
#vulnerable code public void close() { synchronized (this) { state = ConnectionState.DISCONNECTED; } if (channel != null) { channel.close().awaitUninterruptibly(); } if (readTimeoutTimer != null) { readTimeoutTimer.stop(); readTimeoutTimer = null; } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj sync = (SyncObj) ctx; sync.setLedgerEntries(seq); sync.setReturnCode(rc); synchronized (sync) { sync.value = true; sync.notify(); } }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public StatsLogger getStatsLogger(String name) { initIfNecessary(); return new CodahaleStatsLogger(getMetrics(), name); }
#vulnerable code @Override public StatsLogger getStatsLogger(String name) { initIfNecessary(); return new CodahaleStatsLogger(metrics, name); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code FileInfo getFileInfo(Long ledger, byte masterKey[]) throws IOException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledger); if (fi == null) { File lf = findIndexFile(ledger); if (lf == null) { if (masterKey == null) { throw new Bookie.NoLedgerException(ledger); } File dir = pickDirs(ledgerDirectories); String ledgerName = getLedgerName(ledger); lf = new File(dir, ledgerName); // A new ledger index file has been created for this Bookie. // Add this new ledger to the set of active ledgers. if (LOG.isDebugEnabled()) { LOG.debug("New ledger index file created for ledgerId: " + ledger); } activeLedgerManager.addActiveLedger(ledger, true); } evictFileInfoIfNecessary(); fi = new FileInfo(lf, masterKey); fileInfoCache.put(ledger, fi); openLedgers.add(ledger); } if (fi != null) { fi.use(); } return fi; } }
#vulnerable code FileInfo getFileInfo(Long ledger, byte masterKey[]) throws IOException { synchronized(fileInfoCache) { FileInfo fi = fileInfoCache.get(ledger); if (fi == null) { File lf = findIndexFile(ledger); if (lf == null) { if (masterKey == null) { throw new Bookie.NoLedgerException(ledger); } File dir = pickDirs(ledgerDirectories); String ledgerName = getLedgerName(ledger); lf = new File(dir, ledgerName); // A new ledger index file has been created for this Bookie. // Add this new ledger to the set of active ledgers. if (LOG.isDebugEnabled()) { LOG.debug("New ledger index file created for ledgerId: " + ledger); } activeLedgerManager.addActiveLedger(ledger, true); } if (openLedgers.size() > openFileLimit) { fileInfoCache.remove(openLedgers.removeFirst()).close(); } fi = new FileInfo(lf, masterKey); fileInfoCache.put(ledger, fi); openLedgers.add(ledger); } if (fi != null) { fi.use(); } return fi; } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void connectIfNeededAndDoOp(GenericCallback<Void> op) { boolean doOpNow; synchronized (this) { if (channel != null && state == ConnectionState.CONNECTED) { doOpNow = true; } else { // if reached here, channel is either null (first connection // attempt), // or the channel is disconnected doOpNow = false; // connection attempt is still in progress, queue up this // op. Op will be executed when connection attempt either // fails // or // succeeds pendingOps.add(op); connect(); } } if (doOpNow) { op.operationComplete(BKException.Code.OK, null); } }
#vulnerable code void connectIfNeededAndDoOp(GenericCallback<Void> op) { boolean doOpNow; // common case without lock first if (channel != null && state == ConnectionState.CONNECTED) { doOpNow = true; } else { synchronized (this) { // check again under lock if (channel != null && state == ConnectionState.CONNECTED) { doOpNow = true; } else { // if reached here, channel is either null (first connection // attempt), // or the channel is disconnected doOpNow = false; // connection attempt is still in progress, queue up this // op. Op will be executed when connection attempt either // fails // or // succeeds pendingOps.add(op); connect(); } } } if (doOpNow) { op.operationComplete(BKException.Code.OK, null); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSimpleBookieLedgerMapping() throws Exception { for (int i = 0; i < numberOfLedgers; i++) { createAndAddEntriesToLedger().close(); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 3, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3, ledgers.size()); for (Long ledgerId : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerId)); } } }
#vulnerable code @Test public void testSimpleBookieLedgerMapping() throws Exception { LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory .newLedgerManagerFactory(baseConf, zkc); LedgerManager ledgerManager = newLedgerManagerFactory .newLedgerManager(); List<Long> ledgerList = new ArrayList<Long>(3); LedgerHandle lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex .getBookieToLedgerIndex(); assertEquals("Missed few bookies in the bookie-ledger mapping!", 3, bookieToLedgerIndex.size()); Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values(); for (Set<Long> ledgers : bk2ledgerEntry) { assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3, ledgers.size()); for (Long ledgerId : ledgers) { assertTrue("Unknown ledger-bookie mapping", ledgerList .contains(ledgerId)); } } } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setMessageHandler(MessageHandler messageHandler) { if (logger.isDebugEnabled()) { logger.debug("Setting the messageHandler for topic: {}, subscriberId: {}", getOrigSubData().topic.toStringUtf8(), getOrigSubData().subscriberId.toStringUtf8()); } synchronized (this) { this.messageHandler = messageHandler; // Once the MessageHandler is registered, see if we have any queued up // subscription messages sent to us already from the server. If so, // consume those first. Do this only if the MessageHandler registered is // not null (since that would be the HedwigSubscriber.stopDelivery // call). if (messageHandler != null && subscribeMsgQueue != null && subscribeMsgQueue.size() > 0) { if (logger.isDebugEnabled()) logger.debug("Consuming " + subscribeMsgQueue.size() + " queued up messages for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); for (Message message : subscribeMsgQueue) { asyncMessageConsume(message); } // Now we can remove the queued up messages since they are all // consumed. subscribeMsgQueue.clear(); } } }
#vulnerable code public void setMessageHandler(MessageHandler messageHandler) { if (logger.isDebugEnabled()) logger.debug("Setting the messageHandler for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); synchronized (this) { this.messageHandler = messageHandler; // Once the MessageHandler is registered, see if we have any queued up // subscription messages sent to us already from the server. If so, // consume those first. Do this only if the MessageHandler registered is // not null (since that would be the HedwigSubscriber.stopDelivery // call). if (messageHandler != null && subscribeMsgQueue != null && subscribeMsgQueue.size() > 0) { if (logger.isDebugEnabled()) logger.debug("Consuming " + subscribeMsgQueue.size() + " queued up messages for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); for (Message message : subscribeMsgQueue) { asyncMessageConsume(message); } // Now we can remove the queued up messages since they are all // consumed. subscribeMsgQueue.clear(); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj sync = (SyncObj) ctx; sync.setLedgerEntries(seq); sync.setReturnCode(rc); synchronized (sync) { sync.value = true; sync.notify(); } }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGarbageCollectLedgers() throws Exception { int numLedgers = 100; int numRemovedLedgers = 10; final Set<Long> createdLedgers = new HashSet<Long>(); final Set<Long> removedLedgers = new HashSet<Long>(); // create 100 ledgers createLedgers(numLedgers, createdLedgers); Random r = new Random(System.currentTimeMillis()); final List<Long> tmpList = new ArrayList<Long>(); tmpList.addAll(createdLedgers); Collections.shuffle(tmpList, r); // random remove several ledgers for (int i=0; i<numRemovedLedgers; i++) { long ledgerId = tmpList.get(i); synchronized (removedLedgers) { getLedgerManager().deleteLedger(ledgerId, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { synchronized (removedLedgers) { removedLedgers.notify(); } } }); removedLedgers.wait(); } removedLedgers.add(ledgerId); createdLedgers.remove(ledgerId); } final CountDownLatch inGcProgress = new CountDownLatch(1); final CountDownLatch createLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(2); Thread gcThread = new Thread() { @Override public void run() { getActiveLedgerManager().garbageCollectLedgers(new GarbageCollector() { boolean paused = false; @Override public void gc(long ledgerId) { if (!paused) { inGcProgress.countDown(); try { createLatch.await(); } catch (InterruptedException ie) { } paused = true; } LOG.info("Garbage Collected ledger {}", ledgerId); } }); LOG.info("Gc Thread quits."); endLatch.countDown(); } }; Thread createThread = new Thread() { @Override public void run() { try { inGcProgress.await(); // create 10 more ledgers createLedgers(10, createdLedgers); LOG.info("Finished creating 10 more ledgers."); createLatch.countDown(); } catch (Exception e) { } LOG.info("Create Thread quits."); endLatch.countDown(); } }; createThread.start(); gcThread.start(); endLatch.await(); // test ledgers for (Long ledger : removedLedgers) { assertFalse(getActiveLedgerManager().containsActiveLedger(ledger)); } for (Long ledger : createdLedgers) { assertTrue(getActiveLedgerManager().containsActiveLedger(ledger)); } }
#vulnerable code @Test public void testGarbageCollectLedgers() throws Exception { int numLedgers = 100; int numRemovedLedgers = 10; final Set<Long> createdLedgers = new HashSet<Long>(); final Set<Long> removedLedgers = new HashSet<Long>(); // create 100 ledgers createLedgers(numLedgers, createdLedgers); Random r = new Random(System.currentTimeMillis()); final List<Long> tmpList = new ArrayList<Long>(); tmpList.addAll(createdLedgers); Collections.shuffle(tmpList, r); // random remove several ledgers for (int i=0; i<numRemovedLedgers; i++) { long ledgerId = tmpList.get(i); getLedgerManager().deleteLedger(ledgerId, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { synchronized (removedLedgers) { removedLedgers.notify(); } } }); synchronized (removedLedgers) { removedLedgers.wait(); } removedLedgers.add(ledgerId); createdLedgers.remove(ledgerId); } final CountDownLatch inGcProgress = new CountDownLatch(1); final CountDownLatch createLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(2); Thread gcThread = new Thread() { @Override public void run() { getActiveLedgerManager().garbageCollectLedgers(new GarbageCollector() { boolean paused = false; @Override public void gc(long ledgerId) { if (!paused) { inGcProgress.countDown(); try { createLatch.await(); } catch (InterruptedException ie) { } paused = true; } LOG.info("Garbage Collected ledger {}", ledgerId); } }); LOG.info("Gc Thread quits."); endLatch.countDown(); } }; Thread createThread = new Thread() { @Override public void run() { try { inGcProgress.await(); // create 10 more ledgers createLedgers(10, createdLedgers); LOG.info("Finished creating 10 more ledgers."); createLatch.countDown(); } catch (Exception e) { } LOG.info("Create Thread quits."); endLatch.countDown(); } }; createThread.start(); gcThread.start(); endLatch.await(); // test ledgers for (Long ledger : removedLedgers) { assertFalse(getActiveLedgerManager().containsActiveLedger(ledger)); } for (Long ledger : createdLedgers) { assertTrue(getActiveLedgerManager().containsActiveLedger(ledger)); } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void start(Configuration conf) { initIfNecessary(); int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); String prefix = conf.getString("codahaleStatsPrefix", ""); String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); String csvDir = conf.getString("codahaleStatsCSVEndpoint"); String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); if (!Strings.isNullOrEmpty(graphiteHost)) { LOG.info("Configuring stats with graphite"); HostAndPort addr = HostAndPort.fromString(graphiteHost); final Graphite graphite = new Graphite( new InetSocketAddress(addr.getHostText(), addr.getPort())); reporters.add(GraphiteReporter.forRegistry(getMetrics()) .prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite)); } if (!Strings.isNullOrEmpty(csvDir)) { // NOTE: 1/ metrics output files are exclusive to a given process // 2/ the output directory must exist // 3/ if output files already exist they are not overwritten and there is no metrics output File outdir; if (Strings.isNullOrEmpty(prefix)) { outdir = new File(csvDir, prefix); } else { outdir = new File(csvDir); } LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); reporters.add(CsvReporter.forRegistry(getMetrics()) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(outdir)); } if (!Strings.isNullOrEmpty(slf4jCat)) { LOG.info("Configuring stats with slf4j"); reporters.add(Slf4jReporter.forRegistry(getMetrics()) .outputTo(LoggerFactory.getLogger(slf4jCat)) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build()); } for (ScheduledReporter r : reporters) { r.start(metricsOutputFrequency, TimeUnit.SECONDS); } }
#vulnerable code @Override public void start(Configuration conf) { initIfNecessary(); int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); String prefix = conf.getString("codahaleStatsPrefix", ""); String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); String csvDir = conf.getString("codahaleStatsCSVEndpoint"); String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); if (!Strings.isNullOrEmpty(graphiteHost)) { LOG.info("Configuring stats with graphite"); HostAndPort addr = HostAndPort.fromString(graphiteHost); final Graphite graphite = new Graphite( new InetSocketAddress(addr.getHostText(), addr.getPort())); reporters.add(GraphiteReporter.forRegistry(metrics) .prefixedWith(prefix) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(MetricFilter.ALL) .build(graphite)); } if (!Strings.isNullOrEmpty(csvDir)) { // NOTE: 1/ metrics output files are exclusive to a given process // 2/ the output directory must exist // 3/ if output files already exist they are not overwritten and there is no metrics output File outdir; if (Strings.isNullOrEmpty(prefix)) { outdir = new File(csvDir, prefix); } else { outdir = new File(csvDir); } LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); reporters.add(CsvReporter.forRegistry(metrics) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build(outdir)); } if (!Strings.isNullOrEmpty(slf4jCat)) { LOG.info("Configuring stats with slf4j"); reporters.add(Slf4jReporter.forRegistry(metrics) .outputTo(LoggerFactory.getLogger(slf4jCat)) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build()); } for (ScheduledReporter r : reporters) { r.start(metricsOutputFrequency, TimeUnit.SECONDS); } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc == BKException.Code.OK) { LedgerEntry entry = seq.nextElement(); byte[] data = entry.getEntry(); /* * We will add this entry again to make sure it is written to enough * replicas. We subtract the length of the data itself, since it will * be added again when processing the call to add it. */ synchronized (lh) { lh.length = entry.getLength() - (long) data.length; } lh.asyncRecoveryAddEntry(data, 0, data.length, this, null); return; } if (rc == BKException.Code.NoSuchEntryException || rc == BKException.Code.NoSuchLedgerExistsException) { lh.asyncCloseInternal(new CloseCallback() { @Override public void closeComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != KeeperException.Code.OK.intValue()) { LOG.warn("Close failed: " + BKException.getMessage(rc)); cb.operationComplete(BKException.Code.ZKException, null); } else { cb.operationComplete(BKException.Code.OK, null); LOG.debug("After closing length is: {}", lh.getLength()); } } }, null, BKException.Code.LedgerClosedException); return; } // otherwise, some other error, we can't handle LOG.error("Failure " + BKException.getMessage(rc) + " while reading entry: " + (lh.lastAddConfirmed + 1) + " ledger: " + lh.ledgerId + " while recovering ledger"); cb.operationComplete(rc, null); return; }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { // get back to prev value lh.lastAddConfirmed--; if (rc == BKException.Code.OK) { LedgerEntry entry = seq.nextElement(); byte[] data = entry.getEntry(); /* * We will add this entry again to make sure it is written to enough * replicas. We subtract the length of the data itself, since it will * be added again when processing the call to add it. */ synchronized (lh) { lh.length = entry.getLength() - (long) data.length; } lh.asyncRecoveryAddEntry(data, 0, data.length, this, null); return; } if (rc == BKException.Code.NoSuchEntryException || rc == BKException.Code.NoSuchLedgerExistsException) { lh.asyncCloseInternal(new CloseCallback() { @Override public void closeComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != KeeperException.Code.OK.intValue()) { LOG.warn("Close failed: " + BKException.getMessage(rc)); cb.operationComplete(BKException.Code.ZKException, null); } else { cb.operationComplete(BKException.Code.OK, null); LOG.debug("After closing length is: {}", lh.getLength()); } } }, null, BKException.Code.LedgerClosedException); return; } // otherwise, some other error, we can't handle LOG.error("Failure " + BKException.getMessage(rc) + " while reading entry: " + (lh.lastAddConfirmed + 1) + " ledger: " + lh.ledgerId + " while recovering ledger"); cb.operationComplete(rc, null); return; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. try { HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); } catch (NoResponseHandlerException e) { logger.error("No response handler found while storing the publish callback."); // Callback on pubsubdata indicating failure. pubSubData.getCallback().operationFailed(pubSubData.context, new CouldNotConnectException("No response " + "handler found while attempting to publish. So could not connect.")); return; } // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); }
#vulnerable code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { bw.close(); } catch (IOException e) { } } }
#vulnerable code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { fos.close(); } catch (IOException e) { } } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 86 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj x = (SyncObj) ctx; if (rc != 0) { LOG.error("Failure during add {}", rc); x.failureOccurred = true; } synchronized (x) { x.value = true; x.ls = seq; x.notify(); } }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc != 0) fail("Failed to write entry"); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected synchronized void messageConsumed(Message message) { if (logger.isDebugEnabled()) logger.debug("Message has been successfully consumed by the client app for message: " + message + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); // Update the consumed messages buffer variables if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled()) { // Update these variables only if we are auto-sending consume // messages to the server. Otherwise the onus is on the client app // to call the Subscriber consume API to let the server know which // messages it has successfully consumed. numConsumedMessagesInBuffer++; lastMessageSeqId = message.getMsgId(); } // Remove this consumed message from the outstanding Message Set. outstandingMsgSet.remove(message); // For consume response to server, there is a config param on how many // messages to consume and buffer up before sending the consume request. // We just need to keep a count of the number of messages consumed // and the largest/latest msg ID seen so far in this batch. Messages // should be delivered in order and without gaps. Do this only if // auto-sending of consume messages is enabled. if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled() && numConsumedMessagesInBuffer >= responseHandler.getConfiguration().getConsumedMessagesBufferSize()) { // Send the consume request and reset the consumed messages buffer // variables. We will use the same Channel created from the // subscribe request for the TopicSubscriber. logger.debug("Consumed message buffer limit reached so send the Consume Request to the " + "server with lastMessageSeqId: {}", lastMessageSeqId); responseHandler.getSubscriber().doConsume(origSubData, subscribeChannel, lastMessageSeqId); numConsumedMessagesInBuffer = 0; lastMessageSeqId = null; } // Check if we throttled message consumption previously when the // outstanding message limit was reached. For now, only turn the // delivery back on if there are no more outstanding messages to // consume. We could make this a configurable parameter if needed. if (!subscribeChannel.isReadable() && outstandingMsgSet.isEmpty()) { if (logger.isDebugEnabled()) logger.debug("Message consumption has caught up so okay to turn off throttling of " + "messages on the subscribe channel for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); subscribeChannel.setReadable(true); } }
#vulnerable code protected synchronized void messageConsumed(Message message) { if (logger.isDebugEnabled()) logger.debug("Message has been successfully consumed by the client app for message: " + message + ", topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); // Update the consumed messages buffer variables if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled()) { // Update these variables only if we are auto-sending consume // messages to the server. Otherwise the onus is on the client app // to call the Subscriber consume API to let the server know which // messages it has successfully consumed. numConsumedMessagesInBuffer++; lastMessageSeqId = message.getMsgId(); } // Remove this consumed message from the outstanding Message Set. outstandingMsgSet.remove(message); // For consume response to server, there is a config param on how many // messages to consume and buffer up before sending the consume request. // We just need to keep a count of the number of messages consumed // and the largest/latest msg ID seen so far in this batch. Messages // should be delivered in order and without gaps. Do this only if // auto-sending of consume messages is enabled. if (responseHandler.getConfiguration().isAutoSendConsumeMessageEnabled() && numConsumedMessagesInBuffer >= responseHandler.getConfiguration().getConsumedMessagesBufferSize()) { // Send the consume request and reset the consumed messages buffer // variables. We will use the same Channel created from the // subscribe request for the TopicSubscriber. if (logger.isDebugEnabled()) logger .debug("Consumed message buffer limit reached so send the Consume Request to the server with lastMessageSeqId: " + lastMessageSeqId); responseHandler.getSubscriber().doConsume(origSubData, subscribeChannel, lastMessageSeqId); numConsumedMessagesInBuffer = 0; lastMessageSeqId = null; } // Check if we throttled message consumption previously when the // outstanding message limit was reached. For now, only turn the // delivery back on if there are no more outstanding messages to // consume. We could make this a configurable parameter if needed. if (!subscribeChannel.isReadable() && outstandingMsgSet.isEmpty()) { if (logger.isDebugEnabled()) logger .debug("Message consumption has caught up so okay to turn off throttling of messages on the subscribe channel for topic: " + origSubData.topic.toStringUtf8() + ", subscriberId: " + origSubData.subscriberId.toStringUtf8()); subscribeChannel.setReadable(true); } } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout=60000) public void testReadFromOpenLedger() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); long lac = writeNEntriesLastWriteSync(lh, numEntriesToWrite); LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); // no recovery opened ledger 's last confirmed entry id is less than written // and it just can read until (i-1) long toRead = lac - 1; Enumeration<LedgerEntry> readEntry = lhOpen.readEntries(toRead, toRead); assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); LedgerEntry e = readEntry.nextElement(); assertEquals(toRead, e.getEntryId()); Assert.assertArrayEquals(entries.get((int)toRead), e.getEntry()); // should not written to a read only ledger try { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); lhOpen.addEntry(entry.array()); fail("Should have thrown an exception here"); } catch (BKException.BKIllegalOpException bkioe) { // this is the correct response } catch (Exception ex) { LOG.error("Unexpected exception", ex); fail("Unexpected exception"); } // close read only ledger should not change metadata lhOpen.close(); lac = writeNEntriesLastWriteSync(lh, numEntriesToWrite); assertEquals("Last confirmed add: ", lac, (numEntriesToWrite * 2) - 1); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == -1) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertEquals("Last confirmed add", sync.lastConfirmed, (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test(timeout=60000) public void testReadFromOpenLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); if(i == numEntriesToWrite/2) { LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); // no recovery opened ledger 's last confirmed entry id is less than written // and it just can read until (i-1) int toRead = i - 1; Enumeration<LedgerEntry> readEntry = lhOpen.readEntries(toRead, toRead); assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); LedgerEntry e = readEntry.nextElement(); assertEquals(toRead, e.getEntryId()); Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); // should not written to a read only ledger try { lhOpen.addEntry(entry.array()); fail("Should have thrown an exception here"); } catch (BKException.BKIllegalOpException bkioe) { // this is the correct response } catch (Exception ex) { LOG.error("Unexpected exception", ex); fail("Unexpected exception"); } // close read only ledger should not change metadata lhOpen.close(); } } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == -1) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void processResult(int rc, String path, Object ctx, List<String> children) { if (rc != KeeperException.Code.OK.intValue()) { //logger.error("Error while reading bookies", KeeperException.create(Code.get(rc), path)); // try the read after a second again scheduler.schedule(reReadTask, ZK_CONNECT_BACKOFF_SEC, TimeUnit.SECONDS); return; } // Read the bookie addresses into a set for efficient lookup HashSet<InetSocketAddress> newBookieAddrs = new HashSet<InetSocketAddress>(); for (String bookieAddrString : children) { InetSocketAddress bookieAddr; try { bookieAddr = StringUtils.parseAddr(bookieAddrString); } catch (IOException e) { logger.error("Could not parse bookie address: " + bookieAddrString + ", ignoring this bookie"); continue; } newBookieAddrs.add(bookieAddr); } final HashSet<InetSocketAddress> deadBookies; synchronized (this) { deadBookies = (HashSet<InetSocketAddress>)knownBookies.clone(); deadBookies.removeAll(newBookieAddrs); knownBookies = newBookieAddrs; } if (bk.getBookieClient() != null) { bk.getBookieClient().closeClients(deadBookies); } }
#vulnerable code @Override public void processResult(int rc, String path, Object ctx, List<String> children) { if (rc != KeeperException.Code.OK.intValue()) { //logger.error("Error while reading bookies", KeeperException.create(Code.get(rc), path)); // try the read after a second again scheduler.schedule(reReadTask, ZK_CONNECT_BACKOFF_SEC, TimeUnit.SECONDS); return; } // Read the bookie addresses into a set for efficient lookup HashSet<InetSocketAddress> newBookieAddrs = new HashSet<InetSocketAddress>(); for (String bookieAddrString : children) { InetSocketAddress bookieAddr; try { bookieAddr = StringUtils.parseAddr(bookieAddrString); } catch (IOException e) { logger.error("Could not parse bookie address: " + bookieAddrString + ", ignoring this bookie"); continue; } newBookieAddrs.add(bookieAddr); } HashSet<InetSocketAddress> deadBookies = (HashSet<InetSocketAddress>)knownBookies.clone(); deadBookies.removeAll(newBookieAddrs); synchronized (this) { knownBookies = newBookieAddrs; } if (bk.getBookieClient() != null) { bk.getBookieClient().closeClients(deadBookies); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(10000); assertFalse("Failure occurred during write", sync.failureOccurred); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); assertFalse("Failure occurred during read", sync.failureOccurred); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (sync.ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = sync.ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } }
#vulnerable code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout=60000) public void testLastConfirmedAdd() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test(timeout=60000) public void testLastConfirmedAdd() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. try { HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); } catch (NoResponseHandlerException e) { logger.error("No response handler found while storing the publish callback."); // Callback on pubsubdata indicating failure. pubSubData.getCallback().operationFailed(pubSubData.context, new CouldNotConnectException("No response " + "handler found while attempting to publish. So could not connect.")); return; } // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); }
#vulnerable code protected void doPublish(PubSubData pubSubData, Channel channel) { // Create a PubSubRequest PubSubRequest.Builder pubsubRequestBuilder = PubSubRequest.newBuilder(); pubsubRequestBuilder.setProtocolVersion(ProtocolVersion.VERSION_ONE); pubsubRequestBuilder.setType(OperationType.PUBLISH); if (pubSubData.triedServers != null && pubSubData.triedServers.size() > 0) { pubsubRequestBuilder.addAllTriedServers(pubSubData.triedServers); } long txnId = client.globalCounter.incrementAndGet(); pubsubRequestBuilder.setTxnId(txnId); pubsubRequestBuilder.setShouldClaim(pubSubData.shouldClaim); pubsubRequestBuilder.setTopic(pubSubData.topic); // Now create the PublishRequest PublishRequest.Builder publishRequestBuilder = PublishRequest.newBuilder(); publishRequestBuilder.setMsg(pubSubData.msg); // Set the PublishRequest into the outer PubSubRequest pubsubRequestBuilder.setPublishRequest(publishRequestBuilder); // Update the PubSubData with the txnId and the requestWriteTime pubSubData.txnId = txnId; pubSubData.requestWriteTime = MathUtils.now(); // Before we do the write, store this information into the // ResponseHandler so when the server responds, we know what // appropriate Callback Data to invoke for the given txn ID. HedwigClientImpl.getResponseHandlerFromChannel(channel).txn2PubSubData.put(txnId, pubSubData); // Finally, write the Publish request through the Channel. if (logger.isDebugEnabled()) logger.debug("Writing a Publish request to host: " + HedwigClientImpl.getHostFromChannel(channel) + " for pubSubData: " + pubSubData); ChannelFuture future = channel.write(pubsubRequestBuilder.build()); future.addListener(new WriteCallback(pubSubData, client)); } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private long readLastLogId(File f) { FileInputStream fis; try { fis = new FileInputStream(new File(f, "lastId")); } catch (FileNotFoundException e) { return -1; } BufferedReader br = new BufferedReader(new InputStreamReader(fis)); try { String lastIdString = br.readLine(); return Long.parseLong(lastIdString, 16); } catch (IOException e) { return -1; } catch(NumberFormatException e) { return -1; } finally { try { br.close(); } catch (IOException e) { } } }
#vulnerable code private long readLastLogId(File f) { FileInputStream fis; try { fis = new FileInputStream(new File(f, "lastId")); } catch (FileNotFoundException e) { return -1; } BufferedReader br = new BufferedReader(new InputStreamReader(fis)); try { String lastIdString = br.readLine(); return Long.parseLong(lastIdString, 16); } catch (IOException e) { return -1; } catch(NumberFormatException e) { return -1; } finally { try { fis.close(); } catch (IOException e) { } } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { SyncObj sync = new SyncObj(); LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); String charset = "utf-8"; LOG.debug("Default charset: " + Charset.defaultCharset()); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { int randomInt = rng.nextInt(maxInt); byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); entries.add(entry); lh.asyncAddEntry(entry, this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** ASYNC WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETED // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries ls = lh.readEntries(0, numEntriesToWrite - 1); LOG.debug("*** SYNC READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] origEntryBytes = entries.get(i++); byte[] retrEntryBytes = ls.nextElement().getEntry(); LOG.debug("Original byte entry size: " + origEntryBytes.length); LOG.debug("Saved byte entry size: " + retrEntryBytes.length); String origEntry = new String(origEntryBytes, charset); String retrEntry = new String(retrEntryBytes, charset); LOG.debug("Original entry: " + origEntry); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteRangeAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi int numEntries = 4; // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntries) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } try { lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); fail("Shouldn't be able to use negative offset"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); fail("Shouldn't be able to use that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); fail("Shouldn't be able to use negative offset " + "with that much length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, 4, -3, this, sync); fail("Shouldn't be able to use negative length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } try { lh.asyncAddEntry(bytes, -4, -3, this, sync); fail("Shouldn't be able to use negative offset & length"); } catch (ArrayIndexOutOfBoundsException aiob) { // expected } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntries - 1)); // read entries lh.asyncReadEntries(0, numEntries - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { byte[] expected = null; byte[] entry = ls.nextElement().getEntry(); switch (i) { case 0: expected = Arrays.copyOfRange(bytes, 0, bytes.length); break; case 1: expected = Arrays.copyOfRange(bytes, 0, 4); break; case 2: expected = Arrays.copyOfRange(bytes, 3, 3+4); break; case 3: expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); break; } assertNotNull("There are more checks than writes", expected); String message = "Checking entry " + i + " for equality [" + new String(entry, "UTF-8") + "," + new String(expected, "UTF-8") + "]"; assertTrue(message, Arrays.equals(entry, expected)); i++; } assertTrue("Checking number of read entries", i == numEntries); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteAsyncLength() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } long length = numEntriesToWrite * 4; assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteAsyncLength() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } long length = numEntriesToWrite * 4; assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { LOG.info("Running..."); long start = previous = System.currentTimeMillis(); int sent = 0; Thread reporter = new Thread() { public void run() { try { while(true) { Thread.sleep(200); LOG.info("ms: {} req: {}", System.currentTimeMillis(), completedRequests.getAndSet(0)); } } catch (InterruptedException ie) { LOG.info("Caught interrupted exception, going away"); } } }; reporter.start(); long beforeSend = System.nanoTime(); while(!Thread.currentThread().isInterrupted() && sent < sendLimit) { try { sem.acquire(); if (sent == 10000) { long afterSend = System.nanoTime(); long time = afterSend - beforeSend; LOG.info("Time to send first batch: {}s {}ns ", time/1000/1000/1000, time); } } catch (InterruptedException e) { break; } final int index = getRandomLedger(); LedgerHandle h = lh[index]; if (h == null) { LOG.error("Handle " + index + " is null!"); } else { long nanoTime = System.nanoTime(); lh[index].asyncAddEntry(bytes, this, new Context(sent, nanoTime)); counter.incrementAndGet(); } sent++; } LOG.info("Sent: " + sent); try { synchronized (this) { while (this.counter.get() > 0) { waitFor(1000); } } } catch(InterruptedException e) { LOG.error("Interrupted while waiting", e); } synchronized(this) { duration = System.currentTimeMillis() - start; } throughput = sent*1000/getDuration(); reporter.interrupt(); try { reporter.join(); } catch (InterruptedException ie) { // ignore } LOG.info("Finished processing in ms: " + getDuration() + " tp = " + throughput); }
#vulnerable code public void run() { LOG.info("Running..."); long start = previous = System.currentTimeMillis(); byte messageCount = 0; int sent = 0; Thread reporter = new Thread() { public void run() { try { while(true) { Thread.sleep(200); LOG.info("ms: {} req: {}", System.currentTimeMillis(), completedRequests.getAndSet(0)); } } catch (InterruptedException ie) { LOG.info("Caught interrupted exception, going away"); } } }; reporter.start(); long beforeSend = System.nanoTime(); while(!Thread.currentThread().isInterrupted() && sent < sendLimit) { try { sem.acquire(); if (sent == 10000) { long afterSend = System.nanoTime(); long time = afterSend - beforeSend; LOG.info("Time to send first batch: {}s {}ns ", time/1000/1000/1000, time); } } catch (InterruptedException e) { break; } final int index = getRandomLedger(); LedgerHandle h = lh[index]; if (h == null) { LOG.error("Handle " + index + " is null!"); } else { long nanoTime = System.nanoTime(); lh[index].asyncAddEntry(bytes, this, new Context(sent, nanoTime)); counter.incrementAndGet(); } sent++; } LOG.info("Sent: " + sent); try { synchronized (this) { while(this.counter.get() > 0) Thread.sleep(1000); } } catch(InterruptedException e) { LOG.error("Interrupted while waiting", e); } synchronized(this) { duration = System.currentTimeMillis() - start; } throughput = sent*1000/duration; reporter.interrupt(); try { reporter.join(); } catch (InterruptedException ie) { // ignore } LOG.info("Finished processing in ms: " + duration + " tp = " + throughput); } #location 67 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code LedgerHandle(BookKeeper bk, long ledgerId, LedgerMetadata metadata, DigestType digestType, byte[] password) throws GeneralSecurityException, NumberFormatException { this.bk = bk; this.metadata = metadata; if (metadata.isClosed()) { lastAddConfirmed = lastAddPushed = metadata.getLastEntryId(); length = metadata.getLength(); } else { lastAddConfirmed = lastAddPushed = INVALID_ENTRY_ID; length = 0; } this.ledgerId = ledgerId; this.throttling = bk.getConf().getThrottleValue(); this.opCounterSem = new Semaphore(throttling); macManager = DigestManager.instantiate(ledgerId, password, digestType); this.ledgerKey = MacDigestManager.genDigest("ledger", password); distributionSchedule = new RoundRobinDistributionSchedule( metadata.getQuorumSize(), metadata.getEnsembleSize()); }
#vulnerable code void handleBookieFailure(InetSocketAddress addr, final int bookieIndex) { InetSocketAddress newBookie; if (LOG.isDebugEnabled()) { LOG.debug("Handling failure of bookie: " + addr + " index: " + bookieIndex); } try { newBookie = bk.bookieWatcher .getAdditionalBookie(metadata.currentEnsemble); } catch (BKNotEnoughBookiesException e) { LOG .error("Could not get additional bookie to remake ensemble, closing ledger: " + ledgerId); handleUnrecoverableErrorDuringAdd(e.getCode()); return; } final ArrayList<InetSocketAddress> newEnsemble = new ArrayList<InetSocketAddress>( metadata.currentEnsemble); newEnsemble.set(bookieIndex, newBookie); if (LOG.isDebugEnabled()) { LOG.debug("Changing ensemble from: " + metadata.currentEnsemble + " to: " + newEnsemble + " for ledger: " + ledgerId + " starting at entry: " + (lastAddConfirmed + 1)); } final long newEnsembleStartEntry = lastAddConfirmed + 1; metadata.addEnsemble(newEnsembleStartEntry, newEnsemble); final class ChangeEnsembleCb implements GenericCallback<Void> { @Override public void operationComplete(final int rc, Void result) { bk.mainWorkerPool.submitOrdered(ledgerId, new SafeRunnable() { @Override public void safeRun() { if (rc == BKException.Code.MetadataVersionException) { rereadMetadata(new GenericCallback<LedgerMetadata>() { @Override public void operationComplete(int newrc, LedgerMetadata newMeta) { if (newrc != BKException.Code.OK) { LOG.error("Error reading new metadata from ledger after changing ensemble, code=" + newrc); handleUnrecoverableErrorDuringAdd(rc); } else { // a new ensemble is added only when the start entry is larger than zero if (newEnsembleStartEntry > 0) { metadata.getEnsembles().remove(newEnsembleStartEntry); } if (metadata.resolveConflict(newMeta)) { metadata.addEnsemble(newEnsembleStartEntry, newEnsemble); writeLedgerConfig(new ChangeEnsembleCb()); return; } else { LOG.error("Could not resolve ledger metadata conflict while changing ensemble to: " + newEnsemble + ", old meta data is \n" + new String(metadata.serialize()) + "\n, new meta data is \n" + new String(newMeta.serialize()) + "\n ,closing ledger"); handleUnrecoverableErrorDuringAdd(rc); } } } }); return; } else if (rc != BKException.Code.OK) { LOG.error("Could not persist ledger metadata while changing ensemble to: " + newEnsemble + " , closing ledger"); handleUnrecoverableErrorDuringAdd(rc); return; } for (PendingAddOp pendingAddOp : pendingAddOps) { pendingAddOp.unsetSuccessAndSendWriteRequest(bookieIndex); } } }); } }; writeLedgerConfig(new ChangeEnsembleCb()); } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { bw.close(); } catch (IOException e) { } } }
#vulnerable code private void setLastLogId(File dir, long logId) throws IOException { FileOutputStream fos; fos = new FileOutputStream(new File(dir, "lastId")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); try { bw.write(Long.toHexString(logId) + "\n"); bw.flush(); } finally { try { fos.close(); } catch (IOException e) { } } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { SyncObj x = (SyncObj) ctx; if (rc != 0) { LOG.error("Failure during add {}", rc); x.failureOccurred = true; } synchronized (x) { x.value = true; x.ls = seq; x.notify(); } }
#vulnerable code @Override public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) { if (rc != 0) fail("Failed to write entry"); ls = seq; synchronized (sync) { sync.value = true; sync.notify(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout = 60000) public void testWhenNoLogsToCompact() throws Exception { tearDown(); // I dont want the test infrastructure ServerConfiguration conf = new ServerConfiguration(); File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); LedgerDirsManager dirs = new LedgerDirsManager(conf, conf.getLedgerDirs()); final Set<Long> ledgers = Collections .newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); LedgerManager manager = getLedgerManager(ledgers); CheckpointSource checkpointSource = new CheckpointSource() { @Override public Checkpoint newCheckpoint() { return null; } @Override public void checkpointComplete(Checkpoint checkpoint, boolean compact) throws IOException { } }; InterleavedLedgerStorage storage = new InterleavedLedgerStorage(conf, manager, dirs, checkpointSource); double threshold = 0.1; // shouldn't throw exception storage.gcThread.doCompactEntryLogs(threshold); }
#vulnerable code @Test(timeout = 60000) public void testWhenNoLogsToCompact() throws Exception { tearDown(); // I dont want the test infrastructure ServerConfiguration conf = new ServerConfiguration(); File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); LedgerDirsManager dirs = new LedgerDirsManager(conf); final Set<Long> ledgers = Collections .newSetFromMap(new ConcurrentHashMap<Long, Boolean>()); LedgerManager manager = getLedgerManager(ledgers); CheckpointSource checkpointSource = new CheckpointSource() { @Override public Checkpoint newCheckpoint() { return null; } @Override public void checkpointComplete(Checkpoint checkpoint, boolean compact) throws IOException { } }; InterleavedLedgerStorage storage = new InterleavedLedgerStorage(conf, manager, dirs, checkpointSource); double threshold = 0.1; // shouldn't throw exception storage.gcThread.doCompactEntryLogs(threshold); } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code LedgerHandle(BookKeeper bk, long ledgerId, LedgerMetadata metadata, DigestType digestType, byte[] password) throws GeneralSecurityException, NumberFormatException { this.bk = bk; this.metadata = metadata; if (metadata.isClosed()) { lastAddConfirmed = lastAddPushed = metadata.getLastEntryId(); length = metadata.getLength(); } else { lastAddConfirmed = lastAddPushed = INVALID_ENTRY_ID; length = 0; } this.ledgerId = ledgerId; this.throttler = RateLimiter.create(bk.getConf().getThrottleValue()); macManager = DigestManager.instantiate(ledgerId, password, digestType); this.ledgerKey = MacDigestManager.genDigest("ledger", password); distributionSchedule = new RoundRobinDistributionSchedule( metadata.getWriteQuorumSize(), metadata.getAckQuorumSize(), metadata.getEnsembleSize()); }
#vulnerable code void handleBookieFailure(final InetSocketAddress addr, final int bookieIndex) { InetSocketAddress newBookie; LOG.debug("Handling failure of bookie: {} index: {}", addr, bookieIndex); final ArrayList<InetSocketAddress> newEnsemble = new ArrayList<InetSocketAddress>(); blockAddCompletions.incrementAndGet(); final long newEnsembleStartEntry = lastAddConfirmed + 1; // avoid parallel ensemble changes to same ensemble. synchronized (metadata) { if (!metadata.currentEnsemble.get(bookieIndex).equals(addr)) { // ensemble has already changed, failure of this addr is immaterial LOG.warn("Write did not succeed to {}, bookieIndex {}, but we have already fixed it.", addr, bookieIndex); blockAddCompletions.decrementAndGet(); return; } try { newBookie = bk.bookieWatcher .getAdditionalBookie(metadata.currentEnsemble); } catch (BKNotEnoughBookiesException e) { LOG.error("Could not get additional bookie to " + "remake ensemble, closing ledger: " + ledgerId); handleUnrecoverableErrorDuringAdd(e.getCode()); return; } newEnsemble.addAll(metadata.currentEnsemble); newEnsemble.set(bookieIndex, newBookie); if (LOG.isDebugEnabled()) { LOG.debug("Changing ensemble from: " + metadata.currentEnsemble + " to: " + newEnsemble + " for ledger: " + ledgerId + " starting at entry: " + (lastAddConfirmed + 1)); } metadata.addEnsemble(newEnsembleStartEntry, newEnsemble); } EnsembleInfo ensembleInfo = new EnsembleInfo(newEnsemble, bookieIndex, addr); writeLedgerConfig(new ChangeEnsembleCb(ensembleInfo)); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout=60000) public void testLastConfirmedAdd() throws Exception { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); writeNEntriesLastWriteSync(lh, numEntriesToWrite); SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test(timeout=60000) public void testLastConfirmedAdd() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } long last = lh.readLastConfirmed(); assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); /* * Asynchronous call to read last confirmed entry */ lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.addEntry(entry.array()); } SyncObj sync = new SyncObj(); lh.asyncReadLastConfirmed(this, sync); // Wait for for last confirmed synchronized (sync) { while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { LOG.debug("Counter = " + sync.lastConfirmed); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void compactEntryLog(long entryLogId) { EntryLogMetadata entryLogMeta = entryLogMetaMap.get(entryLogId); if (null == entryLogMeta) { LOG.warn("Can't get entry log meta when compacting entry log " + entryLogId + "."); return; } // Similar with Sync Thread // try to mark compacting flag to make sure it would not be interrupted // by shutdown during compaction. otherwise it will receive // ClosedByInterruptException which may cause index file & entry logger // closed and corrupted. if (!compacting.compareAndSet(false, true)) { // set compacting flag failed, means compacting is true now // indicates another thread wants to interrupt gc thread to exit return; } LOG.info("Compacting entry log : " + entryLogId); try { CompactionScanner scanner = new CompactionScanner(entryLogMeta); entryLogger.scanEntryLog(entryLogId, scanner); scanner.awaitComplete(); // after moving entries to new entry log, remove this old one removeEntryLog(entryLogId); } catch (IOException e) { LOG.info("Premature exception when compacting " + entryLogId, e); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.warn("Interrupted while compacting", ie); } finally { // clear compacting flag compacting.set(false); } }
#vulnerable code protected void compactEntryLog(long entryLogId) { EntryLogMetadata entryLogMeta = entryLogMetaMap.get(entryLogId); if (null == entryLogMeta) { LOG.warn("Can't get entry log meta when compacting entry log " + entryLogId + "."); return; } // Similar with Sync Thread // try to mark compacting flag to make sure it would not be interrupted // by shutdown during compaction. otherwise it will receive // ClosedByInterruptException which may cause index file & entry logger // closed and corrupted. if (!compacting.compareAndSet(false, true)) { // set compacting flag failed, means compacting is true now // indicates another thread wants to interrupt gc thread to exit return; } LOG.info("Compacting entry log : " + entryLogId); try { entryLogger.scanEntryLog(entryLogId, new CompactionScanner(entryLogMeta)); // after moving entries to new entry log, remove this old one removeEntryLog(entryLogId); } catch (IOException e) { LOG.info("Premature exception when compacting " + entryLogId, e); } finally { // clear compacting flag compacting.set(false); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(10000); assertFalse("Failure occurred during write", sync.failureOccurred); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); assertFalse("Failure occurred during read", sync.failureOccurred); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (sync.ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = sync.ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } }
#vulnerable code void auxTestReadWriteAsyncSingleClient(BookieServer bs) throws IOException { try { // Create a ledger lh = bkc.createLedger(3, 2, digestType, ledgerPassword); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } LOG.info("Wrote " + numEntriesToWrite + " and now going to fail bookie."); // Bookie fail bs.shutdown(); // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger bkc.close(); bkc = new BookKeeperTestClient(baseClientConf); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(10000); assertTrue("Haven't received entries", sync.value); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + i); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); LOG.info("Verified that entries are ok, and now closing ledger"); lh.close(); } catch (KeeperException e) { LOG.error("Caught KeeperException", e); fail(e.toString()); } catch (BKException e) { LOG.error("Caught BKException", e); fail(e.toString()); } catch (InterruptedException e) { LOG.error("Caught InterruptedException", e); fail(e.toString()); } } #location 63 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWithoutZookeeper() throws Exception { for (int i = 0; i < numberOfLedgers; i++) { createAndAddEntriesToLedger().close(); } BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); stopZKCluster(); try { bookieLedgerIndex.getBookieToLedgerIndex(); fail("Must throw exception as bookies are not running!"); } catch (BKAuditException bkAuditException) { // expected behaviour } }
#vulnerable code @Test public void testWithoutZookeeper() throws Exception { LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory .newLedgerManagerFactory(baseConf, zkc); LedgerManager ledgerManager = newLedgerManagerFactory .newLedgerManager(); List<Long> ledgerList = new ArrayList<Long>(3); LedgerHandle lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); lh = createAndAddEntriesToLedger(); lh.close(); ledgerList.add(lh.getId()); BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer( ledgerManager); stopZKCluster(); try { bookieLedgerIndex.getBookieToLedgerIndex(); fail("Must throw exception as bookies are not running!"); } catch (BKAuditException bkAuditException) { // expected behaviour } } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteAsyncSingleClient() throws IOException { SyncObj sync = new SyncObj(); try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; Enumeration<LedgerEntry> ls = sync.getLedgerEntries(); while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteAsyncSingleClient() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); for (int i = 0; i < numEntriesToWrite; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); synchronized (sync) { while (sync.value == false) { sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); // at this point, Enumeration<LedgerEntry> ls is filled with the returned // values int i = 0; while (ls.hasMoreElements()) { ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); Integer origEntry = origbb.getInt(); byte[] entry = ls.nextElement().getEntry(); ByteBuffer result = ByteBuffer.wrap(entry); LOG.debug("Length of result: " + result.capacity()); LOG.debug("Original entry: " + origEntry); Integer retrEntry = result.getInt(); LOG.debug("Retrieved entry: " + retrEntry); assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); i++; } assertTrue("Checking number of read entries", i == numEntriesToWrite); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void initiate() { ReadLastConfirmedOp rlcop = new ReadLastConfirmedOp(lh, new ReadLastConfirmedOp.LastConfirmedDataCallback() { public void readLastConfirmedDataComplete(int rc, RecoveryData data) { if (rc == BKException.Code.OK) { lh.lastAddPushed = lh.lastAddConfirmed = data.lastAddConfirmed; lh.length = data.length; doRecoveryRead(); } else { cb.operationComplete(BKException.Code.ReadException, null); } } }); /** * Enable fencing on this op. When the read request reaches the bookies * server it will fence off the ledger, stopping any subsequent operation * from writing to it. */ rlcop.initiateWithFencing(); }
#vulnerable code public void initiate() { /** * Enable fencing on this op. When the read request reaches the bookies * server it will fence off the ledger, stopping any subsequent operation * from writing to it. */ int flags = BookieProtocol.FLAG_DO_FENCING; for (int i = 0; i < lh.metadata.currentEnsemble.size(); i++) { lh.bk.bookieClient.readEntry(lh.metadata.currentEnsemble.get(i), lh.ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, this, i, flags); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadWriteAsyncSingleClientThrottle() throws IOException, NoSuchFieldException, IllegalAccessException { SyncObj sync = new SyncObj(); try { Integer throttle = 100; ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); // Create a ledger bkc.getConf().setThrottleValue(throttle); lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); numEntriesToWrite = 8000; for (int i = 0; i < (numEntriesToWrite - 2000); i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } for (int i = 0; i < 2000; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries sync.counter = 0; for (int i = 0; i < numEntriesToWrite; i+=throttle) { lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.info("Entries counter = " + sync.counter); sync.wait(); } assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); } LOG.debug("*** READ COMPLETE ***"); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testReadWriteAsyncSingleClientThrottle() throws IOException, NoSuchFieldException, IllegalAccessException { try { Integer throttle = 100; ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); // Create a ledger bkc.getConf().setThrottleValue(throttle); lh = bkc.createLedger(digestType, ledgerPassword); // bkc.initMessageDigest("SHA1"); ledgerId = lh.getId(); LOG.info("Ledger ID: " + lh.getId()); numEntriesToWrite = 8000; for (int i = 0; i < (numEntriesToWrite - 2000); i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } for (int i = 0; i < 2000; i++) { ByteBuffer entry = ByteBuffer.allocate(4); entry.putInt(rng.nextInt(maxInt)); entry.position(0); entries.add(entry.array()); entriesSize.add(entry.array().length); lh.asyncAddEntry(entry.array(), this, sync); /* * Check that the difference is no larger than the throttling threshold */ int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } // wait for all entries to be acknowledged synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.debug("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** WRITE COMPLETE ***"); // close ledger lh.close(); // *** WRITING PART COMPLETE // READ PART BEGINS *** // open ledger lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); // read entries sync.counter = 0; for (int i = 0; i < numEntriesToWrite; i+=throttle) { lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); int testValue = getAvailablePermits(lh); assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); } synchronized (sync) { while (sync.counter < numEntriesToWrite) { LOG.info("Entries counter = " + sync.counter); sync.wait(); } } LOG.debug("*** READ COMPLETE ***"); lh.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); Enumeration<LedgerEntry> ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } }
#vulnerable code @Test public void testMultiLedger() throws IOException { try { // Create a ledger lh = bkc.createLedger(digestType, ledgerPassword); lh2 = bkc.createLedger(digestType, ledgerPassword); long ledgerId = lh.getId(); long ledgerId2 = lh2.getId(); // bkc.initMessageDigest("SHA1"); LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); for (int i = 0; i < numEntriesToWrite; i++) { lh.addEntry(new byte[0]); lh2.addEntry(new byte[0]); } lh.close(); lh2.close(); lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh .getLastAddConfirmed() == (numEntriesToWrite - 1)); assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 .getLastAddConfirmed() == (numEntriesToWrite - 1)); ls = lh.readEntries(0, numEntriesToWrite - 1); int i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh.close(); ls = lh2.readEntries(0, numEntriesToWrite - 1); i = 0; while (ls.hasMoreElements()) { ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); LOG.debug("Length of result: " + result.capacity()); assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); } lh2.close(); } catch (BKException e) { LOG.error("Test failed", e); fail("Test failed due to BookKeeper exception"); } catch (InterruptedException e) { LOG.error("Test failed", e); fail("Test failed due to interruption"); } } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { if (this.enabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } } } else { return joinPoint.proceed(); } }
#vulnerable code @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { if (this.isEnabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } } } else { return joinPoint.proceed(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object eval(final String js) { try { Object _xblockexpression = null; { this.assertScriptEngine(); if (((this.maxCPUTimeInMs).longValue() == 0)) { if (this.debug) { InputOutput.<String>println("--- Running JS ---"); InputOutput.<String>println(js); InputOutput.<String>println("--- JS END ---"); } return this.scriptEngine.eval(js); } Object _xsynchronizedexpression = null; synchronized (this) { Object _xblockexpression_1 = null; { final Value<Object> resVal = new Value<Object>(null); final Value<Throwable> exceptionVal = new Value<Throwable>(null); final MonitorThread monitorThread = new MonitorThread(((this.maxCPUTimeInMs).longValue() * 1000000)); if ((this.exectuor == null)) { throw new IllegalStateException( "When a CPU time limit is set, an executor needs to be provided by calling .setExecutor(...)"); } final Object monitor = new Object(); final Runnable _function = new Runnable() { @Override public void run() { try { boolean _contains = js.contains("intCheckForInterruption"); if (_contains) { throw new IllegalArgumentException( "Script contains the illegal string [intCheckForInterruption]"); } Object _eval = NashornSandboxImpl.this.scriptEngine.eval("window.js_beautify;"); final ScriptObjectMirror jsBeautify = ((ScriptObjectMirror) _eval); Object _call = jsBeautify.call("beautify", js); final String beautifiedJs = ((String) _call); Random _random = new Random(); int _nextInt = _random.nextInt(); final int randomToken = Math.abs(_nextInt); StringConcatenation _builder = new StringConcatenation(); _builder.append("var InterruptTest = Java.type(\'"); String _name = InterruptTest.class.getName(); _builder.append(_name, ""); _builder.append("\');"); _builder.newLineIfNotEmpty(); _builder.append("var isInterrupted = InterruptTest.isInterrupted;"); _builder.newLine(); _builder.append("var intCheckForInterruption"); _builder.append(randomToken, ""); _builder.append(" = function() {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("if (isInterrupted()) {"); _builder.newLine(); _builder.append("\t "); _builder.append("throw new Error(\'Interrupted"); _builder.append(randomToken, "\t "); _builder.append("\')"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("}"); _builder.newLine(); _builder.append("};"); _builder.newLine(); String preamble = _builder.toString(); String _replace = preamble.replace("\n", ""); preamble = _replace; String _injectInterruptionCalls = NashornSandboxImpl.injectInterruptionCalls(beautifiedJs, randomToken); final String securedJs = (preamble + _injectInterruptionCalls); final Thread mainThread = Thread.currentThread(); Thread _currentThread = Thread.currentThread(); monitorThread.setThreadToMonitor(_currentThread); final Runnable _function = new Runnable() { @Override public void run() { mainThread.interrupt(); } }; monitorThread.setOnInvalidHandler(_function); monitorThread.start(); try { if (NashornSandboxImpl.this.debug) { InputOutput.<String>println("--- Running JS ---"); InputOutput.<String>println(securedJs); InputOutput.<String>println("--- JS END ---"); } final Object res = NashornSandboxImpl.this.scriptEngine.eval(securedJs); resVal.set(res); } catch (final Throwable _t) { if (_t instanceof ScriptException) { final ScriptException e = (ScriptException)_t; String _message = e.getMessage(); boolean _contains_1 = _message.contains(("Interrupted" + Integer.valueOf(randomToken))); if (_contains_1) { monitorThread.notifyOperationInterrupted(); } else { exceptionVal.set(e); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } return; } } else { throw Exceptions.sneakyThrow(_t); } } finally { monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } } catch (final Throwable _t_1) { if (_t_1 instanceof Throwable) { final Throwable t = (Throwable)_t_1; exceptionVal.set(t); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } else { throw Exceptions.sneakyThrow(_t_1); } } } }; this.exectuor.execute(_function); synchronized (monitor) { monitor.wait(); } boolean _isCPULimitExceeded = monitorThread.isCPULimitExceeded(); if (_isCPULimitExceeded) { String notGraceful = ""; boolean _gracefullyInterrputed = monitorThread.gracefullyInterrputed(); boolean _not = (!_gracefullyInterrputed); if (_not) { notGraceful = " The operation could not be gracefully interrupted."; } Throwable _get = exceptionVal.get(); throw new ScriptCPUAbuseException( ((("Script used more than the allowed [" + this.maxCPUTimeInMs) + " ms] of CPU time. ") + notGraceful), _get); } Throwable _get_1 = exceptionVal.get(); boolean _tripleNotEquals = (_get_1 != null); if (_tripleNotEquals) { throw exceptionVal.get(); } _xblockexpression_1 = resVal.get(); } _xsynchronizedexpression = _xblockexpression_1; } _xblockexpression = _xsynchronizedexpression; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
#vulnerable code @Override public Object eval(final String js) { try { Object _xblockexpression = null; { this.assertScriptEngine(); if (((this.maxCPUTimeInMs).longValue() == 0)) { return this.scriptEngine.eval(js); } Object _xsynchronizedexpression = null; synchronized (this) { Object _xblockexpression_1 = null; { final Value<Object> resVal = new Value<Object>(null); final Value<Throwable> exceptionVal = new Value<Throwable>(null); final MonitorThread monitorThread = new MonitorThread(((this.maxCPUTimeInMs).longValue() * 1000000)); if ((this.exectuor == null)) { throw new IllegalStateException( "When a CPU time limit is set, an executor needs to be provided by calling .setExecutor(...)"); } final Object monitor = new Object(); final Runnable _function = new Runnable() { @Override public void run() { try { boolean _contains = js.contains("intCheckForInterruption"); if (_contains) { throw new IllegalArgumentException( "Script contains the illegal string [intCheckForInterruption]"); } Object _eval = NashornSandboxImpl.this.scriptEngine.eval("window.js_beautify;"); final ScriptObjectMirror jsBeautify = ((ScriptObjectMirror) _eval); Object _call = jsBeautify.call("beautify", js); final String beautifiedJs = ((String) _call); Random _random = new Random(); int _nextInt = _random.nextInt(); final int randomToken = Math.abs(_nextInt); StringConcatenation _builder = new StringConcatenation(); _builder.append("var InterruptTest = Java.type(\'"); String _name = InterruptTest.class.getName(); _builder.append(_name, ""); _builder.append("\');"); _builder.newLineIfNotEmpty(); _builder.append("var isInterrupted = InterruptTest.isInterrupted;"); _builder.newLine(); _builder.append("var intCheckForInterruption"); _builder.append(randomToken, ""); _builder.append(" = function() {"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("if (isInterrupted()) {"); _builder.newLine(); _builder.append("\t "); _builder.append("throw new Error(\'Interrupted"); _builder.append(randomToken, "\t "); _builder.append("\')"); _builder.newLineIfNotEmpty(); _builder.append("\t"); _builder.append("}"); _builder.newLine(); _builder.append("};"); _builder.newLine(); String preamble = _builder.toString(); String _replace = preamble.replace("\n", ""); preamble = _replace; String _injectInterruptionCalls = NashornSandboxImpl.injectInterruptionCalls(beautifiedJs, randomToken); final String securedJs = (preamble + _injectInterruptionCalls); final Thread mainThread = Thread.currentThread(); Thread _currentThread = Thread.currentThread(); monitorThread.setThreadToMonitor(_currentThread); final Runnable _function = new Runnable() { @Override public void run() { mainThread.interrupt(); } }; monitorThread.setOnInvalidHandler(_function); monitorThread.start(); try { if (NashornSandboxImpl.this.debug) { InputOutput.<String>println("--- Running JS ---"); InputOutput.<String>println(securedJs); InputOutput.<String>println("--- JS END ---"); } final Object res = NashornSandboxImpl.this.scriptEngine.eval(securedJs); resVal.set(res); } catch (final Throwable _t) { if (_t instanceof ScriptException) { final ScriptException e = (ScriptException)_t; String _message = e.getMessage(); boolean _contains_1 = _message.contains(("Interrupted" + Integer.valueOf(randomToken))); if (_contains_1) { monitorThread.notifyOperationInterrupted(); } else { exceptionVal.set(e); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } return; } } else { throw Exceptions.sneakyThrow(_t); } } finally { monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } } catch (final Throwable _t_1) { if (_t_1 instanceof Throwable) { final Throwable t = (Throwable)_t_1; exceptionVal.set(t); monitorThread.stopMonitor(); synchronized (monitor) { monitor.notify(); } } else { throw Exceptions.sneakyThrow(_t_1); } } } }; this.exectuor.execute(_function); synchronized (monitor) { monitor.wait(); } boolean _isCPULimitExceeded = monitorThread.isCPULimitExceeded(); if (_isCPULimitExceeded) { String notGraceful = ""; boolean _gracefullyInterrputed = monitorThread.gracefullyInterrputed(); boolean _not = (!_gracefullyInterrputed); if (_not) { notGraceful = " The operation could not be gracefully interrupted."; } Throwable _get = exceptionVal.get(); throw new ScriptCPUAbuseException( ((("Script used more than the allowed [" + this.maxCPUTimeInMs) + " ms] of CPU time. ") + notGraceful), _get); } Throwable _get_1 = exceptionVal.get(); boolean _tripleNotEquals = (_get_1 != null); if (_tripleNotEquals) { throw exceptionVal.get(); } _xblockexpression_1 = resVal.get(); } _xsynchronizedexpression = _xblockexpression_1; } _xblockexpression = _xsynchronizedexpression; } return _xblockexpression; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void callOnError(final ExecutionError error) { if (onError != null) { onError.call(error); } callOnTerminate((C) error.getContext()); }
#vulnerable code protected void callOnError(final ExecutionError error) { if (onError != null) { onError.call(error); } synchronized (error.getContext()) { callOnTerminate((C) error.getContext()); error.getContext().notifyAll(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } callOnTerminate(context); } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } }
#vulnerable code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } synchronized (context) { callOnTerminate(context); context.notifyAll(); } } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } callOnTerminate(context); } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } }
#vulnerable code protected void callOnFinalState(final State<C> state, final C context) { try { if (onFinalStateHandler != null) { if (isTrace()) log.debug("when final state {} for {} <<<", state, context); onFinalStateHandler.call(state, context); if (isTrace()) log.debug("when final state {} for {} >>>", state, context); } synchronized (context) { callOnTerminate(context); context.notifyAll(); } } catch (Exception e) { callOnError(new ExecutionError(state, null, e, "Execution Error in [EasyFlow.whenFinalState] handler", context)); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @GET @Path("/result_counter/{identifier}") @Produces("application/json") public EnumMap<ResultType, Integer> getCounterResults(@PathParam("identifier") String executionIdentifier) { try { return this.resultCounts.get(executionIdentifier); } catch (Exception e) { throw new WebException("Could not find any progress to the given identifier", Response.Status.BAD_REQUEST); } }
#vulnerable code @GET @Path("/result_counter/{identifier}") @Produces("application/json") public EnumMap<ResultType, Integer> getCounterResults(@PathParam("identifier") String executionIdentifier) { try { return AlgorithmExecutionCache.getResultCounter(executionIdentifier).getResults(); } catch (Exception e) { throw new WebException("Could not find any progress to the given identifier", Response.Status.BAD_REQUEST); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { LinkedList<ResultPrinter> resultPrinters = new LinkedList<ResultPrinter>(); FunctionalDependencyPrinter fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(fdResultReceiver); InclusionDependencyPrinter indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(indResultReceiver); UniqueColumnCombinationPrinter uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(uccResultReceiver); FileGenerator fileGenerator = new TempFileGenerator(); AlgorithmExecutor executor = new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); currentResultPrinters.put(algorithmName, resultPrinters); return executor; }
#vulnerable code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { FunctionalDependencyResultReceiver fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); InclusionDependencyResultReceiver indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); UniqueColumnCombinationResultReceiver uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); FileGenerator fileGenerator = new TempFileGenerator(); return new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void executeUniqueColumnCombinationsAlgorithmTest() { // Setup List<ConfigurationValue> configs = new ArrayList<ConfigurationValue>(); configs.add(new ConfigurationValueString("pathToInputFile", "blub")); UniqueColumnCombinationResultReceiver resultReceiver = mock(UniqueColumnCombinationFileWriter.class); // Execute executer.executeUniqueColumnCombinationsAlgorithm("example_algorithm-0.0.1-SNAPSHOT-jar-with-dependencies.jar", configs, resultReceiver); // Check result verify(resultReceiver).receiveResult(isA(ColumnCombination.class)); }
#vulnerable code @Test public void executeUniqueColumnCombinationsAlgorithmTest() { // Setup AlgorithmExecuter executer = new AlgorithmExecuter(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); List<ConfigurationValue> configs = new ArrayList<ConfigurationValue>(); configs.add(new ConfigurationValueString("pathToInputFile", "blub")); // Expected values ColumnCombination columnCombination = new ColumnCombination( new ColumnIdentifier("table1", "column1"), new ColumnIdentifier("table2", "column2")); // Execute executer.executeUniqueColumnCombinationsAlgorithm("example_algorithm-0.0.1-SNAPSHOT-jar-with-dependencies.jar", configs, new UniqueColumnCombinationPrinter(new PrintStream(outStream))); // Check result assertTrue(outStream.toString().contains(columnCombination.toString())); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
#vulnerable code @Test public void testGenerateNewCsvFile() throws IOException { // Setup SimpleRelationalInput csv = generator.generateNewCsvFile(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCsvFile(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void receiveResult(ColumnCombination columnCombination) { appendToResultFile(columnCombination.toString()); }
#vulnerable code @Override public void receiveResult(ColumnCombination columnCombination) { try { FileWriter writer = new FileWriter(this.file, true); writer.write(columnCombination.toString() + "\n"); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { LinkedList<ResultPrinter> resultPrinters = new LinkedList<ResultPrinter>(); FunctionalDependencyPrinter fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(fdResultReceiver); InclusionDependencyPrinter indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(indResultReceiver); UniqueColumnCombinationPrinter uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); resultPrinters.add(uccResultReceiver); FileGenerator fileGenerator = new TempFileGenerator(); AlgorithmExecutor executor = new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); currentResultPrinters.put(algorithmName, resultPrinters); return executor; }
#vulnerable code protected AlgorithmExecutor buildExecutor(String algorithmName) throws FileNotFoundException, UnsupportedEncodingException { FunctionalDependencyResultReceiver fdResultReceiver = new FunctionalDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); InclusionDependencyResultReceiver indResultReceiver = new InclusionDependencyPrinter(getResultFileName(algorithmName), getResultDirectoryName()); UniqueColumnCombinationResultReceiver uccResultReceiver = new UniqueColumnCombinationPrinter(getResultFileName(algorithmName), getResultDirectoryName()); FileGenerator fileGenerator = new TempFileGenerator(); return new AlgorithmExecutor(fdResultReceiver, indResultReceiver, uccResultReceiver, fileGenerator); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
#vulnerable code @Test public void testGenerateNewCsvFile() throws IOException { // Setup SimpleRelationalInput csv = generator.generateNewCsvFile(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCsvFile(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T loadAlgorithm(String path) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException { String pathToFolder = ClassLoader.getSystemResource("algorithms").getPath(); File file = new File(URLDecoder.decode(pathToFolder + "/" + path, "utf-8")); JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, algorithmSubclass.getClassLoader()); Class<? extends T> algorithmClass = Class.forName(className, true, loader).asSubclass(algorithmSubclass); jar.close(); return algorithmClass.getConstructor().newInstance(); }
#vulnerable code public T loadAlgorithm(String path) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException { String pathToFolder = ClassLoader.getSystemResource("algorithms").getPath(); File file = new File(URLDecoder.decode(pathToFolder + "/" + path, "utf-8")); JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, algorithmSubclass.getClassLoader()); Class<? extends T> algorithmClass = Class.forName(className, true, loader).asSubclass(algorithmSubclass); return algorithmClass.getConstructor().newInstance(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAddAlgorithm() throws EntityStorageException, AlgorithmLoadingException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); }
#vulnerable code @Test public void testAddAlgorithm() throws EntityStorageException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("someFileName.jar"); algorithm.setInd(true); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void executeAlgorithm(String algorithmName, List<InputParameter> parameters) throws AlgorithmConfigurationException, AlgorithmLoadingException, AlgorithmExecutionException { List<ConfigurationValue> configs = convertInputParameters(parameters); AlgorithmExecutor executor = null; try { executor = buildExecutor(algorithmName); } catch (FileNotFoundException e) { throw new AlgorithmExecutionException("Could not generate result file."); } catch (UnsupportedEncodingException e) { throw new AlgorithmExecutionException("Could not build temporary file generator."); } System.out.println("before execution"); executor.executeAlgorithm(algorithmName, configs); System.out.println("after execution & wait"); }
#vulnerable code @Override public void executeAlgorithm(String algorithmName, List<InputParameter> parameters) throws AlgorithmConfigurationException, AlgorithmLoadingException, AlgorithmExecutionException { List<ConfigurationValue> configs = convertInputParameters(parameters); try { buildExecutor(algorithmName).executeAlgorithm(algorithmName, configs); } catch (FileNotFoundException e) { throw new AlgorithmExecutionException("Could not generate result file."); } catch (UnsupportedEncodingException e) { throw new AlgorithmExecutionException("Could not build temporary file generator."); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ConfigurationSettingCsvFile getValues() throws InputValidationException { String selectedValue = this.listbox.getSelectedValue(); if (selectedValue.equals("--")) { throw new InputValidationException("You must choose a CSV file!"); } FileInput currentFileInput = this.fileInputs.get(selectedValue); return getCurrentSetting(currentFileInput); }
#vulnerable code public ConfigurationSettingCsvFile getValues() { if (this.listbox.getSelectedValue().equals("--")) { this.messageReceiver.addError("You must choose a CSV file!"); return null; } FileInput currentFileInput = this.fileInputs.get( this.listbox.getSelectedValue()); return getCurrentSetting(currentFileInput); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, InputIterationException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
#vulnerable code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testUpdateOnSuccess() { // Set up TestHelper.resetDatabaseSync(); Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); Execution execution = new Execution(algorithm, 12); execution.setEnd(2345); BasePage parent = new BasePage(); ResultsPage page = new ResultsPage(parent); page.setMessageReceiver(new TabWrapper()); page.setExecutionParameter("identifier", "name"); page.startPolling(true); // Expected Values // Execute page.updateOnSuccess(execution); // Check assertEquals(2, page.getWidgetCount()); assertTrue(page.getWidget(1) instanceof TabLayoutPanel); assertEquals(2, ((TabLayoutPanel) page.getWidget(1)).getWidgetCount()); // Cleanup TestHelper.resetDatabaseSync(); }
#vulnerable code public void testUpdateOnSuccess() { // Set up TestHelper.resetDatabaseSync(); Execution execution = new Execution(null, 12); execution.setEnd(2345); BasePage parent = new BasePage(); ResultsPage page = new ResultsPage(parent); page.setMessageReceiver(new TabWrapper()); page.setExecutionParameter("identifier", "name"); page.startPolling(true); // Expected Values // Execute page.updateOnSuccess(null); // Check assertEquals(2, page.getWidgetCount()); assertTrue(page.getWidget(1) instanceof TabLayoutPanel); assertEquals(2, ((TabLayoutPanel) page.getWidget(1)).getWidgetCount()); // Cleanup TestHelper.resetDatabaseSync(); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Result> fetchNewResults(String algorithmName){ List<Result> newResults = new LinkedList<Result>(); //newResults.add(currentResultReceivers.get(algorithmName).getNewResults()); newResults.add(new UniqueColumnCombination(new ColumnIdentifier("table", "col1"))); return newResults; }
#vulnerable code public List<Result> fetchNewResults(String algorithmName){ List<Result> newResults = new LinkedList<Result>(); for (ResultPrinter printer : currentResultPrinters.get(algorithmName)) { // newResults.addAll(printer.getNewResults()); } newResults.add(new UniqueColumnCombination(new ColumnIdentifier("table", "col1"))); return newResults; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAddAlgorithm() throws EntityStorageException, AlgorithmLoadingException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); }
#vulnerable code @Test public void testAddAlgorithm() throws EntityStorageException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("someFileName.jar"); algorithm.setInd(true); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Class<?>> getAlgorithmInterfaces(File file) throws IOException, ClassNotFoundException { JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader()); Class<?> algorithmClass = Class.forName(className, false, loader); jar.close(); return Arrays.asList(algorithmClass.getInterfaces()); }
#vulnerable code public List<Class<?>> getAlgorithmInterfaces(File file) throws IOException, ClassNotFoundException { JarFile jar = new JarFile(file); Manifest man = jar.getManifest(); Attributes attr = man.getMainAttributes(); String className = attr.getValue(bootstrapClassTagName); URL[] url = {file.toURI().toURL()}; ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader()); Class<?> algorithmClass = Class.forName(className, false, loader); return Arrays.asList(algorithmClass.getInterfaces()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, InputIterationException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); }
#vulnerable code @Test public void testGenerateNewCsvFile() throws SimpleRelationalInputGenerationException, IOException { // Setup SimpleRelationalInput csv = generator.generateNewCopy(); // Check result // The csv should contain both lines and iterate through them with next. assertEquals(csvFileFixture.expectedFirstLine(), csv.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv.next()); // A new CsvFile should iterate from the start. SimpleRelationalInput csv2 = generator.generateNewCopy(); assertEquals(csvFileFixture.expectedFirstLine(), csv2.next()); assertEquals(csvFileFixture.expectedSecondLine(), csv2.next()); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected AlgorithmExecutor buildExecutor(String executionIdentifier) throws FileNotFoundException, UnsupportedEncodingException { ResultPrinter resultPrinter = new ResultPrinter(executionIdentifier); ResultsCache resultsCache = new ResultsCache(); ResultsHub resultsHub = new ResultsHub(); resultsHub.addSubscriber(resultPrinter); resultsHub.addSubscriber(resultsCache); FileGenerator fileGenerator = new TempFileGenerator(); ProgressCache progressCache = new ProgressCache(); AlgorithmExecutor executor = new AlgorithmExecutor(resultsHub, progressCache, fileGenerator); executor.setResultPathPrefix(resultPrinter.getOutputFilePathPrefix()); AlgorithmExecutionCache.add(executionIdentifier, resultsCache, progressCache); return executor; }
#vulnerable code protected AlgorithmExecutor buildExecutor(String executionIdentifier) throws FileNotFoundException, UnsupportedEncodingException { ResultPrinter resultPrinter = new ResultPrinter(executionIdentifier, "results"); ResultsCache resultsCache = new ResultsCache(); ResultsHub resultsHub = new ResultsHub(); resultsHub.addSubscriber(resultPrinter); resultsHub.addSubscriber(resultsCache); FileGenerator fileGenerator = new TempFileGenerator(); ProgressCache progressCache = new ProgressCache(); AlgorithmExecutor executor = new AlgorithmExecutor(resultsHub, progressCache, fileGenerator); AlgorithmExecutionCache.add(executionIdentifier, resultsCache, progressCache); return executor; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStoreTableInput() throws EntityStorageException, InputValidationException { // Setup TestHelper.resetDatabaseSync(); final boolean[] blocked = {true}; BasePage parent = new BasePage(); InputConfigurationPage page = new InputConfigurationPage(parent); page.setErrorReceiver(new TabWrapper()); DatabaseConnection dbConnection = new DatabaseConnection(); dbConnection.setUrl("url"); dbConnection.setPassword("password"); dbConnection.setUsername("db"); TestHelper.storeDatabaseConnectionSync(dbConnection); page.tableInputField.setValues("1: url", "table"); page.tableInputFieldSelected = true; page.dbFieldSelected = false; page.fileInputFieldSelected = false; page.content.clear(); page.content.add(page.tableInputField); // Execute page.saveObject(); // Expected values final TableInput expectedInput = page.tableInputField.getValue(); // Check result TestHelper.getAllTableInputs( new AsyncCallback<List<TableInput>>() { @Override public void onFailure(Throwable throwable) { fail(); } @Override public void onSuccess(List<TableInput> con) { blocked[0] = false; assertTrue(con.contains(expectedInput)); } }); Timer rpcCheck = new Timer() { @Override public void run() { if (blocked[0]) { this.schedule(100); } } }; rpcCheck.schedule(100); // Cleanup TestHelper.resetDatabaseSync(); }
#vulnerable code @Test public void testStoreTableInput() throws EntityStorageException, InputValidationException { // Setup TestHelper.resetDatabaseSync(); BasePage parent = new BasePage(); InputConfigurationPage page = new InputConfigurationPage(parent); page.setErrorReceiver(new TabWrapper()); DatabaseConnection dbConnection = new DatabaseConnection(); dbConnection.setId(1); dbConnection.setUrl("url"); dbConnection.setPassword("password"); dbConnection.setUsername("db"); TestHelper.storeDatabaseConnectionSync(dbConnection); page.tableInputField.setValues("1: url", "table"); page.tableInputFieldSelected = true; page.dbFieldSelected = false; page.fileInputFieldSelected = false; page.content.clear(); page.content.add(page.tableInputField); // Execute page.saveObject(); // Expected values TableInput expectedInput = page.tableInputField.getValue(); // Check result assertTrue(TestHelper.getAllTableInputs().contains(expectedInput)); // Cleanup TestHelper.resetDatabaseSync(); } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNextSeparator() throws InputIterationException { // Setup CsvFileOneLineFixture fixtureSeparator = new CsvFileOneLineFixture(';'); CsvFile csvFileSeparator = fixtureSeparator.getTestData(); // Check result assertEquals(fixtureSeparator.getExpectedStrings(), csvFileSeparator.next()); }
#vulnerable code @Test public void testNextSeparator() throws IOException { // Setup CsvFileOneLineFixture fixtureSeparator = new CsvFileOneLineFixture(';'); CsvFile csvFileSeparator = fixtureSeparator.getTestData(); // Check result assertEquals(fixtureSeparator.getExpectedStrings(), csvFileSeparator.next()); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAddAlgorithm() throws EntityStorageException, AlgorithmLoadingException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("example_ind_algorithm.jar"); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); }
#vulnerable code @Test public void testAddAlgorithm() throws EntityStorageException { // Setup HibernateUtil.clear(); AlgorithmServiceImpl finderService = new AlgorithmServiceImpl(); // Execute functionality: add an IND algorithm Algorithm algorithm = new Algorithm("someFileName.jar"); algorithm.setInd(true); finderService.addAlgorithm(algorithm); // Check result assertTrue(finderService.listAllAlgorithms().contains(algorithm)); assertTrue( finderService.listAlgorithms(InclusionDependencyAlgorithm.class).contains(algorithm)); assertFalse(finderService.listAlgorithms(FunctionalDependencyAlgorithm.class).contains( algorithm)); // Cleanup HibernateUtil.clear(); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<OperationArgument> buildResolverArguments(ArgumentBuilderParams params) { Method resolverMethod = params.getResolverMethod(); List<OperationArgument> operationArguments = new ArrayList<>(resolverMethod.getParameterCount()); AnnotatedType[] parameterTypes = ClassUtils.getParameterTypes(resolverMethod, params.getDeclaringType()); for (int i = 0; i < resolverMethod.getParameterCount(); i++) { Parameter parameter = resolverMethod.getParameters()[i]; if (parameter.isSynthetic() || parameter.isImplicit()) continue; AnnotatedType parameterType; try { parameterType = params.getTypeTransformer().transform(parameterTypes[i]); } catch (TypeMappingException e) { throw new TypeMappingException(resolverMethod, parameter, e); } operationArguments.add(buildResolverArgument(parameter, parameterType, params.getInclusionStrategy(), params.getEnvironment())); } return operationArguments; }
#vulnerable code @Override public List<OperationArgument> buildResolverArguments(ArgumentBuilderParams params) { Method resolverMethod = params.getResolverMethod(); List<OperationArgument> operationArguments = new ArrayList<>(resolverMethod.getParameterCount()); AnnotatedType[] parameterTypes = ClassUtils.getParameterTypes(resolverMethod, params.getDeclaringType()); for (int i = 0; i < resolverMethod.getParameterCount(); i++) { Parameter parameter = resolverMethod.getParameters()[i]; if (parameter.isSynthetic() || parameter.isImplicit()) continue; AnnotatedType parameterType; try { parameterType = params.getTypeTransformer().transform(parameterTypes[i]); } catch (TypeMappingException e) { throw new TypeMappingException(resolverMethod, parameter, e); } parameterType = ClassUtils.addAnnotations(parameterType, parameter.getAnnotations()); operationArguments.add(buildResolverArgument(parameter, parameterType, params.getInclusionStrategy(), params.getEnvironment())); } return operationArguments; } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<OperationArgument> buildResolverArguments(ArgumentBuilderParams params) { Method resolverMethod = params.getResolverMethod(); List<OperationArgument> operationArguments = new ArrayList<>(resolverMethod.getParameterCount()); AnnotatedType[] parameterTypes = ClassUtils.getParameterTypes(resolverMethod, params.getDeclaringType()); for (int i = 0; i < resolverMethod.getParameterCount(); i++) { Parameter parameter = resolverMethod.getParameters()[i]; if (parameter.isSynthetic() || parameter.isImplicit()) continue; AnnotatedType parameterType; try { parameterType = params.getTypeTransformer().transform(parameterTypes[i]); } catch (TypeMappingException e) { throw new TypeMappingException(resolverMethod, parameter, e); } parameterType = ClassUtils.addAnnotations(parameterType, parameter.getAnnotations()); operationArguments.add(buildResolverArgument(parameter, parameterType, params.getInclusionStrategy())); } return operationArguments; }
#vulnerable code @Override public List<OperationArgument> buildResolverArguments(ArgumentBuilderParams params) { Method resolverMethod = params.getResolverMethod(); List<OperationArgument> operationArguments = new ArrayList<>(resolverMethod.getParameterCount()); AnnotatedType[] parameterTypes = ClassUtils.getParameterTypes(resolverMethod, params.getDeclaringType()); for (int i = 0; i < resolverMethod.getParameterCount(); i++) { Parameter parameter = resolverMethod.getParameters()[i]; if (parameter.isSynthetic() || parameter.isImplicit()) continue; AnnotatedType parameterType; try { parameterType = params.getTypeTransformer().transform(parameterTypes[i]); } catch (TypeMappingException e) { throw new TypeMappingException(resolverMethod, parameter, e); } parameterType = ClassUtils.addAnnotations(parameterType, parameter.getAnnotations()); operationArguments.add(new OperationArgument( parameterType, getArgumentName(parameter, parameterType, params.getInclusionStrategy()), getArgumentDescription(parameter, parameterType), defaultValue(parameter, parameterType), parameter, parameter.isAnnotationPresent(GraphQLContext.class), params.getInclusionStrategy().includeArgument(parameter, parameterType) )); } return operationArguments; } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConflictingConnections() { try (TestLog log = new TestLog(OperationMapper.class)) { new TestSchemaGenerator() .withOperationsFromSingleton(new ConflictingBookService()) .generate(); assertWarningsLogged(log.getEvents(), Urls.Errors.NON_UNIQUE_TYPE_NAME); } }
#vulnerable code @Test public void testConflictingConnections() { try (TestLog log = new TestLog(OperationMapper.class)) { new TestSchemaGenerator() .withOperationsFromSingleton(new ConflictingBookService()) .generate(); assertEquals(1, log.getEvents().size()); ILoggingEvent event = log.getEvents().get(0); assertThat(event.getLevel(), is(Level.WARN)); assertThat(event.getMessage(), containsString(Urls.Errors.NON_UNIQUE_TYPE_NAME)); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void startDb() { postgres = new MyPostgreSQLContainer() .withDatabaseName(TEST_SCHEMA_NAME) .withUsername("SA") .withPassword("pass") .withLogConsumer(new Consumer<OutputFrame>() { @Override public void accept(OutputFrame outputFrame) { logger.debug(outputFrame.getUtf8String()); } }); postgres.start(); }
#vulnerable code public void startDb() { postgres = (PostgreSQLContainer) new PostgreSQLContainer() .withDatabaseName(TEST_SCHEMA_NAME) .withUsername("SA") .withPassword("pass") .withLogConsumer(new Consumer<OutputFrame>() { @Override public void accept(OutputFrame outputFrame) { logger.debug(outputFrame.getUtf8String()); } }); postgres.start(); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { long st = System.currentTimeMillis(); //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); ByteBuf content = dp.content(); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); // conv应该在客户端第一次建立时获取 int conv = content.getIntLE(0); ku.setConv(conv); ku.setMinRto(minRto); ku.setStream(stream); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(content); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { if (ku.isClosed()) { temp = ku; } else { ku.update(); } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } if (inputs.isEmpty())//如果输入为空则考虑wait { long end = System.currentTimeMillis(); if (end - st < this.interval) { synchronized (this.lock) { try { lock.wait(interval - end + st); } catch (InterruptedException e) { } } } } } release(); }
#vulnerable code @Override public void run() { while (this.running) { long st = System.currentTimeMillis(); //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setConv(conv); ku.setMinRto(minRto); ku.setStream(stream); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { if (ku.isClosed()) { temp = ku; } else { ku.update(); } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } if (inputs.isEmpty())//如果输入为空则考虑wait { long end = System.currentTimeMillis(); if (end - st < this.interval) { synchronized (this.lock) { try { lock.wait(interval - end + st); } catch (InterruptedException e) { } } } } } release(); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { long st = System.currentTimeMillis(); //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setConv(conv); ku.setMinRto(minRto); ku.setStream(stream); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { if (ku.isClosed()) { temp = ku; } else { ku.update(); } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } if (inputs.isEmpty())//如果输入为空则考虑wait { long end = System.currentTimeMillis(); if (end - st < this.interval) { synchronized (this.lock) { try { lock.wait(interval - end + st); } catch (InterruptedException e) { } } } } } release(); }
#vulnerable code @Override public void run() { while (this.running) { long st = System.currentTimeMillis(); //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setConv(conv); ku.setOrder(order); ku.setMinRto(minRto); ku.setStream(stream); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { if (ku.isClosed()) { temp = ku; } else { ku.update(); } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } if (inputs.isEmpty())//如果输入为空则考虑wait { long end = System.currentTimeMillis(); if (end - st < this.interval) { synchronized (this.lock) { try { lock.wait(interval - end + st); } catch (InterruptedException e) { } } } } } release(); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (running) { if (this.kcp.isClosed()) { this.running = false; continue; } this.kcp.update(); if (this.kcp.needUpdate()) { continue; } synchronized (waitLock) { try { waitLock.wait(this.interval); } catch (Exception ex) { System.out.println("error.........."); } } } nioEventLoopGroup.shutdownGracefully(); this.channel.close(); }
#vulnerable code @Override public void run() { while (running) { if (this.kcp.isClosed()) { this.running = false; continue; } long st = System.currentTimeMillis(); this.kcp.update(); if (this.kcp.needUpdate()) { continue; } long end = System.currentTimeMillis(); while ((end - st) < this.interval) { synchronized (waitLock) { try { waitLock.wait(this.interval - end + st); } catch (Exception ex) { } } break; } } nioEventLoopGroup.shutdownGracefully(); this.channel.close(); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); } ku.input(dp.content()); } //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) { temp = ku; } } if (temp != null)//删掉过时的kcp { this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); } try { Thread.sleep(this.interval); } catch (InterruptedException ex) { } } }
#vulnerable code @Override public void run() { while (this.running) { //input while (!this.inputs.isEmpty()) { DatagramPacket dp = this.inputs.remove(); KcpOnUdp ku = this.kcps.get(dp.sender()); if (ku == null) { ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 ku.noDelay(nodelay, interval, resend, nc); ku.wndSize(sndwnd, rcvwnd); ku.setMtu(mtu); ku.setTimeout(timeout); this.kcps.put(dp.sender(), ku); pqueue.add(ku); } ku.input(dp.content()); } //选出第一个kcp更新状态 KcpOnUdp first = pqueue.poll(); if(first != null && first.getTimeout() < System.currentTimeMillis()) { first.update(); if(!first.isClosed()) { pqueue.add(first); } else { this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); } } //每30s,更新一遍所有的kcp状态 if(System.currentTimeMillis()%(1000*30) == 0) { //update KcpOnUdp temp = null; for (KcpOnUdp ku : this.kcps.values()) { ku.update(); if (ku.isClosed()) {//删掉过时的kcp this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); pqueue.remove(ku); } } } //等待 try { synchronized(wakeup){ wakeup.wait(5*60*1000); } } catch (InterruptedException ex) { Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); } } } #location 43 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Instances createBootstrapSample(Instances instances) { Random rand = Random.getInstance(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < instances.size(); i++) { int idx = rand.nextInt(instances.size()); map.put(idx, map.getOrDefault(idx, 0) + 1); } Instances bag = new Instances(instances.getAttributes(), instances.getTargetAttribute(), map.size()); for (Integer idx : map.keySet()) { int weight = map.get(idx); Instance instance = instances.get(idx).clone(); instance.setWeight(weight); bag.add(instance); } return bag; }
#vulnerable code public static Instances createBootstrapSample(Instances instances) { Random rand = Random.getInstance(); Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < instances.size(); i++) { int idx = rand.nextInt(instances.size()); if (!map.containsKey(idx)) { map.put(idx, 0); } map.put(idx, map.get(idx) + 1); } Instances bag = new Instances(instances.getAttributes(), instances.getTargetAttribute(), map.size()); for (Integer idx : map.keySet()) { int weight = map.get(idx); Instance instance = instances.get(idx).clone(); instance.setWeight(weight); bag.add(instance); } return bag; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout = 60000) public void testCommitFailWhenTSOIsDown() throws Exception { Configuration clientConfiguration = getClientConfiguration(); clientConfiguration.setProperty(TSOClient.REQUEST_TIMEOUT_IN_MS_CONFKEY, 100); clientConfiguration.setProperty(TSOClient.REQUEST_MAX_RETRIES_CONFKEY, 10); TSOClient client = TSOClient.newBuilder().withConfiguration(clientConf).build(); long ts1 = client.createTransaction().get(); pauseTSO(); TSOFuture<Long> future = client.commit(ts1, Sets.newSet(c1, c2)); while(!isTsoBlockingRequest()) {} try { future.get(); } catch(ExecutionException e) { assertEquals("Should be a ServiceUnavailableExeption", ServiceUnavailableException.class, e.getCause().getClass()); } }
#vulnerable code @Test(timeout = 60000) public void testCommitFailWhenTSOIsDown() throws Exception { Configuration clientConfiguration = getClientConfiguration(); clientConfiguration.setProperty(TSOClient.REQUEST_TIMEOUT_IN_MS_CONFKEY, 100); clientConfiguration.setProperty(TSOClient.REQUEST_MAX_RETRIES_CONFKEY, 10); TSOClient client = TSOClient.newBuilder().withConfiguration(clientConf) .withCommitTableClient(getCommitTable().getClient().get()).build(); long ts1 = client.createTransaction().get(); pauseTSO(); TSOFuture<Long> future = client.commit(ts1, Sets.newSet(c1, c2)); while(!isTsoBlockingRequest()) {} try { future.get(); } catch(ExecutionException e) { assertEquals("Should be a ServiceUnavailableExeption", ServiceUnavailableException.class, e.getCause().getClass()); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.