input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Deprecated public static boolean addHotkey(char key, int modifiers, HotkeyListener listener) { return HotkeyManager.getInstance().addHotkey(key, modifiers, listener); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Deprecated public static boolean addHotkey(char key, int modifiers, HotkeyListener listener) { return Key.addHotkey(key, modifiers, listener); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { System.out.println("********** Running Sikulix.main"); int dl = RunTime.checkArgs(args, RunTime.Type.API); if (dl > -1) { testNumber = dl; Debug.on(3); } rt = RunTime.get(); testNumber = rt.getOptionNumber("testing.test", -1); if (testNumber > -1) { rt = RunTime.get(); if (!rt.testing) { rt.show(); rt.testing = true; } Tests.runTest(testNumber); System.exit(1); } else { rt = RunTime.get(); Debug.on(3); if (rt.runningWinApp) { popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName()); try { Screen scr = new Screen(); scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3); } catch (Exception ex) { popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName()); } popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName()); System.exit(1); } rt.terminate(1,"Sikulix::main: nothing to test"); } } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { System.out.println("********** Running Sikulix.main"); int dl = RunTime.checkArgs(args, RunTime.Type.API); if (dl > -1) { testNumber = dl; Debug.on(3); } rt = RunTime.get(); testNumber = rt.getOptionNumber("testing.test", -1); if (testNumber > -1) { rt = RunTime.get(); if (!rt.testing) { rt.show(); rt.testing = true; } Tests.runTest(testNumber); System.exit(1); } else { rt = RunTime.get(); Debug.on(3); String jythonJar = rt.SikuliLocalRepo + rt.SikuliJythonMaven; log(0, "%s", rt.fSxBaseJar); log(0, jythonJar); rt.addToClasspath(jythonJar); //addFromProject("API", "sikulixapi-1.1.0.jar"); // JythonHelper.get().addSysPath("/Users/raimundhocke/SikuliX/SikuliX-2014/API/target/classes/Lib"); //rt.dumpClassPath(); //Debug.on(4); SikulixForJython.get(); String stuff = rt.resourceListAsString("Lib/sikuli", null); if (rt.runningWinApp) { popup("Hello World\nNot much else to do ( yet ;-)", rt.fSxBaseJar.getName()); try { Screen scr = new Screen(); scr.find(new Image(scr.userCapture("grab something to find"))).highlight(3); } catch (Exception ex) { popup("Uuups :-(\n" + ex.getMessage(), rt.fSxBaseJar.getName()); } popup("Hello World\nNothing else to do ( yet ;-)", rt.fSxBaseJar.getName()); System.exit(1); } rt.terminate(1,"Sikulix::main: nothing to test"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean reparse() { File temp = FileManager.createTempFile("py"); Element e = this.getDocument().getDefaultRootElement(); if (e.getEndOffset() - e.getStartOffset() == 1) { return true; } try { writeFile(temp.getAbsolutePath()); this.read(new BufferedReader(new InputStreamReader(new FileInputStream(temp), "UTF8")), null); updateDocumentListeners(); return true; } catch (IOException ex) { } return false; } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public boolean reparse() { File temp = null; Element e = this.getDocument().getDefaultRootElement(); if (e.getEndOffset() - e.getStartOffset() == 1) { return true; } if ((temp = reparseBefore()) != null) { if (reparseAfter(temp)) { updateDocumentListeners(); return true; } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void clearCache(int maxSize) { Image first; while (images.size() > 0 && currentMemory > maxSize) { first = images.remove(0); first.bimg = null; currentMemory -= first.bsize; } if (maxSize == 0) { currentMemory = 0; } else { currentMemory = Math.max(0, currentMemory); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void clearCache(int maxSize) { currentMemoryChange(0, maxSize); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void runscript(String[] args) { if (isRunningScript) { log(-1, "can run only one script at a time!"); return; } IScriptRunner currentRunner = null; if (args != null && args.length > 1 && args[0].startsWith("-testSetup")) { currentRunner = getRunner(null, args[1]); if (currentRunner == null) { args[0] = null; } else { String[] stmts = new String[0]; if (args.length > 2) { stmts = new String[args.length - 2]; for (int i = 0; i < stmts.length; i++) { stmts[i] = args[i+2]; } } if (0 != currentRunner.runScript(null, null, stmts, null)) { args[0] = null; } } isRunningScript = false; return; } runScripts = Runner.evalArgs(args); isRunningScript = true; if (runTime.runningInteractive) { int exitCode = 0; if (currentRunner == null) { String givenRunnerName = runTime.interactiveRunner; if (givenRunnerName == null) { currentRunner = getRunner(null, Runner.RDEFAULT); } else { currentRunner = getRunner(null, givenRunnerName); } } if (currentRunner == null) { System.exit(1); } exitCode = currentRunner.runInteractive(runTime.getSikuliArgs()); currentRunner.close(); Sikulix.endNormal(exitCode); } if (runScripts.length > 0) { String scriptName = runScripts[0]; if (scriptName != null && !scriptName.isEmpty() && scriptName.startsWith("git*")) { run(scriptName, runTime.getSikuliArgs()); return; } } if (runScripts != null && runScripts.length > 0) { int exitCode = 0; runAsTest = runTime.runningTests; for (String givenScriptName : runScripts) { if (lastReturnCode == -1) { log(lvl, "Exit code -1: Terminating multi-script-run"); break; } exitCode = new RunBox(givenScriptName, runTime.getSikuliArgs(), runAsTest).run(); lastReturnCode = exitCode; } System.exit(exitCode); } } #location 51 #vulnerability type NULL_DEREFERENCE
#fixed code public static void runscript(String[] args) { if (isRunningScript) { log(-1, "can run only one script at a time!"); return; } IScriptRunner currentRunner = null; if (args != null && args.length > 1 && args[0].startsWith("-testSetup")) { currentRunner = getRunner(null, args[1]); if (currentRunner == null) { args[0] = null; } else { String[] stmts = new String[0]; if (args.length > 2) { stmts = new String[args.length - 2]; for (int i = 0; i < stmts.length; i++) { stmts[i] = args[i+2]; } } if (0 != currentRunner.runScript(null, null, stmts, null)) { args[0] = null; } } isRunningScript = false; return; } runScripts = Runner.evalArgs(args); isRunningScript = true; if (runTime.runningInteractive) { int exitCode = 0; if (currentRunner == null) { String givenRunnerName = runTime.interactiveRunner; if (givenRunnerName == null) { currentRunner = getRunner(null, Runner.RDEFAULT); } else { currentRunner = getRunner(null, givenRunnerName); } } if (currentRunner == null) { System.exit(1); } exitCode = currentRunner.runInteractive(runTime.getSikuliArgs()); currentRunner.close(); Sikulix.endNormal(exitCode); } if (runScripts == null) { runTime.terminate(1, "option -r without any script"); } if (runScripts.length > 0) { String scriptName = runScripts[0]; if (scriptName != null && !scriptName.isEmpty() && scriptName.startsWith("git*")) { run(scriptName, runTime.getSikuliArgs()); return; } } if (runScripts != null && runScripts.length > 0) { int exitCode = 0; runAsTest = runTime.runningTests; for (String givenScriptName : runScripts) { if (lastReturnCode == -1) { log(lvl, "Exit code -1: Terminating multi-script-run"); break; } exitCode = new RunBox(givenScriptName, runTime.getSikuliArgs(), runAsTest).run(); lastReturnCode = exitCode; } System.exit(exitCode); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Stream<IdObject<U, List<I>>> get() { BufferedReader candidatesReader; try { candidatesReader = new BufferedReader(new FileReader(candidatesPath)); } catch (FileNotFoundException ex) { throw new UncheckedIOException(ex); } return candidatesReader.lines().parallel().map(line -> { CharSequence[] tokens = split(line, '\t', 3); final U user = uParser.parse(tokens[0]); final List<I> candidates = new ArrayList<>(); for (CharSequence candidate : split(tokens[1], ',')) { candidates.add(iParser.parse(candidate)); } testData.getUserPreferences(user).forEach(iv -> candidates.add(iv.id)); return new IdObject<>(user, candidates); }); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Stream<IdObject<U, List<I>>> get() { try (BufferedReader candidatesReader = new BufferedReader(new FileReader(candidatesPath))) { return candidatesReader.lines().parallel().map(line -> { CharSequence[] tokens = split(line, '\t', 3); final U user = uParser.parse(tokens[0]); final List<I> candidates = new ArrayList<>(); for (CharSequence candidate : split(tokens[1], ',')) { candidates.add(iParser.parse(candidate)); } testData.getUserPreferences(user).forEach(iv -> candidates.add(iv.id)); return new IdObject<>(user, candidates); }); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static <T> List<T> queryObjectListSQL(String poolName, String sql, Class<T> type, Object[] params) { List<T> returnList = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); BeanListHandler<T> resultSetHandler = new BeanListHandler<T>(type); returnList = new QueryRunner().query(con, sql, resultSetHandler, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e2) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e2); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnList; } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code public static <T> List<T> queryObjectListSQL(String poolName, String sql, Class<T> type, Object[] params) { List<T> returnList = null; try { BeanListHandler<T> resultSetHandler = new BeanListHandler<T>(type); returnList = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<Object[]> queryGenericObjectArrayListSQL(String poolName, String sql, Object[] params) { List<Object[]> returnList = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); ArrayListHandler resultSetHandler = new ArrayListHandler(); returnList = new QueryRunner().query(con, sql, resultSetHandler, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e1) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e1); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnList; } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code public static List<Object[]> queryGenericObjectArrayListSQL(String poolName, String sql, Object[] params) { List<Object[]> returnList = null; try { ArrayListHandler resultSetHandler = new ArrayListHandler(); // returnList = new QueryRunner().query(con, sql, resultSetHandler, params); returnList = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static <T> T querySingleScalarSQL(String poolName, String sql, Class<T> type, Object[] params) { T returnObject = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); ScalarHandler<T> resultSetHandler = new ScalarHandler<T>(); returnObject = new QueryRunner().query(con, sql, resultSetHandler, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e2) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e2); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnObject; } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code public static <T> T querySingleScalarSQL(String poolName, String sql, Class<T> type, Object[] params) { T returnObject = null; try { ScalarHandler<T> resultSetHandler = new ScalarHandler<T>(); returnObject = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnObject; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static <T> List<T> queryColumnListSQL(String poolName, String sql, String columnName, Class<T> type, Object[] params) { List<T> returnList = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); ColumnListHandler<T> resultSetHandler = new ColumnListHandler<T>(columnName); returnList = new QueryRunner().query(con, sql, resultSetHandler, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e2) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e2); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnList; } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code public static <T> List<T> queryColumnListSQL(String poolName, String sql, String columnName, Class<T> type, Object[] params) { List<T> returnList = null; try { ColumnListHandler<T> resultSetHandler = new ColumnListHandler<T>(columnName); returnList = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnList; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static int[] executeBatchSQL(String poolName, String sql, Object[][] params) { int[] returnIntArray = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); returnIntArray = new QueryRunner().batch(con, sql, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e1) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e1); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnIntArray; } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public static int[] executeBatchSQL(String poolName, String sql, Object[][] params) { int[] returnIntArray = null; try { returnIntArray = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).batch(sql, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnIntArray; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static <T> T querySingleObjectSQL(String poolName, String sql, Class<T> type, Object[] params) { T returnObject = null; Connection con = null; try { con = DB_CONNECTION_MANAGER.getConnection(poolName); if (con == null) { throw new ConnectionException(poolName); } con.setAutoCommit(false); BeanHandler<T> resultSetHandler = new BeanHandler<T>(type); returnObject = new QueryRunner().query(con, sql, resultSetHandler, params); con.commit(); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); try { con.rollback(); } catch (SQLException e2) { logger.error(ROLLBACK_EXCEPTION_MESSAGE, e2); } } finally { DB_CONNECTION_MANAGER.freeConnection(con); } return returnObject; } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code public static <T> T querySingleObjectSQL(String poolName, String sql, Class<T> type, Object[] params) { T returnObject = null; try { BeanHandler<T> resultSetHandler = new BeanHandler<T>(type); returnObject = new QueryRunner(DB_CONNECTION_MANAGER.getDataSource(poolName)).query(sql, resultSetHandler, params); } catch (Exception e) { logger.error(QUERY_EXCEPTION_MESSAGE, e); } return returnObject; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean connect(final Endpoint endpoint) { if (this.rpcClient == null) { throw new IllegalStateException("Client service is not inited."); } if (isConnected(endpoint)) { return true; } try { final PingRequest req = PingRequest.newBuilder() // .setSendTimestamp(System.currentTimeMillis()) // .build(); final ErrorResponse resp = (ErrorResponse) this.rpcClient.invokeSync(endpoint.toString(), req, this.defaultInvokeCtx, this.rpcOptions.getRpcConnectTimeoutMs()); return resp.getErrorCode() == 0; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); return false; } catch (final RemotingException e) { LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage()); return false; } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean connect(final Endpoint endpoint) { final RpcClient rc = this.rpcClient; if (rc == null) { throw new IllegalStateException("Client service is uninitialized."); } if (isConnected(rc, endpoint)) { return true; } try { final PingRequest req = PingRequest.newBuilder() // .setSendTimestamp(System.currentTimeMillis()) // .build(); final ErrorResponse resp = (ErrorResponse) rc.invokeSync(endpoint.toString(), req, this.defaultInvokeCtx, this.rpcOptions.getRpcConnectTimeoutMs()); return resp.getErrorCode() == 0; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); return false; } catch (final RemotingException e) { LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage()); return false; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void onRpcReturned(Status status, GetFileResponse response) { lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (st.isOk()) { st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (st.isOk()) { st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (outputStream != null) { try { response.getData().writeTo(outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { lock.unlock(); } this.sendNextRpc(); } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void cancel() { lock.lock(); try { if (this.finished) { return; } if (this.timer != null) { this.timer.cancel(true); } if (this.rpcCall != null) { this.rpcCall.cancel(true); } if (st.isOk()) { st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); } this.onFinished(); } finally { lock.unlock(); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void cancel() { this.lock.lock(); try { if (this.finished) { return; } if (this.timer != null) { this.timer.cancel(true); } if (this.rpcCall != null) { this.rpcCall.cancel(true); } if (this.st.isOk()) { this.st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); } this.onFinished(); } finally { this.lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testChangePeers() throws Exception { final List<PeerId> newPeers = TestUtils.generatePeers(10); newPeers.removeAll(conf.getPeerSet()); for (final PeerId peer : newPeers) { assertTrue(cluster.start(peer.getEndpoint())); } final PeerId oldLeader = cluster.getLeader().getNodeId().getPeerId(); assertNotNull(oldLeader); assertTrue(this.cliService.changePeers(groupId, conf, new Configuration(newPeers)).isOk()); cluster.waitLeader(); final PeerId newLeader = cluster.getLeader().getNodeId().getPeerId(); assertNotEquals(oldLeader, newLeader); assertTrue(newPeers.contains(newLeader)); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testChangePeers() throws Exception { final List<PeerId> newPeers = TestUtils.generatePeers(10); newPeers.removeAll(conf.getPeerSet()); for (final PeerId peer : newPeers) { assertTrue(cluster.start(peer.getEndpoint())); } cluster.waitLeader(); final Node oldLeaderNode = cluster.getLeader(); assertNotNull(oldLeaderNode); final PeerId oldLeader = oldLeaderNode.getNodeId().getPeerId(); assertNotNull(oldLeader); assertTrue(this.cliService.changePeers(groupId, conf, new Configuration(newPeers)).isOk()); cluster.waitLeader(); final PeerId newLeader = cluster.getLeader().getNodeId().getPeerId(); assertNotEquals(oldLeader, newLeader); assertTrue(newPeers.contains(newLeader)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void shutdown(final Closure done) { this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Destroy all timers if (this.electionTimer != null) { this.electionTimer.destroy(); } if (this.voteTimer != null) { this.voteTimer.destroy(); } if (this.stepDownTimer != null) { this.stepDownTimer.destroy(); } if (this.snapshotTimer != null) { this.snapshotTimer.destroy(); } if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void shutdown(final Closure done) { List<RepeatedTimer> timers = null; this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Stop all timers timers = stopAllTimers(); if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); // Destroy all timers out of lock if (timers != null) { destroyAllTimers(timers); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isConnected(final Endpoint endpoint) { return this.rpcClient.checkConnection(endpoint.toString()); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean isConnected(final Endpoint endpoint) { final RpcClient rc = this.rpcClient; return rc != null && isConnected(rc, endpoint); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void onRpcReturned(Status status, GetFileResponse response) { lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (st.isOk()) { st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (st.isOk()) { st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (outputStream != null) { try { response.getData().writeTo(outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { lock.unlock(); } this.sendNextRpc(); } #location 57 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean disconnect(final Endpoint endpoint) { LOG.info("Disconnect from {}", endpoint); this.rpcClient.closeConnection(endpoint.toString()); return true; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean disconnect(final Endpoint endpoint) { final RpcClient rc = this.rpcClient; if (rc == null) { return true; } LOG.info("Disconnect from {}.", endpoint); rc.closeConnection(endpoint.toString()); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void addLeaderStateListener(final long regionId, final LeaderStateListener listener) { checkState(); if (this.storeEngine == null) { throw new IllegalStateException("current node do not have store engine"); } final RegionEngine regionEngine = this.storeEngine.getRegionEngine(regionId); if (regionEngine == null) { throw new IllegalStateException("current node do not have this region engine[" + regionId + "]"); } regionEngine.getFsm().addLeaderStateListener(listener); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void addLeaderStateListener(final long regionId, final LeaderStateListener listener) { addStateListener(regionId, listener); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void addStateListener(final long regionId, final StateListener listener) { checkState(); if (this.storeEngine == null) { throw new IllegalStateException("current node do not have store engine"); } final RegionEngine regionEngine = this.storeEngine.getRegionEngine(regionId); if (regionEngine == null) { throw new IllegalStateException("current node do not have this region engine[" + regionId + "]"); } regionEngine.getFsm().addStateListener(listener); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void addStateListener(final long regionId, final StateListener listener) { this.stateListenerContainer.addStateListener(regionId, listener); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { // TODO: Currently we don't care about error_code which indicates why the // very RPC fails. To make it better there should be different timeout for // each individual error (e.g. we don't need check every // heartbeat_timeout_ms whether a dead follower has come back), but it's just // fine now. final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); try { LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), TimeUnit.MILLISECONDS); this.statInfo.runningState = RunningState.BLOCKING; this.id.unlock(); } catch (final Exception e) { LOG.error("Fail to add timer", e); // id unlock in sendEmptyEntries. sendEmptyEntries(false); } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, final AppendEntriesResponse response, final long rpcSendTime) { if (id == null) { // replicator already was destroyed. return; } final long startTimeMs = Utils.nowMs(); Replicator r; if ((r = (Replicator) id.lock()) == null) { return; } boolean doUnlock = true; try { final boolean isLogDebugEnabled = LOG.isDebugEnabled(); StringBuilder sb = null; if (isLogDebugEnabled) { sb = new StringBuilder("Node "). // append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // append(" received HeartbeatResponse from "). // append(r.options.getPeerId()). // append(" prevLogIndex=").append(request.getPrevLogIndex()). // append(" prevLogTerm=").append(request.getPrevLogTerm()); } if (!status.isOk()) { if (isLogDebugEnabled) { sb.append(" fail, sleep."); LOG.debug(sb.toString()); } r.state = State.Probe; if (++r.consecutiveErrorTimes % 10 == 0) { LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), r.consecutiveErrorTimes, status); } r.startHeartbeatTimer(startTimeMs); return; } r.consecutiveErrorTimes = 0; if (response.getTerm() > r.options.getTerm()) { if (isLogDebugEnabled) { sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") .append(r.options.getTerm()); LOG.debug(sb.toString()); } final NodeImpl node = r.options.getNode(); r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); r.destroy(); node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); return; } if (!response.getSuccess() && response.hasLastLogIndex()) { if (isLogDebugEnabled) { sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") .append(response.getLastLogIndex()); LOG.debug(sb.toString()); } LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); doUnlock = false; r.sendEmptyEntries(false); r.startHeartbeatTimer(startTimeMs); return; } if (isLogDebugEnabled) { LOG.debug(sb.toString()); } if (rpcSendTime > r.lastRpcSendTimestamp) { r.lastRpcSendTimestamp = rpcSendTime; } r.startHeartbeatTimer(startTimeMs); } finally { if (doUnlock) { id.unlock(); } } } #location 59 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, final AppendEntriesResponse response, final long rpcSendTime) { if (id == null) { // replicator already was destroyed. return; } final long startTimeMs = Utils.nowMs(); Replicator r; if ((r = (Replicator) id.lock()) == null) { return; } boolean doUnlock = true; try { final boolean isLogDebugEnabled = LOG.isDebugEnabled(); StringBuilder sb = null; if (isLogDebugEnabled) { sb = new StringBuilder("Node "). // append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // append(" received HeartbeatResponse from "). // append(r.options.getPeerId()). // append(" prevLogIndex=").append(request.getPrevLogIndex()). // append(" prevLogTerm=").append(request.getPrevLogTerm()); } if (!status.isOk()) { if (isLogDebugEnabled) { sb.append(" fail, sleep."); LOG.debug(sb.toString()); } r.state = State.Probe; notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); if (++r.consecutiveErrorTimes % 10 == 0) { LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), r.consecutiveErrorTimes, status); } r.startHeartbeatTimer(startTimeMs); return; } r.consecutiveErrorTimes = 0; if (response.getTerm() > r.options.getTerm()) { if (isLogDebugEnabled) { sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") .append(r.options.getTerm()); LOG.debug(sb.toString()); } final NodeImpl node = r.options.getNode(); r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); r.destroy(); node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); return; } if (!response.getSuccess() && response.hasLastLogIndex()) { if (isLogDebugEnabled) { sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") .append(response.getLastLogIndex()); LOG.debug(sb.toString()); } LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); doUnlock = false; r.sendEmptyEntries(false); r.startHeartbeatTimer(startTimeMs); return; } if (isLogDebugEnabled) { LOG.debug(sb.toString()); } if (rpcSendTime > r.lastRpcSendTimestamp) { r.lastRpcSendTimestamp = rpcSendTime; } r.startHeartbeatTimer(startTimeMs); } finally { if (doUnlock) { id.unlock(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { throw new IllegalArgumentException("Invalid ReplicatorOptions."); } final Replicator r = new Replicator(opts, raftOptions); if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { LOG.error("Fail to init sending channel to {}", opts.getPeerId()); // Return and it will be retried later. return null; } // Register replicator metric set. final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); if (metricRegistry != null) { try { final String replicatorMetricName = getReplicatorMetricName(opts); if (!metricRegistry.getNames().contains(replicatorMetricName)) { metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); } } catch (final IllegalArgumentException e) { // ignore } } // Start replication r.id = new ThreadId(r, r); r.id.lock(); LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); r.catchUpClosure = null; r.lastRpcSendTimestamp = Utils.monotonicMs(); r.startHeartbeatTimer(Utils.nowMs()); // id.unlock in sendEmptyEntries r.sendEmptyEntries(false); return r.id; } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { throw new IllegalArgumentException("Invalid ReplicatorOptions."); } final Replicator r = new Replicator(opts, raftOptions); if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { LOG.error("Fail to init sending channel to {}", opts.getPeerId()); // Return and it will be retried later. return null; } // Register replicator metric set. final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); if (metricRegistry != null) { try { final String replicatorMetricName = getReplicatorMetricName(opts); if (!metricRegistry.getNames().contains(replicatorMetricName)) { metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); } } catch (final IllegalArgumentException e) { // ignore } } // Start replication r.id = new ThreadId(r, r); r.id.lock(); notifyReplicatorStatusListener(r, ReplicatorEvent.CREATED); LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); r.catchUpClosure = null; r.lastRpcSendTimestamp = Utils.monotonicMs(); r.startHeartbeatTimer(Utils.nowMs()); // id.unlock in sendEmptyEntries r.sendEmptyEntries(false); return r.id; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) { final FutureImpl<Message> future = new FutureImpl<>(); try { final Url rpcUrl = this.rpcAddressParser.parse(endpoint.toString()); this.rpcClient.invokeWithCallback(rpcUrl, request, ctx, new InvokeCallback() { @SuppressWarnings("unchecked") @Override public void onResponse(final Object result) { if (future.isCancelled()) { onCanceled(request, done); return; } Status status = Status.OK(); if (result instanceof ErrorResponse) { final ErrorResponse eResp = (ErrorResponse) result; status = new Status(); status.setCode(eResp.getErrorCode()); if (eResp.hasErrorMsg()) { status.setErrorMsg(eResp.getErrorMsg()); } } else { if (done != null) { done.setResponse((T) result); } } if (done != null) { try { done.run(status); } catch (final Throwable t) { LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); } } if (!future.isDone()) { future.setResult((Message) result); } } @Override public void onException(final Throwable e) { if (future.isCancelled()) { onCanceled(request, done); return; } if (done != null) { try { done.run(new Status(e instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT : RaftError.EINTERNAL, "RPC exception:" + e.getMessage())); } catch (final Throwable t) { LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); } } if (!future.isDone()) { future.failure(e); } } @Override public Executor getExecutor() { return rpcExecutor != null ? rpcExecutor : AbstractBoltClientService.this.rpcExecutor; } }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); future.failure(e); // should be in another thread to avoid dead locking. Utils.runClosureInThread(done, new Status(RaftError.EINTR, "Sending rpc was interrupted")); } catch (final RemotingException e) { future.failure(e); // should be in another thread to avoid dead locking. Utils.runClosureInThread(done, new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage())); } return future; } #location 65 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public <T extends Message> Future<Message> invokeWithDone(final Endpoint endpoint, final Message request, final InvokeContext ctx, final RpcResponseClosure<T> done, final int timeoutMs, final Executor rpcExecutor) { final RpcClient rc = this.rpcClient; final FutureImpl<Message> future = new FutureImpl<>(); try { if (rc == null) { future.failure(new IllegalStateException("Client service is uninitialized.")); // should be in another thread to avoid dead locking. Utils.runClosureInThread(done, new Status(RaftError.EINTERNAL, "Client service is uninitialized.")); return future; } final Url rpcUrl = this.rpcAddressParser.parse(endpoint.toString()); rc.invokeWithCallback(rpcUrl, request, ctx, new InvokeCallback() { @SuppressWarnings("unchecked") @Override public void onResponse(final Object result) { if (future.isCancelled()) { onCanceled(request, done); return; } Status status = Status.OK(); if (result instanceof ErrorResponse) { final ErrorResponse eResp = (ErrorResponse) result; status = new Status(); status.setCode(eResp.getErrorCode()); if (eResp.hasErrorMsg()) { status.setErrorMsg(eResp.getErrorMsg()); } } else { if (done != null) { done.setResponse((T) result); } } if (done != null) { try { done.run(status); } catch (final Throwable t) { LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); } } if (!future.isDone()) { future.setResult((Message) result); } } @Override public void onException(final Throwable e) { if (future.isCancelled()) { onCanceled(request, done); return; } if (done != null) { try { done.run(new Status(e instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT : RaftError.EINTERNAL, "RPC exception:" + e.getMessage())); } catch (final Throwable t) { LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); } } if (!future.isDone()) { future.failure(e); } } @Override public Executor getExecutor() { return rpcExecutor != null ? rpcExecutor : AbstractBoltClientService.this.rpcExecutor; } }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); future.failure(e); // should be in another thread to avoid dead locking. Utils.runClosureInThread(done, new Status(RaftError.EINTR, "Sending rpc was interrupted")); } catch (final RemotingException e) { future.failure(e); // should be in another thread to avoid dead locking. Utils.runClosureInThread(done, new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage())); } return future; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 55 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void shutdown(final Closure done) { this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Destroy all timers if (this.electionTimer != null) { this.electionTimer.destroy(); } if (this.voteTimer != null) { this.voteTimer.destroy(); } if (this.stepDownTimer != null) { this.stepDownTimer.destroy(); } if (this.snapshotTimer != null) { this.snapshotTimer.destroy(); } if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void shutdown(final Closure done) { List<RepeatedTimer> timers = null; this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Stop all timers timers = stopAllTimers(); if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); // Destroy all timers out of lock if (timers != null) { destroyAllTimers(timers); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void destroy() { final ThreadId savedId = this.id; LOG.info("Replicator {} is going to quit", savedId); this.id = null; releaseReader(); // Unregister replicator metric set if (this.options.getNode().getNodeMetrics().isEnabled()) { this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); } this.state = State.Destroyed; notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); savedId.unlockAndDestroy(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void shutdown(final Closure done) { this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Destroy all timers if (this.electionTimer != null) { this.electionTimer.destroy(); } if (this.voteTimer != null) { this.voteTimer.destroy(); } if (this.stepDownTimer != null) { this.stepDownTimer.destroy(); } if (this.snapshotTimer != null) { this.snapshotTimer.destroy(); } if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void shutdown(final Closure done) { List<RepeatedTimer> timers = null; this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Stop all timers timers = stopAllTimers(); if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); // Destroy all timers out of lock if (timers != null) { destroyAllTimers(timers); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void destroy() { final ThreadId savedId = this.id; LOG.info("Replicator {} is going to quit", savedId); this.id = null; releaseReader(); // Unregister replicator metric set if (this.options.getNode().getNodeMetrics().isEnabled()) { this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); } this.state = State.Destroyed; notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); savedId.unlockAndDestroy(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void destroy() { final ThreadId savedId = this.id; LOG.info("Replicator {} is going to quit", savedId); this.id = null; if (this.reader != null) { Utils.closeQuietly(this.reader); this.reader = null; } // Unregister replicator metric set if (this.options.getNode().getNodeMetrics().getMetricRegistry() != null) { this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); } this.state = State.Destroyed; savedId.unlockAndDestroy(); } #location 14 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void shutdown(final Closure done) { this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Destroy all timers if (this.electionTimer != null) { this.electionTimer.destroy(); } if (this.voteTimer != null) { this.voteTimer.destroy(); } if (this.stepDownTimer != null) { this.stepDownTimer.destroy(); } if (this.snapshotTimer != null) { this.snapshotTimer.destroy(); } if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void shutdown(final Closure done) { List<RepeatedTimer> timers = null; this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Stop all timers timers = stopAllTimers(); if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); // Destroy all timers out of lock if (timers != null) { destroyAllTimers(timers); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testOnRpcReturnedRpcError() { final Replicator r = getReplicator(); assertNull(r.getBlockTimer()); final RpcRequests.AppendEntriesRequest request = createEmptyEntriesRequest(); final RpcRequests.AppendEntriesResponse response = RpcRequests.AppendEntriesResponse.newBuilder() // .setSuccess(false) // .setLastLogIndex(12) // .setTerm(2) // .build(); this.id.unlock(); Replicator.onRpcReturned(this.id, Replicator.RequestType.AppendEntries, new Status(-1, "test error"), request, response, 0, 0, Utils.monotonicMs()); assertEquals(r.statInfo.runningState, Replicator.RunningState.BLOCKING); assertNotNull(r.getBlockTimer()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testOnRpcReturnedRpcError() { testRpcReturnedError(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unused") static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, final TimeoutNowResponse response, final boolean stopAfterFinish) { final Replicator r = (Replicator) id.lock(); if (r == null) { return; } final boolean isLogDebugEnabled = LOG.isDebugEnabled(); StringBuilder sb = null; if (isLogDebugEnabled) { sb = new StringBuilder("Node "). // append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // append(" received TimeoutNowResponse from "). // append(r.options.getPeerId()); } if (!status.isOk()) { if (isLogDebugEnabled) { sb.append(" fail:").append(status); LOG.debug(sb.toString()); } if (stopAfterFinish) { r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); r.destroy(); } else { id.unlock(); } return; } if (isLogDebugEnabled) { sb.append(response.getSuccess() ? " success" : " fail"); LOG.debug(sb.toString()); } if (response.getTerm() > r.options.getTerm()) { final NodeImpl node = r.options.getNode(); r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); r.destroy(); node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); return; } if (stopAfterFinish) { r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); r.destroy(); } else { id.unlock(); } } #location 38 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unused") static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, final TimeoutNowResponse response, final boolean stopAfterFinish) { final Replicator r = (Replicator) id.lock(); if (r == null) { return; } final boolean isLogDebugEnabled = LOG.isDebugEnabled(); StringBuilder sb = null; if (isLogDebugEnabled) { sb = new StringBuilder("Node "). // append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // append(" received TimeoutNowResponse from "). // append(r.options.getPeerId()); } if (!status.isOk()) { if (isLogDebugEnabled) { sb.append(" fail:").append(status); LOG.debug(sb.toString()); } notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); if (stopAfterFinish) { r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); r.destroy(); } else { id.unlock(); } return; } if (isLogDebugEnabled) { sb.append(response.getSuccess() ? " success" : " fail"); LOG.debug(sb.toString()); } if (response.getTerm() > r.options.getTerm()) { final NodeImpl node = r.options.getNode(); r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); r.destroy(); node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); return; } if (stopAfterFinish) { r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); r.destroy(); } else { id.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean commitAt(long firstLogIndex, long lastLogIndex, PeerId peer) { //TODO use lock-free algorithm here? final long stamp = stampedLock.writeLock(); long lastCommittedIndex = 0; try { if (pendingIndex == 0) { return false; } if (lastLogIndex < pendingIndex) { return true; } if (lastLogIndex >= pendingIndex + pendingMetaQueue.size()) { throw new ArrayIndexOutOfBoundsException(); } final long startAt = Math.max(pendingIndex, firstLogIndex); Ballot.PosHint hint = new Ballot.PosHint(); for (long logIndex = startAt; logIndex <= lastLogIndex; logIndex++) { final Ballot bl = this.pendingMetaQueue.get((int) (logIndex - pendingIndex)); hint = bl.grant(peer, hint); if (bl.isGranted()) { lastCommittedIndex = logIndex; } } if (lastCommittedIndex == 0) { return true; } // When removing a peer off the raft group which contains even number of // peers, the quorum would decrease by 1, e.g. 3 of 4 changes to 2 of 3. In // this case, the log after removal may be committed before some previous // logs, since we use the new configuration to deal the quorum of the // removal request, we think it's safe to commit all the uncommitted // previous logs, which is not well proved right now for (long index = pendingIndex; index <= lastCommittedIndex; index++) { pendingMetaQueue.pollFirst(); LOG.debug("Committed log index={}", index); } pendingIndex = lastCommittedIndex + 1; this.lastCommittedIndex = lastCommittedIndex; } finally { stampedLock.unlockWrite(stamp); } this.waiter.onCommitted(lastCommittedIndex); return true; } #location 37 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code public boolean commitAt(long firstLogIndex, long lastLogIndex, PeerId peer) { //TODO use lock-free algorithm here? final long stamp = stampedLock.writeLock(); long lastCommittedIndex = 0; try { if (pendingIndex == 0) { return false; } if (lastLogIndex < pendingIndex) { return true; } if (lastLogIndex >= pendingIndex + pendingMetaQueue.size()) { throw new ArrayIndexOutOfBoundsException(); } final long startAt = Math.max(pendingIndex, firstLogIndex); Ballot.PosHint hint = new Ballot.PosHint(); for (long logIndex = startAt; logIndex <= lastLogIndex; logIndex++) { final Ballot bl = this.pendingMetaQueue.get((int) (logIndex - pendingIndex)); hint = bl.grant(peer, hint); if (bl.isGranted()) { lastCommittedIndex = logIndex; } } if (lastCommittedIndex == 0) { return true; } // When removing a peer off the raft group which contains even number of // peers, the quorum would decrease by 1, e.g. 3 of 4 changes to 2 of 3. In // this case, the log after removal may be committed before some previous // logs, since we use the new configuration to deal the quorum of the // removal request, we think it's safe to commit all the uncommitted // previous logs, which is not well proved right now pendingMetaQueue.removeRange(0, (int) (lastCommittedIndex - pendingIndex) + 1); LOG.debug("Committed log fromIndex={}, toIndex={}.", pendingIndex, lastCommittedIndex); pendingIndex = lastCommittedIndex + 1; this.lastCommittedIndex = lastCommittedIndex; } finally { stampedLock.unlockWrite(stamp); } this.waiter.onCommitted(lastCommittedIndex); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendNextRpc() { this.timer = null; final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); this.lock.lock(); try { if (this.finished) { return; } // throttle long newMaxCount = maxCount; if (this.snapshotThrottle != null) { newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); if (newMaxCount == 0) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } } this.requestBuilder.setCount(newMaxCount); LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), this.copyOptions.getTimeoutMs(), done); } finally { lock.unlock(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void destroy() { final ThreadId savedId = this.id; LOG.info("Replicator {} is going to quit", savedId); this.id = null; releaseReader(); // Unregister replicator metric set if (this.options.getNode().getNodeMetrics().isEnabled()) { this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); } this.state = State.Destroyed; notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); savedId.unlockAndDestroy(); } #location 11 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void destroy() { final ThreadId savedId = this.id; LOG.info("Replicator {} is going to quit", savedId); this.id = null; releaseReader(); // Unregister replicator metric set if (this.options.getNode().getNodeMetrics().isEnabled()) { this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); } this.state = State.Destroyed; notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); savedId.unlockAndDestroy(); } #location 12 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void sendEntries() { boolean doUnlock = true; try { long prevSendIndex = -1; while (true) { final long nextSendingIndex = getNextSendIndex(); if (nextSendingIndex > prevSendIndex) { if (sendEntries(nextSendingIndex)) { prevSendIndex = nextSendingIndex; } else { doUnlock = false; // id already unlock in sendEntries when it returns false. break; } } else { break; } } } finally { if (doUnlock) { this.id.unlock(); } } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void destroy() { final ThreadId savedId = this.id; LOG.info("Replicator {} is going to quit", savedId); this.id = null; releaseReader(); // Unregister replicator metric set if (this.options.getNode().getNodeMetrics().isEnabled()) { this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); } this.state = State.Destroyed; notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); savedId.unlockAndDestroy(); } #location 3 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Session startCopyToFile(String source, String destPath, CopyOptions opts) throws IOException { final File file = new File(destPath); // delete exists file. if (file.exists()) { if (!file.delete()) { LOG.error("Fail to delete destPath: {}", destPath); return null; } } final OutputStream out = new BufferedOutputStream(new FileOutputStream(file, false)); final BoltSession session = newBoltSession(source); session.setOutputStream(out); session.setDestPath(destPath); session.setDestBuf(null); if (opts != null) { session.setCopyOptions(opts); } session.sendNextRpc(); return session; } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public Session startCopyToFile(String source, String destPath, CopyOptions opts) throws IOException { final File file = new File(destPath); // delete exists file. if (file.exists()) { if (!file.delete()) { LOG.error("Fail to delete destPath: {}", destPath); return null; } } final OutputStream out = new BufferedOutputStream(new FileOutputStream(file, false) { @Override public void close() throws IOException { getFD().sync(); super.close(); } }); final BoltSession session = newBoltSession(source); session.setOutputStream(out); session.setDestPath(destPath); session.setDestBuf(null); if (opts != null) { session.setCopyOptions(opts); } session.sendNextRpc(); return session; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, final AppendEntriesResponse response, final long rpcSendTime) { if (id == null) { // replicator already was destroyed. return; } final long startTimeMs = Utils.nowMs(); Replicator r; if ((r = (Replicator) id.lock()) == null) { return; } boolean doUnlock = true; try { final boolean isLogDebugEnabled = LOG.isDebugEnabled(); StringBuilder sb = null; if (isLogDebugEnabled) { sb = new StringBuilder("Node "). // append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // append(" received HeartbeatResponse from "). // append(r.options.getPeerId()). // append(" prevLogIndex=").append(request.getPrevLogIndex()). // append(" prevLogTerm=").append(request.getPrevLogTerm()); } if (!status.isOk()) { if (isLogDebugEnabled) { sb.append(" fail, sleep."); LOG.debug(sb.toString()); } r.state = State.Probe; if (++r.consecutiveErrorTimes % 10 == 0) { LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), r.consecutiveErrorTimes, status); } r.startHeartbeatTimer(startTimeMs); return; } r.consecutiveErrorTimes = 0; if (response.getTerm() > r.options.getTerm()) { if (isLogDebugEnabled) { sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") .append(r.options.getTerm()); LOG.debug(sb.toString()); } final NodeImpl node = r.options.getNode(); r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); r.destroy(); node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); return; } if (!response.getSuccess() && response.hasLastLogIndex()) { if (isLogDebugEnabled) { sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") .append(response.getLastLogIndex()); LOG.debug(sb.toString()); } LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); doUnlock = false; r.sendEmptyEntries(false); r.startHeartbeatTimer(startTimeMs); return; } if (isLogDebugEnabled) { LOG.debug(sb.toString()); } if (rpcSendTime > r.lastRpcSendTimestamp) { r.lastRpcSendTimestamp = rpcSendTime; } r.startHeartbeatTimer(startTimeMs); } finally { if (doUnlock) { id.unlock(); } } } #location 47 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, final AppendEntriesResponse response, final long rpcSendTime) { if (id == null) { // replicator already was destroyed. return; } final long startTimeMs = Utils.nowMs(); Replicator r; if ((r = (Replicator) id.lock()) == null) { return; } boolean doUnlock = true; try { final boolean isLogDebugEnabled = LOG.isDebugEnabled(); StringBuilder sb = null; if (isLogDebugEnabled) { sb = new StringBuilder("Node "). // append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // append(" received HeartbeatResponse from "). // append(r.options.getPeerId()). // append(" prevLogIndex=").append(request.getPrevLogIndex()). // append(" prevLogTerm=").append(request.getPrevLogTerm()); } if (!status.isOk()) { if (isLogDebugEnabled) { sb.append(" fail, sleep."); LOG.debug(sb.toString()); } r.state = State.Probe; notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); if (++r.consecutiveErrorTimes % 10 == 0) { LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), r.consecutiveErrorTimes, status); } r.startHeartbeatTimer(startTimeMs); return; } r.consecutiveErrorTimes = 0; if (response.getTerm() > r.options.getTerm()) { if (isLogDebugEnabled) { sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") .append(r.options.getTerm()); LOG.debug(sb.toString()); } final NodeImpl node = r.options.getNode(); r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); r.destroy(); node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); return; } if (!response.getSuccess() && response.hasLastLogIndex()) { if (isLogDebugEnabled) { sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") .append(response.getLastLogIndex()); LOG.debug(sb.toString()); } LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); doUnlock = false; r.sendEmptyEntries(false); r.startHeartbeatTimer(startTimeMs); return; } if (isLogDebugEnabled) { LOG.debug(sb.toString()); } if (rpcSendTime > r.lastRpcSendTimestamp) { r.lastRpcSendTimestamp = rpcSendTime; } r.startHeartbeatTimer(startTimeMs); } finally { if (doUnlock) { id.unlock(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void onRpcReturned(Status status, GetFileResponse response) { lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (st.isOk()) { st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (st.isOk()) { st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (outputStream != null) { try { response.getData().writeTo(outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { lock.unlock(); } this.sendNextRpc(); } #location 35 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void onRpcReturned(Status status, GetFileResponse response) { this.lock.lock(); try { if (this.finished) { return; } if (!status.isOk()) { // Reset count to make next rpc retry the previous one this.requestBuilder.setCount(0); if (status.getCode() == RaftError.ECANCELED.getNumber()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } // Throttled reading failure does not increase _retry_times if (status.getCode() != RaftError.EAGAIN.getNumber() && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { if (this.st.isOk()) { this.st.setError(status.getCode(), status.getErrorMsg()); this.onFinished(); return; } } this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), TimeUnit.MILLISECONDS); return; } this.retryTimes = 0; Requires.requireNonNull(response, "response"); // Reset count to |real_read_size| to make next rpc get the right offset if (response.hasReadSize() && response.getReadSize() != 0) { this.requestBuilder.setCount(response.getReadSize()); } if (this.outputStream != null) { try { response.getData().writeTo(this.outputStream); } catch (final IOException e) { LOG.error("Fail to write into file {}", this.destPath); this.st.setError(RaftError.EIO, RaftError.EIO.name()); this.onFinished(); return; } } else { final byte[] data = response.getData().toByteArray(); this.destBuf.put(data); } if (response.getEof()) { onFinished(); return; } } finally { this.lock.unlock(); } sendNextRpc(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void shutdown(final Closure done) { this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Destroy all timers if (this.electionTimer != null) { this.electionTimer.destroy(); } if (this.voteTimer != null) { this.voteTimer.destroy(); } if (this.stepDownTimer != null) { this.stepDownTimer.destroy(); } if (this.snapshotTimer != null) { this.snapshotTimer.destroy(); } if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void shutdown(final Closure done) { List<RepeatedTimer> timers = null; this.writeLock.lock(); try { LOG.info("Node {} shutdown, currTerm={} state={}.", getNodeId(), this.currTerm, this.state); if (this.state.compareTo(State.STATE_SHUTTING) < 0) { NodeManager.getInstance().remove(this); // If it is leader, set the wakeup_a_candidate with true; // If it is follower, call on_stop_following in step_down if (this.state.compareTo(State.STATE_FOLLOWER) <= 0) { stepDown(this.currTerm, this.state == State.STATE_LEADER, new Status(RaftError.ESHUTDOWN, "Raft node is going to quit.")); } this.state = State.STATE_SHUTTING; // Stop all timers timers = stopAllTimers(); if (this.readOnlyService != null) { this.readOnlyService.shutdown(); } if (this.logManager != null) { this.logManager.shutdown(); } if (this.metaStorage != null) { this.metaStorage.shutdown(); } if (this.snapshotExecutor != null) { this.snapshotExecutor.shutdown(); } if (this.wakingCandidate != null) { Replicator.stop(this.wakingCandidate); } if (this.fsmCaller != null) { this.fsmCaller.shutdown(); } if (this.rpcService != null) { this.rpcService.shutdown(); } if (this.applyQueue != null) { Utils.runInThread(() -> { this.shutdownLatch = new CountDownLatch(1); this.applyQueue.publishEvent((event, sequence) -> event.shutdownLatch = this.shutdownLatch); }); } else { final int num = GLOBAL_NUM_NODES.decrementAndGet(); LOG.info("The number of active nodes decrement to {}.", num); } if (this.timerManager != null) { this.timerManager.shutdown(); } } if (this.state != State.STATE_SHUTDOWN) { if (done != null) { this.shutdownContinuations.add(done); } return; } // This node is down, it's ok to invoke done right now. Don't invoke this // in place to avoid the dead writeLock issue when done.Run() is going to acquire // a writeLock which is already held by the caller if (done != null) { Utils.runClosureInThread(done); } } finally { this.writeLock.unlock(); // Destroy all timers out of lock if (timers != null) { destroyAllTimers(timers); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void installSnapshot() { if (this.state == State.Snapshot) { LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); this.id.unlock(); return; } boolean doUnlock = true; try { Requires.requireTrue(this.reader == null, "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), this.state); this.reader = this.options.getSnapshotStorage().open(); if (this.reader == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); this.id.unlock(); doUnlock = false; node.onError(error); return; } final String uri = this.reader.generateURIForCopy(); if (uri == null) { final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final RaftOutter.SnapshotMeta meta = this.reader.load(); if (meta == null) { final String snapshotPath = this.reader.getPath(); final NodeImpl node = this.options.getNode(); final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); releaseReader(); this.id.unlock(); doUnlock = false; node.onError(error); return; } final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); rb.setTerm(this.options.getTerm()); rb.setGroupId(this.options.getGroupId()); rb.setServerId(this.options.getServerId().toString()); rb.setPeerId(this.options.getPeerId().toString()); rb.setMeta(meta); rb.setUri(uri); this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); final InstallSnapshotRequest request = rb.build(); this.state = State.Snapshot; // noinspection NonAtomicOperationOnVolatileField this.installSnapshotCounter++; final long monotonicSendTimeMs = Utils.monotonicMs(); final int stateVersion = this.version; final int seq = getAndIncrementReqSeq(); final Future<Message> rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), request, new RpcResponseClosureAdapter<InstallSnapshotResponse>() { @Override public void run(final Status status) { onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, stateVersion, monotonicSendTimeMs); } }); addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); } finally { if (doUnlock) { this.id.unlock(); } } } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getNextSendIndex() { // Fast path if (this.inflights.isEmpty()) { return this.nextIndex; } // Too many in-flight requests. if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { return -1L; } // Last request should be a AppendEntries request and has some entries. if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { return this.rpcInFly.startIndex + this.rpcInFly.count; } return -1L; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRead() throws IOException, ParseException, Event.EventFormatException { BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8)); Event ev = Event.read(in); assertEquals(444691, ev.getUid()); assertEquals(1382920806122L, ev.getTime()); assertEquals("static/image-4", ev.getOp()); assertEquals(-599092377, ev.getIp()); ev = Event.read(in); assertEquals(49664, ev.getUid()); assertEquals(1382926154968L, ev.getTime()); assertEquals("login", ev.getOp()); assertEquals(950354974, ev.getIp()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRead() throws IOException { //noinspection UnstableApiUsage BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8)); Event ev = Event.read(in); assert ev != null; assertEquals(444691, ev.getUid()); assertEquals(1382920806122L, ev.getTime()); assertEquals("static/image-4", ev.getOp()); assertEquals(-599092377, ev.getIp()); ev = Event.read(in); assert ev != null; assertEquals(49664, ev.getUid()); assertEquals(1382926154968L, ev.getTime()); assertEquals("login", ev.getOp()); assertEquals(950354974, ev.getIp()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRead() throws IOException, ParseException, Event.EventFormatException { BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8)); Event ev = Event.read(in); assertEquals(444691, ev.getUid()); assertEquals(1382920806122L, ev.getTime()); assertEquals("static/image-4", ev.getOp()); assertEquals(-599092377, ev.getIp()); ev = Event.read(in); assertEquals(49664, ev.getUid()); assertEquals(1382926154968L, ev.getTime()); assertEquals("login", ev.getOp()); assertEquals(950354974, ev.getIp()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRead() throws IOException { //noinspection UnstableApiUsage BufferedReader in = new BufferedReader(new InputStreamReader(Resources.getResource("event.txt").openStream(), Charsets.UTF_8)); Event ev = Event.read(in); assert ev != null; assertEquals(444691, ev.getUid()); assertEquals(1382920806122L, ev.getTime()); assertEquals("static/image-4", ev.getOp()); assertEquals(-599092377, ev.getIp()); ev = Event.read(in); assert ev != null; assertEquals(49664, ev.getUid()); assertEquals(1382926154968L, ev.getTime()); assertEquals("login", ev.getOp()); assertEquals(950354974, ev.getIp()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeKryo(String fileName, GraphDatabaseService db, SubGraph graph, ProgressReporter reporter, Config config) throws Exception { OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(fileName, true)); com.esotericsoftware.kryo.io.Output output = new com.esotericsoftware.kryo.io.Output(outputStream); try (Transaction tx = db.beginTx()) { KryoWriter kryoWriter = new KryoWriter(); kryoWriter.write(graph, output, reporter, config); tx.success(); } finally { output.close(); } } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private void writeKryo(String fileName, GraphDatabaseService db, SubGraph graph, ProgressReporter reporter, Config config) throws Exception { OutputStream outputStream = new BufferedOutputStream(new DeflaterOutputStream(new FileOutputStream(fileName, true), false), FileUtils.MEGABYTE); com.esotericsoftware.kryo.io.Output output = new com.esotericsoftware.kryo.io.Output(outputStream, FileUtils.MEGABYTE); try (Transaction tx = db.beginTx()) { KryoWriter kryoWriter = new KryoWriter(); kryoWriter.write(graph, output, reporter, config); tx.success(); } finally { output.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getIpAddress() { HttpServletRequest request = getRequest(); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("http_client_ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip != null && ip.indexOf(",") != -1) { ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim(); } return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip; } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public String getIpAddress() { HttpServletRequest request = getRequest(); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("http_client_ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip != null && ip.indexOf(",") != -1) { ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim(); } return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader, DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) { if (option == null) { option = new DatabaseOperationOption(); } ensureVersionExists(migrationsLoader); Change change = getLastAppliedChange(connectionProvider, option); if (change == null || version.compareTo(change.getId()) > 0) { println(printStream, "Upgrading to: " + version); UpOperation up = new UpOperation(1); while (!version.equals(change.getId())) { up.operate(connectionProvider, migrationsLoader, option, printStream, upHook); change = getLastAppliedChange(connectionProvider, option); } } else if (version.compareTo(change.getId()) < 0) { println(printStream, "Downgrading to: " + version); DownOperation down = new DownOperation(1); while (!version.equals(change.getId())) { down.operate(connectionProvider, migrationsLoader, option, printStream, downHook); change = getLastAppliedChange(connectionProvider, option); } } else { println(printStream, "Already at version: " + version); } println(printStream); return this; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader, DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) { if (option == null) { option = new DatabaseOperationOption(); } List<Change> changesInDb = getChangelog(connectionProvider, option); List<Change> migrations = migrationsLoader.getMigrations(); Change specified = new Change(version); if (!migrations.contains(specified)) { throw new MigrationException("A migration for the specified version number does not exist."); } Change lastChangeInDb = changesInDb.isEmpty() ? null : changesInDb.get(changesInDb.size() - 1); if (lastChangeInDb == null || specified.compareTo(lastChangeInDb) > 0) { println(printStream, "Upgrading to: " + version); int steps = 0; for (Change change : migrations) { if (change.compareTo(lastChangeInDb) > 0 && change.compareTo(specified) < 1) { steps++; } } new UpOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, upHook); } else if (specified.compareTo(lastChangeInDb) < 0) { println(printStream, "Downgrading to: " + version); int steps = 0; for (Change change : migrations) { if (change.compareTo(specified) > -1 && change.compareTo(lastChangeInDb) < 0) { steps++; } } new DownOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, downHook); } else { println(printStream, "Already at version: " + version); } println(printStream); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ClassLoader getDriverClassLoader() { File localDriverPath = getCustomDriverPath(); if (driverClassLoader != null) { return driverClassLoader; } else if (localDriverPath.exists()) { try { List<URL> urlList = new ArrayList<URL>(); for (File file : localDriverPath.listFiles()) { String filename = file.getCanonicalPath(); if (!filename.startsWith("/")) { filename = "/" + filename; } urlList.add(new URL("jar:file:" + filename + "!/")); urlList.add(new URL("file:" + filename)); } URL[] urls = urlList.toArray(new URL[urlList.size()]); return new URLClassLoader(urls); } catch (Exception e) { throw new MigrationException("Error creating a driver ClassLoader. Cause: " + e, e); } } return null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private ClassLoader getDriverClassLoader() { File localDriverPath = getCustomDriverPath(); if (driverClassLoader != null) { return driverClassLoader; } else if (localDriverPath.exists()) { try { List<URL> urlList = new ArrayList<>(); File[] files = localDriverPath.listFiles(); if (files != null) { for (File file : files) { String filename = file.getCanonicalPath(); if (!filename.startsWith("/")) { filename = "/" + filename; } urlList.add(new URL("jar:file:" + filename + "!/")); urlList.add(new URL("file:" + filename)); } } URL[] urls = urlList.toArray(new URL[0]); return new URLClassLoader(urls); } catch (Exception e) { throw new MigrationException("Error creating a driver ClassLoader. Cause: " + e, e); } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetConfiguredTemplate() { String templateName = ""; try { FileWriter fileWriter = new FileWriter(tempFile); fileWriter.append("new_command.template=templates/col_new_template_migration.sql"); fileWriter.flush(); templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template"); assertEquals("templates/col_new_template_migration.sql", templateName); } catch (Exception e) { fail("Test failed with execption: " + e.getMessage()); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetConfiguredTemplate() { String templateName = ""; try { FileWriter fileWriter = new FileWriter(tempFile); try { fileWriter.append("new_command.template=templates/col_new_template_migration.sql"); fileWriter.flush(); templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template"); assertEquals("templates/col_new_template_migration.sql", templateName); } finally { fileWriter.close(); } } catch (Exception e) { fail("Test failed with execption: " + e.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader, DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) { if (option == null) { option = new DatabaseOperationOption(); } ensureVersionExists(migrationsLoader); Change change = getLastAppliedChange(connectionProvider, option); if (change == null || version.compareTo(change.getId()) > 0) { println(printStream, "Upgrading to: " + version); UpOperation up = new UpOperation(1); while (!version.equals(change.getId())) { up.operate(connectionProvider, migrationsLoader, option, printStream, upHook); change = getLastAppliedChange(connectionProvider, option); } } else if (version.compareTo(change.getId()) < 0) { println(printStream, "Downgrading to: " + version); DownOperation down = new DownOperation(1); while (!version.equals(change.getId())) { down.operate(connectionProvider, migrationsLoader, option, printStream, downHook); change = getLastAppliedChange(connectionProvider, option); } } else { println(printStream, "Already at version: " + version); } println(printStream); return this; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public VersionOperation operate(ConnectionProvider connectionProvider, MigrationLoader migrationsLoader, DatabaseOperationOption option, PrintStream printStream, MigrationHook upHook, MigrationHook downHook) { if (option == null) { option = new DatabaseOperationOption(); } List<Change> changesInDb = getChangelog(connectionProvider, option); List<Change> migrations = migrationsLoader.getMigrations(); Change specified = new Change(version); if (!migrations.contains(specified)) { throw new MigrationException("A migration for the specified version number does not exist."); } Change lastChangeInDb = changesInDb.isEmpty() ? null : changesInDb.get(changesInDb.size() - 1); if (lastChangeInDb == null || specified.compareTo(lastChangeInDb) > 0) { println(printStream, "Upgrading to: " + version); int steps = 0; for (Change change : migrations) { if (change.compareTo(lastChangeInDb) > 0 && change.compareTo(specified) < 1) { steps++; } } new UpOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, upHook); } else if (specified.compareTo(lastChangeInDb) < 0) { println(printStream, "Downgrading to: " + version); int steps = 0; for (Change change : migrations) { if (change.compareTo(specified) > -1 && change.compareTo(lastChangeInDb) < 0) { steps++; } } new DownOperation(steps).operate(connectionProvider, migrationsLoader, option, printStream, downHook); } else { println(printStream, "Already at version: " + version); } println(printStream); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetConfiguredTemplate() { String templateName = ""; try { FileWriter fileWriter = new FileWriter(tempFile); fileWriter.append("new_command.template=templates/col_new_template_migration.sql"); fileWriter.flush(); templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template"); assertEquals("templates/col_new_template_migration.sql", templateName); } catch (Exception e) { fail("Test failed with execption: " + e.getMessage()); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetConfiguredTemplate() { String templateName = ""; try { FileWriter fileWriter = new FileWriter(tempFile); try { fileWriter.append("new_command.template=templates/col_new_template_migration.sql"); fileWriter.flush(); templateName = ExternalResources.getConfiguredTemplate(tempFile.getAbsolutePath(), "new_command.template"); assertEquals("templates/col_new_template_migration.sql", templateName); } finally { fileWriter.close(); } } catch (Exception e) { fail("Test failed with execption: " + e.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void save(MethodNode methodNode) { try { MethodNodeService methodNodeService = ApplicationContextHelper.popBean(MethodNodeService.class); methodNodeService.saveNotRedo(methodNode); } catch (Exception e) { logger.error("methodNodeService保存方法节点失败"); e.printStackTrace(); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private static void save(MethodNode methodNode) { try { MethodNodeService methodNodeService = ApplicationContextHelper.popBean(MethodNodeService.class); assert methodNodeService != null; methodNodeService.saveNotRedo(methodNode); } catch (Exception e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code byte[] readFile(File file) throws IOException { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int n = 0; byte[] buffer = new byte[BUFFER_LEN]; while ((n = fis.read(buffer)) != -1) { // System.out.println("ba="+new String(buffer, "UTF-8")); baos.write(buffer, 0, n); } fis.close(); return baos.toByteArray(); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code InplaceFileConverter(RuleSet ruleSet) { this.lineConverter = new LineConverter(ruleSet); lineTerminator = System.getProperty("line.separator"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void convert(File file, byte[] input) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(input); Reader reader = new InputStreamReader(bais); BufferedReader breader = new BufferedReader(reader); FileWriter fileWriter = new FileWriter(file); while (true) { String line = breader.readLine(); if (line != null) { String[] replacement = lineConverter.getReplacement(line); writeReplacement(fileWriter, replacement); } else { fileWriter.close(); break; } } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code InplaceFileConverter(RuleSet ruleSet) { this.lineConverter = new LineConverter(ruleSet); lineTerminator = System.getProperty("line.separator"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean contains(String name) { if(name == null) { return false; } if(factory.exists(name)) { Marker other = factory.getMarker(name); return contains(other); } else { return false; } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean contains(String name) { throw new UnsupportedOperationException("This method has been deprecated."); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Iterator<Marker> iterator() { if (referenceList != null) { return referenceList.iterator(); } else { List<Marker> emptyList = Collections.emptyList(); return emptyList.iterator(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Iterator<Marker> iterator() { return referenceList.iterator(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void convert(File file, byte[] input) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(input); Reader reader = new InputStreamReader(bais); BufferedReader breader = new BufferedReader(reader); FileWriter fileWriter = new FileWriter(file); while (true) { String line = breader.readLine(); if (line != null) { String[] replacement = lineConverter.getReplacement(line); writeReplacement(fileWriter, replacement); } else { fileWriter.close(); break; } } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code InplaceFileConverter(RuleSet ruleSet) { this.lineConverter = new LineConverter(ruleSet); lineTerminator = System.getProperty("line.separator"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ILoggerFactory getILoggerFactory() { if (INITIALIZATION_STATE == UNINITIALIZED) { synchronized (LoggerFactory.class) { if (INITIALIZATION_STATE == UNINITIALIZED) { INITIALIZATION_STATE = ONGOING_INITIALIZATION; performInitialization(); } } } switch (INITIALIZATION_STATE) { case SUCCESSFUL_INITIALIZATION: return StaticLoggerBinder.getSingleton().getLoggerFactory(); case NOP_FALLBACK_INITIALIZATION: return NOP_FALLBACK_FACTORY; case FAILED_INITIALIZATION: throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); case ONGOING_INITIALIZATION: // support re-entrant behavior. // See also http://jira.qos.ch/browse/SLF4J-97 return SUBST_FACTORY; } throw new IllegalStateException("Unreachable code"); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static ILoggerFactory getILoggerFactory() { if (INITIALIZATION_STATE == UNINITIALIZED) { synchronized (LoggerFactory.class) { if (INITIALIZATION_STATE == UNINITIALIZED) { INITIALIZATION_STATE = ONGOING_INITIALIZATION; performInitialization(); } } } switch (INITIALIZATION_STATE) { case SUCCESSFUL_INITIALIZATION: return StaticLoggerBinder.getSingleton().getLoggerFactory(); case NOP_FALLBACK_INITIALIZATION: return NOP_FALLBACK_FACTORY; case FAILED_INITIALIZATION: throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); case ONGOING_INITIALIZATION: // support re-entrant behavior. // See also http://jira.qos.ch/browse/SLF4J-97 return SUBST_FACTORY; } throw new IllegalStateException("Unreachable code"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean contains(String name) { if (name == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.name.equals(name)) { return true; } if (hasChildren()) { for (int i = 0; i < children.size(); i++) { Marker child = (Marker) children.get(i); if (child.contains(name)) { return true; } } } return false; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean contains(String name) { if (name == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.name.equals(name)) { return true; } if (hasReferences()) { for (int i = 0; i < refereceList.size(); i++) { Marker ref = (Marker) refereceList.get(i); if (ref.contains(name)) { return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean contains(String name) { if (name == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.name.equals(name)) { return true; } if (hasReferences()) { for (int i = 0; i < refereceList.size(); i++) { Marker ref = (Marker) refereceList.get(i); if (ref.contains(name)) { return true; } } } return false; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean contains(String name) { if (name == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.name.equals(name)) { return true; } if (hasReferences()) { for (int i = 0; i < referenceList.size(); i++) { Marker ref = (Marker) referenceList.get(i); if (ref.contains(name)) { return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean contains(Marker other) { if (other == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.equals(other)) { return true; } if (hasChildren()) { for (int i = 0; i < children.size(); i++) { Marker child = (Marker) children.get(i); if (child.contains(other)) { return true; } } } return false; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean contains(Marker other) { if (other == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.equals(other)) { return true; } if (hasReferences()) { for (int i = 0; i < refereceList.size(); i++) { Marker ref = (Marker) refereceList.get(i); if (ref.contains(other)) { return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean contains(Marker other) { if (other == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.equals(other)) { return true; } if (hasReferences()) { for (int i = 0; i < refereceList.size(); i++) { Marker ref = (Marker) refereceList.get(i); if (ref.contains(other)) { return true; } } } return false; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean contains(Marker other) { if (other == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.equals(other)) { return true; } if (hasReferences()) { for (int i = 0; i < referenceList.size(); i++) { Marker ref = (Marker) referenceList.get(i); if (ref.contains(other)) { return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean contains(String name) { if(name == null) { return false; } if(factory.exists(name)) { Marker other = factory.getMarker(name); return contains(other); } else { return false; } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean contains(String name) { if(name == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.name.equals(name)) { return true; } if (hasChildren()) { for(int i = 0; i < children.size(); i++) { Marker child = (Marker) children.get(i); if(child.contains(name)) { return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static boolean deleteFileOrDirectory(File path) throws MojoFailureException { if (path.isDirectory()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { if (!deleteFileOrDirectory(files[i])) { throw new MojoFailureException("Can't delete dir " + files[i]); } } else { if (!files[i].delete()) { throw new MojoFailureException("Can't delete file " + files[i]); } } } return path.delete(); } else { return path.delete(); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private static boolean deleteFileOrDirectory(File path) throws MojoFailureException { if (path.isDirectory()) { File[] files = path.listFiles(); if (null != files) { for (File file : files) { if (file.isDirectory()) { if (!deleteFileOrDirectory(file)) { throw new MojoFailureException("Can't delete dir " + file); } } else { if (!file.delete()) { throw new MojoFailureException("Can't delete file " + file); } } } } return path.delete(); } else { return path.delete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void verifyNode(Node node) { if (node == null) return; // Pre-order traversal. verifyNodes(node.children()); if (node instanceof Call) { Call call = (Call) node; // Skip resolving property derefs. if (call.isJavaStatic() || call.isPostfix()) return; verifyNode(call.args()); FunctionDecl targetFunction = resolveCall(call.name); if (targetFunction == null) addError("Cannot resolve function: " + call.name, call.sourceLine, call.sourceColumn); else { // Check that the args are correct. int targetArgs = targetFunction.arguments().children().size(); int calledArgs = call.args().children().size(); if (calledArgs != targetArgs) addError("Incorrect number of arguments to: " + targetFunction.name() + " (expected " + targetArgs + ", found " + calledArgs + ")", call.sourceLine, call.sourceColumn); } } else if (node instanceof PatternRule) { PatternRule patternRule = (PatternRule) node; verifyNode(patternRule.rhs); // Some sanity checking of pattern rules. FunctionDecl function = functionStack.peek().function; int argsSize = function.arguments().children().size(); int patternsSize = patternRule.patterns.size(); if (patternsSize != argsSize) addError("Incorrect number of patterns in: '" + function.name() + "' (expected " + argsSize + " found " + patternsSize + ")", patternRule.sourceLine, patternRule.sourceColumn); } else if (node instanceof Guard) { Guard guard = (Guard) node; verifyNode(guard.expression); verifyNode(guard.line); } else if (node instanceof Variable) { Variable var = (Variable) node; if (!resolveVar(var.name)) addError("Cannot resolve symbol: " + var.name, var.sourceLine, var.sourceColumn); } else if (node instanceof ConstructorCall) { ConstructorCall call = (ConstructorCall) node; if (!resolveType(call)) addError("Cannot resolve type (either as loop or Java): " + (call.modulePart == null ? "" : call.modulePart) + call.name, call.sourceLine, call.sourceColumn); } } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code private void verifyNode(Node node) { if (node == null) return; // Pre-order traversal. verifyNodes(node.children()); if (node instanceof Call) { Call call = (Call) node; // Skip resolving property derefs. if (call.isJavaStatic() || call.isPostfix()) return; verifyNode(call.args()); FunctionDecl targetFunction = resolveCall(call.name); if (targetFunction == null) addError("Cannot resolve function: " + call.name, call.sourceLine, call.sourceColumn); else { // Check that the args are correct. int targetArgs = targetFunction.arguments().children().size(); int calledArgs = call.args().children().size(); if (calledArgs != targetArgs) addError("Incorrect number of arguments to: " + targetFunction.name() + " (expected " + targetArgs + ", found " + calledArgs + ")", call.sourceLine, call.sourceColumn); } } else if (node instanceof PatternRule) { PatternRule patternRule = (PatternRule) node; verifyNode(patternRule.rhs); // Some sanity checking of pattern rules. FunctionDecl function = functionStack.peek().function; int argsSize = function.arguments().children().size(); int patternsSize = patternRule.patterns.size(); if (patternsSize != argsSize) addError("Incorrect number of patterns in: '" + function.name() + "' (expected " + argsSize + " found " + patternsSize + ")", patternRule.sourceLine, patternRule.sourceColumn); } else if (node instanceof Guard) { Guard guard = (Guard) node; verifyNode(guard.expression); verifyNode(guard.line); } else if (node instanceof Variable) { Variable var = (Variable) node; if (!resolveVar(var.name)) addError("Cannot resolve symbol: " + var.name, var.sourceLine, var.sourceColumn); } else if (node instanceof ConstructorCall) { ConstructorCall call = (ConstructorCall) node; if (!resolveType(call)) addError("Cannot resolve type (either as loop or Java): " + (call.modulePart == null ? "" : call.modulePart) + call.name, call.sourceLine, call.sourceColumn); } else if (node instanceof Assignment) { // Make sure that you cannot reassign function arguments. Assignment assignment = (Assignment) node; if (assignment.lhs() instanceof Variable) { Variable lhs = (Variable) assignment.lhs(); FunctionContext functionContext = functionStack.peek(); for (Node argument : functionContext.function.arguments().children()) { ArgDeclList.Argument arg = (ArgDeclList.Argument) argument; if (arg.name().equals(lhs.name)) addError("Illegal argument reassignment (declare a local variable instead)", lhs.sourceLine, lhs.sourceColumn); } // verifyNode(assignment.rhs()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public final void evalLispFile() { Loop.evalLisp("default", new InputStreamReader(LispEvaluatorTest.class.getResourceAsStream("funcs.lisp"))); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test public final void evalLispFile() { // Loop.evalLisp("default", new InputStreamReader(LispEvaluatorTest.class.getResourceAsStream("funcs.lisp"))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String processVForValue(String vForValue) { VForDefinition vForDef = new VForDefinition(vForValue, context); // Set return of the "in" expression currentExpressionReturnType = vForDef.getInExpressionType(); String inExpression = vForDef.getInExpression(); // Process in expression if it's java if (vForDef.isInExpressionJava()) { inExpression = this.processExpression(inExpression); } // And return the newly built definition return vForDef.getVariableDefinition() + " in " + inExpression; } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private String processVForValue(String vForValue) { VForDefinition vForDef = new VForDefinition(vForValue, context); // Set return of the "in" expression currentExpressionReturnType = vForDef.getInExpressionType(); String inExpression = this.processExpression(vForDef.getInExpression()); // And return the newly built definition return vForDef.getVariableDefinition() + " in " + inExpression; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Property(trials = 10) public void shouldCollectToSetWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<Set<Long>, Long> result = timed(collectWith(inParallelToSet(executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(1); }); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Property(trials = 10) public void shouldCollectToSetWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<Set<Long>, Long> result = timed(collectWith(parallelToSet(executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(1); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Property(trials = TRIALS) public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork, BLOCKING_MILLIS); Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToList(executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Property(trials = TRIALS) public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork, BLOCKING_MILLIS); Map.Entry<List<Long>, Long> result = timed(collectWith(f -> parallelToList(f, executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Property(trials = 10) public void shouldCollectToCollectionWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<List<Long>, Long> result = timed(collectWith(inParallelToCollection(ArrayList::new, executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Property(trials = 10) public void shouldCollectToCollectionWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToCollection(ArrayList::new, executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Property(trials = TRIALS) public void shouldCollectToCollectionWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork, BLOCKING_MILLIS); Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToCollection(ArrayList::new, executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Property(trials = TRIALS) public void shouldCollectToCollectionWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork, BLOCKING_MILLIS); Map.Entry<List<Long>, Long> result = timed(collectWith(f -> parallelToCollection(f, ArrayList::new, executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Property(trials = TRIALS) public void shouldCollectToSetWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<Set<Long>, Long> result = timed(collectWith(parallelToSet(executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(1); }); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Property(trials = TRIALS) public void shouldCollectToSetWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<Set<Long>, Long> result = timed(collectWith(f-> parallelToSet(f, executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(1); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Property(trials = 10) public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<List<Long>, Long> result = timed(collectWith(inParallelToList(executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Property(trials = 10) public void shouldCollectToListWithThrottledParallelism(@InRange(minInt = 2, maxInt = 20) int unitsOfWork, @InRange(minInt = 1, maxInt = 40) int parallelism) { // given executor = threadPoolExecutor(unitsOfWork); long expectedDuration = expectedDuration(parallelism, unitsOfWork); Map.Entry<List<Long>, Long> result = timed(collectWith(parallelToList(executor, parallelism), unitsOfWork)); assertThat(result) .satisfies(e -> { assertThat(e.getValue()) .isGreaterThanOrEqualTo(expectedDuration) .isCloseTo(expectedDuration, offset(CONSTANT_DELAY)); assertThat(e.getKey()).hasSize(unitsOfWork); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testToMap() throws SQLException { int rowCount = 0; Map m = null; while (this.rs.next()) { m = processor.toMap(this.rs); assertNotNull(m); assertEquals(COLS, m.keySet().size()); rowCount++; } assertEquals(ROWS, rowCount); assertEquals("4", m.get("One")); // case shouldn't matter assertEquals("5", m.get("two")); assertEquals("6", m.get("THREE")); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public void testToMap() throws SQLException { assertTrue(this.rs.next()); Map m = processor.toMap(this.rs); assertEquals(COLS, m.keySet().size()); assertEquals("1", m.get("one")); assertEquals("2", m.get("TWO")); assertEquals("3", m.get("Three")); assertTrue(this.rs.next()); m = processor.toMap(this.rs); assertEquals(COLS, m.keySet().size()); assertEquals("4", m.get("One")); // case shouldn't matter assertEquals("5", m.get("two")); assertEquals("6", m.get("THREE")); assertFalse(this.rs.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testNext() { Iterator iter = new ResultSetIterator(this.rs); int rowCount = 0; Object[] row = null; while (iter.hasNext()) { rowCount++; row = (Object[]) iter.next(); assertNotNull(row); assertEquals(COLS, row.length); } assertEquals(ROWS, rowCount); assertEquals("4", row[0]); assertEquals("5", row[1]); assertEquals("6", row[2]); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code public void testNext() { Iterator iter = new ResultSetIterator(this.rs); Object[] row = null; assertTrue(iter.hasNext()); row = (Object[]) iter.next(); assertEquals(COLS, row.length); assertEquals("1", row[0]); assertEquals("2", row[1]); assertEquals("3", row[2]); assertTrue(iter.hasNext()); row = (Object[]) iter.next(); assertEquals(COLS, row.length); assertEquals("4", row[0]); assertEquals("5", row[1]); assertEquals("6", row[2]); assertFalse(iter.hasNext()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testToArray() throws SQLException { int rowCount = 0; Object[] a = null; while (this.rs.next()) { a = processor.toArray(this.rs); assertEquals(COLS, a.length); rowCount++; } assertEquals(ROWS, rowCount); assertEquals("4", a[0]); assertEquals("5", a[1]); assertEquals("6", a[2]); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public void testToArray() throws SQLException { Object[] a = null; assertTrue(this.rs.next()); a = processor.toArray(this.rs); assertEquals(COLS, a.length); assertEquals("1", a[0]); assertEquals("2", a[1]); assertEquals("3", a[2]); assertTrue(this.rs.next()); a = processor.toArray(this.rs); assertEquals(COLS, a.length); assertEquals("4", a[0]); assertEquals("5", a[1]); assertEquals("6", a[2]); assertFalse(this.rs.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testProcess() throws SQLException { int rowCount = 0; TestBean b = null; while (this.rs.next()) { b = (TestBean) beanProc.toBean(this.rs, TestBean.class); assertNotNull(b); rowCount++; } assertEquals(ROWS, rowCount); assertEquals(13.0, b.getColumnProcessorDoubleTest(), 0); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public void testProcess() throws SQLException { TestBean b = null; assertTrue(this.rs.next()); b = (TestBean) beanProc.toBean(this.rs, TestBean.class); assertEquals(13.0, b.getColumnProcessorDoubleTest(), 0); assertTrue(this.rs.next()); b = (TestBean) beanProc.toBean(this.rs, TestBean.class); assertEquals(13.0, b.getColumnProcessorDoubleTest(), 0); assertFalse(this.rs.next()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHandle() throws SQLException { ResultSetHandler h = new BeanListHandler(TestBean.class); List results = (List) h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Iterator iter = results.iterator(); TestBean row = null; while (iter.hasNext()) { row = (TestBean) iter.next(); assertNotNull(row); } assertEquals("4", row.getOne()); assertEquals("5", row.getTwo()); assertEquals("6", row.getThree()); assertEquals("not set", row.getDoNotSet()); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public void testHandle() throws SQLException { ResultSetHandler h = new BeanListHandler(TestBean.class); List results = (List) h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Iterator iter = results.iterator(); TestBean row = null; assertTrue(iter.hasNext()); row = (TestBean) iter.next(); assertEquals("1", row.getOne()); assertEquals("2", row.getTwo()); assertEquals("3", row.getThree()); assertEquals("not set", row.getDoNotSet()); assertTrue(iter.hasNext()); row = (TestBean) iter.next(); assertEquals("4", row.getOne()); assertEquals("5", row.getTwo()); assertEquals("6", row.getThree()); assertEquals("not set", row.getDoNotSet()); assertFalse(iter.hasNext()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testColumnNameHandle() throws SQLException { ResultSetHandler<Map<Object,Map<String,Object>>> h = new KeyedHandler("three"); Map<Object,Map<String,Object>> results = h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Map<String,Object> row = null; for(Entry<Object, Map<String, Object>> entry : results.entrySet()) { Object key = entry.getKey(); assertNotNull(key); row = entry.getValue(); assertNotNull(row); assertEquals(COLS, row.keySet().size()); } row = results.get("6"); assertEquals("4", row.get("one")); assertEquals("5", row.get("TWO")); assertEquals("6", row.get("Three")); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public void testColumnNameHandle() throws SQLException { ResultSetHandler<Map<Integer,Map<String,Object>>> h = new KeyedHandler<Integer>("intTest"); Map<Integer,Map<String,Object>> results = h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Map<String,Object> row = null; for(Entry<Integer, Map<String, Object>> entry : results.entrySet()) { Object key = entry.getKey(); assertNotNull(key); row = entry.getValue(); assertNotNull(row); assertEquals(COLS, row.keySet().size()); } row = results.get(3); assertEquals("4", row.get("one")); assertEquals("5", row.get("TWO")); assertEquals("6", row.get("Three")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHandle() throws SQLException { ResultSetHandler h = new ArrayListHandler(); List results = (List) h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Iterator iter = results.iterator(); Object[] row = null; while (iter.hasNext()) { row = (Object[]) iter.next(); assertEquals(COLS, row.length); } assertEquals("4", row[0]); assertEquals("5", row[1]); assertEquals("6", row[2]); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public void testHandle() throws SQLException { ResultSetHandler h = new ArrayListHandler(); List results = (List) h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Iterator iter = results.iterator(); Object[] row = null; assertTrue(iter.hasNext()); row = (Object[]) iter.next(); assertEquals(COLS, row.length); assertEquals("1", row[0]); assertEquals("2", row[1]); assertEquals("3", row[2]); assertTrue(iter.hasNext()); row = (Object[]) iter.next(); assertEquals(COLS, row.length); assertEquals("4", row[0]); assertEquals("5", row[1]); assertEquals("6", row[2]); assertFalse(iter.hasNext()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHandle() throws SQLException { ResultSetHandler h = new MapListHandler(); List results = (List) h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Iterator iter = results.iterator(); Map row = null; while (iter.hasNext()) { row = (Map) iter.next(); assertEquals(COLS, row.keySet().size()); } assertEquals("4", row.get("one")); assertEquals("5", row.get("TWO")); assertEquals("6", row.get("Three")); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public void testHandle() throws SQLException { ResultSetHandler h = new MapListHandler(); List results = (List) h.handle(this.rs); assertNotNull(results); assertEquals(ROWS, results.size()); Iterator iter = results.iterator(); Map row = null; assertTrue(iter.hasNext()); row = (Map) iter.next(); assertEquals(COLS, row.keySet().size()); assertEquals("1", row.get("one")); assertEquals("2", row.get("TWO")); assertEquals("3", row.get("Three")); assertTrue(iter.hasNext()); row = (Map) iter.next(); assertEquals(COLS, row.keySet().size()); assertEquals("4", row.get("one")); assertEquals("5", row.get("TWO")); assertEquals("6", row.get("Three")); assertFalse(iter.hasNext()); }
Below is the vulnerable code, please generate the patch based on the following information.