output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testOnRpcReturnedRpcError() {
testRpcReturnedError();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
}
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
InplaceFileConverter(RuleSet ruleSet) {
this.lineConverter = new LineConverter(ruleSet);
lineTerminator = System.getProperty("line.separator");
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
InplaceFileConverter(RuleSet ruleSet) {
this.lineConverter = new LineConverter(ruleSet);
lineTerminator = System.getProperty("line.separator");
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean contains(String name) {
throw new UnsupportedOperationException("This method has been deprecated.");
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Iterator<Marker> iterator() {
return referenceList.iterator();
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
InplaceFileConverter(RuleSet ruleSet) {
this.lineConverter = new LineConverter(ruleSet);
lineTerminator = System.getProperty("line.separator");
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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");
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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();
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
}
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public final void evalLispFile() {
// Loop.evalLisp("default", new InputStreamReader(LispEvaluatorTest.class.getResourceAsStream("funcs.lisp")));
} | #vulnerable code
@Test
public final void evalLispFile() {
Loop.evalLisp("default", new InputStreamReader(LispEvaluatorTest.class.getResourceAsStream("funcs.lisp")));
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
});
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
});
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
});
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
});
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
});
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
});
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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"));
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testToBean() throws SQLException, ParseException {
TestBean row = null;
assertTrue(this.rs.next());
row = (TestBean) processor.toBean(this.rs, TestBean.class);
assertEquals("1", row.getOne());
assertEquals("2", row.getTwo());
assertEquals("3", row.getThree());
assertEquals("not set", row.getDoNotSet());
assertTrue(this.rs.next());
row = (TestBean) processor.toBean(this.rs, TestBean.class);
assertEquals("4", row.getOne());
assertEquals("5", row.getTwo());
assertEquals("6", row.getThree());
assertEquals("not set", row.getDoNotSet());
assertEquals(3, row.getIntTest());
assertEquals(new Integer(4), row.getIntegerTest());
assertEquals(null, row.getNullObjectTest());
assertEquals(0, row.getNullPrimitiveTest());
// test date -> string handling
assertNotNull(row.getNotDate());
assertTrue(!"not a date".equals(row.getNotDate()));
datef.parse(row.getNotDate());
assertFalse(this.rs.next());
} | #vulnerable code
public void testToBean() throws SQLException, ParseException {
int rowCount = 0;
TestBean b = null;
while (this.rs.next()) {
b = (TestBean) processor.toBean(this.rs, TestBean.class);
assertNotNull(b);
rowCount++;
}
assertEquals(ROWS, rowCount);
assertEquals("4", b.getOne());
assertEquals("5", b.getTwo());
assertEquals("6", b.getThree());
assertEquals("not set", b.getDoNotSet());
assertEquals(3, b.getIntTest());
assertEquals(new Integer(4), b.getIntegerTest());
assertEquals(null, b.getNullObjectTest());
assertEquals(0, b.getNullPrimitiveTest());
// test date -> string handling
assertNotNull(b.getNotDate());
assertTrue(!"not a date".equals(b.getNotDate()));
datef.parse(b.getNotDate());
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void initAuthEnv() {
String paramUserName = getInitParameter(InitServletData.PARAM_NAME_USERNAME);
if (!StringUtils.isEmpty(paramUserName)) {
this.initServletData.setUsername(paramUserName);
}
String paramPassword = getInitParameter(InitServletData.PARAM_NAME_PASSWORD);
if (!StringUtils.isEmpty(paramPassword)) {
this.initServletData.setPassword(paramPassword);
}
try {
String param = getInitParameter(InitServletData.PARAM_NAME_ALLOW);
this.initServletData.setAllowList(parseStringToIP(param));
} catch (Exception e) {
logger.error("initParameter config error, allow : {}", getInitParameter(InitServletData.PARAM_NAME_ALLOW), e);
}
try {
String param = getInitParameter(InitServletData.PARAM_NAME_DENY);
this.initServletData.setDenyList(parseStringToIP(param));
} catch (Exception e) {
logger.error("initParameter config error, deny : {}", getInitParameter(InitServletData.PARAM_NAME_DENY), e);
}
} | #vulnerable code
private void initAuthEnv() {
String paramUserName = getInitParameter(InitServletData.PARAM_NAME_USERNAME);
if (!StringUtils.isEmpty(paramUserName)) {
this.initServletData.setUsername(paramUserName);
}
String paramPassword = getInitParameter(InitServletData.PARAM_NAME_PASSWORD);
if (!StringUtils.isEmpty(paramPassword)) {
this.initServletData.setPassword(paramPassword);
}
try {
String param = getInitParameter(InitServletData.PARAM_NAME_ALLOW);
this.initServletData.setAllowList(parseStringToIP(param));
} catch (Exception e) {
logger.error("initParameter config error, allow : {}", getInitParameter(InitServletData.PARAM_NAME_ALLOW), e);
}
try {
String param = getInitParameter(InitServletData.PARAM_NAME_DENY);
this.initServletData.setDenyList(parseStringToIP(param));
} catch (Exception e) {
logger.error("initParameter config error, deny : {}", getInitParameter(InitServletData.PARAM_NAME_DENY), e);
}
// 采集缓存命中数据
redisTemplate = getRedisTemplate();
BeanFactory.getBean(StatsService.class).syncCacheStats(redisTemplate);
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void test() {
MemoryIndex<String> mi = new MemoryIndex<String>();
// FileIterator instanceFileIterator = IOUtil.instanceFileIterator("/home/ansj/workspace/ansj_seg/library/default.dic", IOUtil.UTF8);
//
long start = System.currentTimeMillis();
// System.out.println("begin init!");
// while (instanceFileIterator.hasNext()) {
// String temp = instanceFileIterator.next();
// temp = temp.split("\t")[0] ;
//
// // temp 是提示返回的元素
// // temp 增加到搜索提示
// // mi.str2QP("字符串转全拼") 比如 “中国” --》 "zhongguo"
// // new String(Pinyin.str2FirstCharArr(temp)) 字符串首字母拼音 比如 “中国” --》 "zg"
// mi.addItem(temp, temp ,mi.str2QP(temp), new String(Pinyin.str2FirstCharArr(temp)));
// }
//增加新词
String temp = "中国" ;
//生成各需要建立索引的字段
String quanpin = mi.str2QP(temp) ; //zhongguo
String jianpinpin = new String(Pinyin.str2FirstCharArr(temp)) ; //zg
//增加到索引中
mi.addItem(temp, temp ,quanpin,jianpinpin);
System.out.println(mi.suggest("zg"));
System.out.println(mi.suggest("zhongguo"));
System.out.println(mi.suggest("中国"));
System.out.println(mi.smartSuggest("中过"));
System.out.println("init ok use time " + (System.currentTimeMillis() - start));
} | #vulnerable code
@Test
public void test() {
MemoryIndex<String> mi = new MemoryIndex<String>();
FileIterator instanceFileIterator = IOUtil.instanceFileIterator("/home/ansj/workspace/ansj_seg/library/default.dic", IOUtil.UTF8);
long start = System.currentTimeMillis();
System.out.println("begin init!");
while (instanceFileIterator.hasNext()) {
String temp = instanceFileIterator.next();
temp = temp.split("\t")[0] ;
// temp 是提示返回的元素
// temp 增加到搜索提示
// mi.str2QP("字符串转全拼") 比如 “中国” --》 "zhongguo"
// new String(Pinyin.str2FirstCharArr(temp)) 字符串首字母拼音 比如 “中国” --》 "zg"
mi.addItem(temp, temp ,mi.str2QP(temp), new String(Pinyin.str2FirstCharArr(temp)));
}
System.out.println("init ok use time " + (System.currentTimeMillis() - start));
System.out.println(mi.suggest("zg"));
System.out.println(mi.suggest("zhongguo"));
System.out.println(mi.suggest("中国"));
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void saveModel(String filePath) throws IOException {
ObjectOutput oot = new ObjectOutputStream(new FileOutputStream(filePath));
oot.writeObject(this);
} | #vulnerable code
public void saveModel(String filePath) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ;
writeMap(bw,idWordMap) ;
writeMap(bw,word2Mc) ;
writeMap(bw,ww2Mc.get()) ;
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static int getIntValue(String value) {
if (StringUtil.isBlank(value)) {
return 0;
}
return castToInteger(value);
} | #vulnerable code
public static int getIntValue(String value) {
if (StringUtil.isBlank(value)) {
return 0;
}
return castToInt(value);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void saveModel(String filePath) throws IOException {
ObjectOutput oot = new ObjectOutputStream(new FileOutputStream(filePath));
oot.writeObject(this);
} | #vulnerable code
public void saveModel(String filePath) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath))) ;
writeMap(bw,idWordMap) ;
writeMap(bw,word2Mc) ;
writeMap(bw,ww2Mc.get()) ;
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout).createClient();
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
return client;
} | #vulnerable code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes host " + getDisplayName() + " URL " + serverUrl);
if (client == null) {
synchronized (this) {
if (client == null) {
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout)
.createClient();
}
}
}
return client;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = pod.getSpec().getContainers().stream()
.collect(Collectors.toMap(Container::getName, Function.identity()));
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = pod.getSpec().getVolumes().stream()
.collect(Collectors.toMap(Volume::getName, Function.identity()));
assertEquals(3, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
assertNotNull(volumes.get("host-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(2, mounts.size());
assertEquals(new VolumeMount("/container/data", "host-volume", null, null), mounts.get(0));
assertEquals(new VolumeMount("/home/jenkins", "workspace-volume", false, null), mounts.get(1));
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
} | #vulnerable code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = new HashMap<>();
for (Container c : pod.getSpec().getContainers()) {
containers.put(c.getName(), c);
}
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = new HashMap<>();
for (Volume v : pod.getSpec().getVolumes()) {
volumes.put(v.getName(), v);
}
assertEquals(2, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(1, mounts.size());
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout).createClient();
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}" + serverUrl,
new String[] { getDisplayName(), serverUrl });
return client;
} | #vulnerable code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes host " + getDisplayName() + " URL " + serverUrl);
if (client == null) {
synchronized (this) {
if (client == null) {
client = new KubernetesFactoryAdapter(serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify, connectTimeout, readTimeout)
.createClient();
}
}
}
return client;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = pod.getSpec().getContainers().stream()
.collect(Collectors.toMap(Container::getName, Function.identity()));
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = pod.getSpec().getVolumes().stream()
.collect(Collectors.toMap(Volume::getName, Function.identity()));
assertEquals(3, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
assertNotNull(volumes.get("host-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(2, mounts.size());
assertEquals(new VolumeMount("/container/data", "host-volume", null, null), mounts.get(0));
assertEquals(new VolumeMount("/home/jenkins", "workspace-volume", false, null), mounts.get(1));
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
} | #vulnerable code
private void validatePod(Pod pod) {
assertEquals(ImmutableMap.of("some-label", "some-label-value"), pod.getMetadata().getLabels());
// check containers
Map<String, Container> containers = new HashMap<>();
for (Container c : pod.getSpec().getContainers()) {
containers.put(c.getName(), c);
}
assertEquals(2, containers.size());
assertEquals("busybox", containers.get("busybox").getImage());
assertEquals("jenkins/jnlp-slave:alpine", containers.get("jnlp").getImage());
// check volumes and volume mounts
Map<String, Volume> volumes = new HashMap<>();
for (Volume v : pod.getSpec().getVolumes()) {
volumes.put(v.getName(), v);
}
assertEquals(2, volumes.size());
assertNotNull(volumes.get("workspace-volume"));
assertNotNull(volumes.get("empty-volume"));
List<VolumeMount> mounts = containers.get("busybox").getVolumeMounts();
assertEquals(1, mounts.size());
mounts = containers.get("jnlp").getVolumeMounts();
assertEquals(1, mounts.size());
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static List<KubernetesCloud> getUsageRestrictedKubernetesClouds() {
List<KubernetesCloud> clouds = Jenkins.get().clouds
.getAll(KubernetesCloud.class)
.stream()
.filter(KubernetesCloud::isUsageRestricted)
.collect(Collectors.toList());
Collections.sort(clouds, Comparator.<Cloud, String>comparing(o -> o.name));
return clouds;
} | #vulnerable code
private static List<KubernetesCloud> getUsageRestrictedKubernetesClouds() {
List<KubernetesCloud> clouds = new ArrayList<>();
for (Cloud cloud : Jenkins.getInstance().clouds) {
if(cloud instanceof KubernetesCloud) {
if (((KubernetesCloud) cloud).isUsageRestricted()) {
clouds.add((KubernetesCloud) cloud);
}
}
}
Collections.sort(clouds, CLOUD_BY_NAME);
return clouds;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
@SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine")
public synchronized void launch(SlaveComputer computer, TaskListener listener) {
if (!(computer instanceof KubernetesComputer)) {
throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer");
}
KubernetesComputer kubernetesComputer = (KubernetesComputer) computer;
computer.setAcceptingTasks(false);
KubernetesSlave slave = kubernetesComputer.getNode();
if (slave == null) {
throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName());
}
if (launched) {
LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName());
computer.setAcceptingTasks(true);
return;
}
final PodTemplate template = slave.getTemplate();
try {
KubernetesClient client = slave.getKubernetesCloud().connect();
Pod pod = template.build(slave);
slave.assignPod(pod);
String podName = pod.getMetadata().getName();
String namespace = Arrays.asList( //
pod.getMetadata().getNamespace(),
template.getNamespace(), client.getNamespace()) //
.stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null);
slave.setNamespace(namespace);
TaskListener runListener = template.getListener();
LOGGER.log(FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName });
try {
pod = client.pods().inNamespace(namespace).create(pod);
} catch (KubernetesClientException e) {
int httpCode = e.getCode();
if (400 <= httpCode && httpCode < 500) { // 4xx
runListener.getLogger().printf("ERROR: Unable to create pod %s/%s.%n%s%n", namespace, pod.getMetadata().getName(), e.getMessage());
PodUtils.cancelQueueItemFor(pod, e.getMessage());
} else if (500 <= httpCode && httpCode < 600) { // 5xx
LOGGER.log(FINE,"Kubernetes returned HTTP code {0} {1}. Retrying...", new Object[] {e.getCode(), e.getStatus()});
} else {
LOGGER.log(WARNING, "Kubernetes returned unhandled HTTP code {0} {1}", new Object[] {e.getCode(), e.getStatus()});
}
throw e;
}
LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName });
listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
template.getWorkspaceVolume().createVolume(client, pod.getMetadata());
watcher = new AllContainersRunningPodWatcher(client, pod, runListener);
try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher);
Watch w2 = eventWatch(client, podName, namespace, runListener)) {
assert watcher != null; // assigned 3 lines above
watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS);
}
LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName });
// We need the pod to be running and connected before returning
// otherwise this method keeps being called multiple times
List<String> validStates = ImmutableList.of("Running");
int waitForSlaveToConnect = template.getSlaveConnectTimeout();
int waitedForSlave;
// now wait for agent to be online
SlaveComputer slaveComputer = null;
String status = null;
List<ContainerStatus> containerStatuses = null;
long lastReportTimestamp = System.currentTimeMillis();
for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) {
slaveComputer = slave.getComputer();
if (slaveComputer == null) {
throw new IllegalStateException("Node was deleted, computer is null");
}
if (slaveComputer.isOnline()) {
break;
}
// Check that the pod hasn't failed already
pod = client.pods().inNamespace(namespace).withName(podName).get();
if (pod == null) {
throw new IllegalStateException("Pod no longer exists: " + podName);
}
status = pod.getStatus().getPhase();
if (!validStates.contains(status)) {
break;
}
containerStatuses = pod.getStatus().getContainerStatuses();
List<ContainerStatus> terminatedContainers = new ArrayList<>();
for (ContainerStatus info : containerStatuses) {
if (info != null) {
if (info.getState().getTerminated() != null) {
// Container has errored
LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}",
new Object[] { podName, info.getState().getTerminated(), info.getName() });
listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName,
info.getState().getTerminated(), info.getName());
terminatedContainers.add(info);
}
}
}
checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client);
if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) {
LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}",
new Object[]{podName, waitedForSlave, waitForSlaveToConnect});
listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave,
waitForSlaveToConnect);
lastReportTimestamp = System.currentTimeMillis();
}
Thread.sleep(1000);
}
if (slaveComputer == null || slaveComputer.isOffline()) {
logLastLines(containerStatuses, podName, namespace, slave, null, client);
throw new IllegalStateException(
"Agent is not connected after " + waitedForSlave + " seconds, status: " + status);
}
computer.setAcceptingTasks(true);
launched = true;
try {
// We need to persist the "launched" setting...
slave.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e);
}
} catch (Throwable ex) {
setProblem(ex);
LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex);
LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName());
try {
slave.terminate();
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e);
}
throw Throwables.propagate(ex);
}
} | #vulnerable code
@Override
@SuppressFBWarnings(value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "This is fine")
public synchronized void launch(SlaveComputer computer, TaskListener listener) {
if (!(computer instanceof KubernetesComputer)) {
throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer");
}
KubernetesComputer kubernetesComputer = (KubernetesComputer) computer;
computer.setAcceptingTasks(false);
KubernetesSlave slave = kubernetesComputer.getNode();
if (slave == null) {
throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName());
}
if (launched) {
LOGGER.log(INFO, "Agent has already been launched, activating: {0}", slave.getNodeName());
computer.setAcceptingTasks(true);
return;
}
final PodTemplate template = slave.getTemplate();
try {
KubernetesClient client = slave.getKubernetesCloud().connect();
Pod pod = template.build(slave);
slave.assignPod(pod);
String podName = pod.getMetadata().getName();
String namespace = Arrays.asList( //
pod.getMetadata().getNamespace(),
template.getNamespace(), client.getNamespace()) //
.stream().filter(s -> StringUtils.isNotBlank(s)).findFirst().orElse(null);
slave.setNamespace(namespace);
TaskListener runListener = template.getListener();
LOGGER.log(FINE, "Creating Pod: {0}/{1}", new Object[] { namespace, podName });
try {
pod = client.pods().inNamespace(namespace).create(pod);
} catch (KubernetesClientException e) {
int k8sCode = e.getCode();
if (k8sCode >= 400 && k8sCode < 500) { // 4xx
runListener.getLogger().printf("ERROR: Unable to create pod. " + e.getMessage());
PodUtils.cancelQueueItemFor(pod, e.getMessage());
} else if (k8sCode >= 500 && k8sCode < 600) { // 5xx
LOGGER.log(FINE,"Kubernetes code {0}. Retrying...", e.getCode());
} else {
LOGGER.log(WARNING, "Unknown Kubernetes code {0}", e.getCode());
}
throw e;
}
LOGGER.log(INFO, "Created Pod: {0}/{1}", new Object[] { namespace, podName });
listener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
runListener.getLogger().printf("Created Pod: %s/%s%n", namespace, podName);
template.getWorkspaceVolume().createVolume(client, pod.getMetadata());
watcher = new AllContainersRunningPodWatcher(client, pod, runListener);
try (Watch w1 = client.pods().inNamespace(namespace).withName(podName).watch(watcher);
Watch w2 = eventWatch(client, podName, namespace, runListener)) {
assert watcher != null; // assigned 3 lines above
watcher.await(template.getSlaveConnectTimeout(), TimeUnit.SECONDS);
}
LOGGER.log(INFO, "Pod is running: {0}/{1}", new Object[] { namespace, podName });
// We need the pod to be running and connected before returning
// otherwise this method keeps being called multiple times
List<String> validStates = ImmutableList.of("Running");
int waitForSlaveToConnect = template.getSlaveConnectTimeout();
int waitedForSlave;
// now wait for agent to be online
SlaveComputer slaveComputer = null;
String status = null;
List<ContainerStatus> containerStatuses = null;
long lastReportTimestamp = System.currentTimeMillis();
for (waitedForSlave = 0; waitedForSlave < waitForSlaveToConnect; waitedForSlave++) {
slaveComputer = slave.getComputer();
if (slaveComputer == null) {
throw new IllegalStateException("Node was deleted, computer is null");
}
if (slaveComputer.isOnline()) {
break;
}
// Check that the pod hasn't failed already
pod = client.pods().inNamespace(namespace).withName(podName).get();
if (pod == null) {
throw new IllegalStateException("Pod no longer exists: " + podName);
}
status = pod.getStatus().getPhase();
if (!validStates.contains(status)) {
break;
}
containerStatuses = pod.getStatus().getContainerStatuses();
List<ContainerStatus> terminatedContainers = new ArrayList<>();
for (ContainerStatus info : containerStatuses) {
if (info != null) {
if (info.getState().getTerminated() != null) {
// Container has errored
LOGGER.log(INFO, "Container is terminated {0} [{2}]: {1}",
new Object[] { podName, info.getState().getTerminated(), info.getName() });
listener.getLogger().printf("Container is terminated %1$s [%3$s]: %2$s%n", podName,
info.getState().getTerminated(), info.getName());
terminatedContainers.add(info);
}
}
}
checkTerminatedContainers(terminatedContainers, podName, namespace, slave, client);
if (lastReportTimestamp + REPORT_INTERVAL < System.currentTimeMillis()) {
LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}",
new Object[]{podName, waitedForSlave, waitForSlaveToConnect});
listener.getLogger().printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podName, waitedForSlave,
waitForSlaveToConnect);
lastReportTimestamp = System.currentTimeMillis();
}
Thread.sleep(1000);
}
if (slaveComputer == null || slaveComputer.isOffline()) {
logLastLines(containerStatuses, podName, namespace, slave, null, client);
throw new IllegalStateException(
"Agent is not connected after " + waitedForSlave + " seconds, status: " + status);
}
computer.setAcceptingTasks(true);
launched = true;
try {
// We need to persist the "launched" setting...
slave.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e);
}
} catch (Throwable ex) {
setProblem(ex);
LOGGER.log(Level.WARNING, String.format("Error in provisioning; agent=%s, template=%s", slave, template), ex);
LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName());
try {
slave.terminate();
} catch (IOException | InterruptedException e) {
LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e);
}
throw Throwables.propagate(ex);
}
}
#location 42
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Nonnull
public KubernetesCloud getKubernetesCloud() {
return getKubernetesCloud(getCloudName());
} | #vulnerable code
@Nonnull
public KubernetesCloud getKubernetesCloud() {
Cloud cloud = Jenkins.getInstance().getCloud(getCloudName());
if (cloud instanceof KubernetesCloud) {
return (KubernetesCloud) cloud;
} else {
throw new IllegalStateException(getClass().getName() + " can be launched only by instances of " + KubernetesCloud.class.getName());
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void push(String item) throws IOException {
if (run == null) {
LOGGER.warning("run is null, cannot push");
return;
}
synchronized (run) {
BulkChange bc = new BulkChange(run);
try {
AbstractInvisibleRunAction2 action = run.getAction(this.getClass());
if (action == null) {
action = createAction(run);
run.addAction(action);
}
LOGGER.log(Level.INFO, "Pushing item {0} to action {1} in run {2}", new Object[] { item, action, run });
action.stack.push(item);
bc.commit();
} finally {
bc.abort();
}
}
} | #vulnerable code
public void push(String item) throws IOException {
if (getRun() == null) {
LOGGER.warning("run is null, cannot push");
return;
}
synchronized (getRun()) {
BulkChange bc = new BulkChange(getRun());
try {
AbstractInvisibleRunAction2 action = getRun().getAction(AbstractInvisibleRunAction2.class);
if (action == null) {
action = new AbstractInvisibleRunAction2(getRun());
getRun().addAction(action);
}
action.stack.push(item);
bc.commit();
} finally {
bc.abort();
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onResume() {
super.onResume();
Cloud cloud = Jenkins.get().getCloud(cloudName);
if (cloud == null) {
throw new RuntimeException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new RuntimeException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
kubernetesCloud.addDynamicTemplate(newTemplate);
} | #vulnerable code
@Override
public void onResume() {
super.onResume();
Cloud cloud = Jenkins.getInstance().getCloud(cloudName);
if (cloud == null) {
throw new RuntimeException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new RuntimeException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
kubernetesCloud.addDynamicTemplate(newTemplate);
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean userHasAdministerPermission() {
return Jenkins.get().hasPermission(Jenkins.ADMINISTER);
} | #vulnerable code
private static boolean userHasAdministerPermission() {
return Jenkins.getInstance().getACL().hasPermission(Jenkins.ADMINISTER);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException, ExecutionException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}",
new String[] { getDisplayName(), serverUrl, namespace });
KubernetesClient client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout, maxRequestsPerHost);
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl });
return client;
} | #vulnerable code
@SuppressFBWarnings({ "IS2_INCONSISTENT_SYNC", "DC_DOUBLECHECK" })
public KubernetesClient connect() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
IOException, CertificateEncodingException, ExecutionException {
LOGGER.log(Level.FINE, "Building connection to Kubernetes {0} URL {1} namespace {2}",
new String[] { getDisplayName(), serverUrl, namespace });
client = KubernetesClientProvider.createClient(name, serverUrl, namespace, serverCertificate, credentialsId, skipTlsVerify,
connectTimeout, readTimeout, maxRequestsPerHost);
LOGGER.log(Level.FINE, "Connected to Kubernetes {0} URL {1}", new String[] { getDisplayName(), serverUrl });
return client;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Node call() throws Exception {
return KubernetesSlave
.builder()
.podTemplate(cloud.getUnwrappedTemplate(t))
.cloud(cloud)
.build();
} | #vulnerable code
public Node call() throws Exception {
RetentionStrategy retentionStrategy;
if (t.getIdleMinutes() == 0) {
retentionStrategy = new OnceRetentionStrategy(cloud.getRetentionTimeout());
} else {
retentionStrategy = new CloudRetentionStrategy(t.getIdleMinutes());
}
final PodTemplate unwrappedTemplate = PodTemplateUtils.unwrap(cloud.getTemplate(label),
cloud.getDefaultsProviderTemplate(), cloud.getTemplates());
return new KubernetesSlave(unwrappedTemplate, unwrappedTemplate.getName(), cloud.name,
unwrappedTemplate.getLabel(), retentionStrategy);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void runWithDeadlineSeconds() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "Deadline");
p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithDeadlineSeconds.groovy")
, true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
assertNotNull(b);
r.waitForMessage("podTemplate", b);
PodTemplate deadlineTemplate = cloud.getTemplates().stream().filter(x -> x.getLabel() == "deadline").findAny().get();
assertEquals(10, deadlineTemplate.getDeadlineSeconds());
assertNotNull(deadlineTemplate);
r.assertLogNotContains("Hello from container!", b);
} | #vulnerable code
@Test
public void runWithDeadlineSeconds() throws Exception {
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "Deadline");
p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithDeadlineSeconds.groovy")
, true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
assertNotNull(b);
r.waitForMessage("podTemplate", b);
PodTemplate deadlineTemplate = null;
for (Iterator<PodTemplate> iterator = cloud.getTemplates().iterator(); iterator.hasNext(); ) {
PodTemplate template = iterator.next();
if (template.getLabel() == "deadline") {
deadlineTemplate = template;
}
}
assertNotNull(deadlineTemplate);
assertEquals(3600, deadlineTemplate.getDeadlineSeconds());
}
#location 19
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean start() throws Exception {
Cloud cloud = Jenkins.get().getCloud(cloudName);
if (cloud == null) {
throw new AbortException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
Run<?, ?> run = getContext().get(Run.class);
if (kubernetesCloud.isUsageRestricted()) {
checkAccess(run, kubernetesCloud);
}
PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class);
String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null;
String label = step.getLabel();
if (label == null) {
label = labelify(run.getExternalizableId());
}
//Let's generate a random name based on the user specified to make sure that we don't have
//issues with concurrent builds, or messing with pre-existing configuration
String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
String stepName = step.getName();
if (stepName == null) {
stepName = label;
}
String name = String.format(NAME_FORMAT, stepName, randString);
String namespace = checkNamespace(kubernetesCloud, podTemplateContext);
newTemplate = new PodTemplate();
newTemplate.setName(name);
newTemplate.setNamespace(namespace);
if (step.getInheritFrom() == null) {
newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates));
} else {
newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom()));
}
newTemplate.setInstanceCap(step.getInstanceCap());
newTemplate.setIdleMinutes(step.getIdleMinutes());
newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout());
newTemplate.setLabel(label);
newTemplate.setEnvVars(step.getEnvVars());
newTemplate.setVolumes(step.getVolumes());
if (step.getWorkspaceVolume() != null) {
newTemplate.setWorkspaceVolume(step.getWorkspaceVolume());
}
newTemplate.setContainers(step.getContainers());
newTemplate.setNodeSelector(step.getNodeSelector());
newTemplate.setNodeUsageMode(step.getNodeUsageMode());
newTemplate.setServiceAccount(step.getServiceAccount());
newTemplate.setAnnotations(step.getAnnotations());
newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy());
if(run!=null) {
String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull();
if(url != null) {
newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl()));
}
}
newTemplate.setImagePullSecrets(
step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));
newTemplate.setYaml(step.getYaml());
if (step.isShowRawYamlSet()) {
newTemplate.setShowRawYaml(step.isShowRawYaml());
}
newTemplate.setPodRetention(step.getPodRetention());
if(step.getActiveDeadlineSeconds() != 0) {
newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds());
}
for (ContainerTemplate container : newTemplate.getContainers()) {
if (!PodTemplateUtils.validateContainerName(container.getName())) {
throw new AbortException(Messages.RFC1123_error(container.getName()));
}
}
Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls());
if (!errors.isEmpty()) {
throw new AbortException(Messages.RFC1123_error(String.join(", ", errors)));
}
// Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally.
if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) {
throw new AbortException(Messages.label_error(newTemplate.getLabel()));
}
kubernetesCloud.addDynamicTemplate(newTemplate);
BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate));
if (step.getLabel() == null) {
invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label))));
}
invoker.start();
return false;
} | #vulnerable code
@Override
public boolean start() throws Exception {
Cloud cloud = Jenkins.getInstance().getCloud(cloudName);
if (cloud == null) {
throw new AbortException(String.format("Cloud does not exist: %s", cloudName));
}
if (!(cloud instanceof KubernetesCloud)) {
throw new AbortException(String.format("Cloud is not a Kubernetes cloud: %s (%s)", cloudName,
cloud.getClass().getName()));
}
KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud;
Run<?, ?> run = getContext().get(Run.class);
if (kubernetesCloud.isUsageRestricted()) {
checkAccess(run, kubernetesCloud);
}
PodTemplateContext podTemplateContext = getContext().get(PodTemplateContext.class);
String parentTemplates = podTemplateContext != null ? podTemplateContext.getName() : null;
String label = step.getLabel();
if (label == null) {
label = labelify(run.getExternalizableId());
}
//Let's generate a random name based on the user specified to make sure that we don't have
//issues with concurrent builds, or messing with pre-existing configuration
String randString = RandomStringUtils.random(5, "bcdfghjklmnpqrstvwxz0123456789");
String stepName = step.getName();
if (stepName == null) {
stepName = label;
}
String name = String.format(NAME_FORMAT, stepName, randString);
String namespace = checkNamespace(kubernetesCloud, podTemplateContext);
newTemplate = new PodTemplate();
newTemplate.setName(name);
newTemplate.setNamespace(namespace);
if (step.getInheritFrom() == null) {
newTemplate.setInheritFrom(Strings.emptyToNull(parentTemplates));
} else {
newTemplate.setInheritFrom(Strings.emptyToNull(step.getInheritFrom()));
}
newTemplate.setInstanceCap(step.getInstanceCap());
newTemplate.setIdleMinutes(step.getIdleMinutes());
newTemplate.setSlaveConnectTimeout(step.getSlaveConnectTimeout());
newTemplate.setLabel(label);
newTemplate.setEnvVars(step.getEnvVars());
newTemplate.setVolumes(step.getVolumes());
if (step.getWorkspaceVolume() != null) {
newTemplate.setWorkspaceVolume(step.getWorkspaceVolume());
}
newTemplate.setContainers(step.getContainers());
newTemplate.setNodeSelector(step.getNodeSelector());
newTemplate.setNodeUsageMode(step.getNodeUsageMode());
newTemplate.setServiceAccount(step.getServiceAccount());
newTemplate.setAnnotations(step.getAnnotations());
newTemplate.setYamlMergeStrategy(step.getYamlMergeStrategy());
if(run!=null) {
String url = ((KubernetesCloud)cloud).getJenkinsUrlOrNull();
if(url != null) {
newTemplate.getAnnotations().add(new PodAnnotation("buildUrl", url + run.getUrl()));
}
}
newTemplate.setImagePullSecrets(
step.getImagePullSecrets().stream().map(x -> new PodImagePullSecret(x)).collect(toList()));
newTemplate.setYaml(step.getYaml());
if (step.isShowRawYamlSet()) {
newTemplate.setShowRawYaml(step.isShowRawYaml());
}
newTemplate.setPodRetention(step.getPodRetention());
if(step.getActiveDeadlineSeconds() != 0) {
newTemplate.setActiveDeadlineSeconds(step.getActiveDeadlineSeconds());
}
for (ContainerTemplate container : newTemplate.getContainers()) {
if (!PodTemplateUtils.validateContainerName(container.getName())) {
throw new AbortException(Messages.RFC1123_error(container.getName()));
}
}
Collection<String> errors = PodTemplateUtils.validateYamlContainerNames(newTemplate.getYamls());
if (!errors.isEmpty()) {
throw new AbortException(Messages.RFC1123_error(String.join(", ", errors)));
}
// Note that after JENKINS-51248 this must be a single label atom, not a space-separated list, unlike PodTemplate.label generally.
if (!PodTemplateUtils.validateLabel(newTemplate.getLabel())) {
throw new AbortException(Messages.label_error(newTemplate.getLabel()));
}
kubernetesCloud.addDynamicTemplate(newTemplate);
BodyInvoker invoker = getContext().newBodyInvoker().withContexts(step, new PodTemplateContext(namespace, name)).withCallback(new PodTemplateCallback(newTemplate));
if (step.getLabel() == null) {
invoker.withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), EnvironmentExpander.constant(Collections.singletonMap("POD_LABEL", label))));
}
invoker.start();
return false;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull Label label) throws Exception {
if (containerCap == 0) {
return true;
}
KubernetesClient client = connect();
String templateNamespace = template.getNamespace();
// If template's namespace is not defined, take the
// Kubernetes Namespace.
if (Strings.isNullOrEmpty(templateNamespace)) {
templateNamespace = client.getNamespace();
}
PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list();
List<Pod> allActiveSlavePods = null;
// JENKINS-53370 check for nulls
if (slaveList != null && slaveList.getItems() != null) {
allActiveSlavePods = slaveList.getItems().stream() //
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
}
Map<String, String> labelsMap = new HashMap<>(this.getLabels());
labelsMap.putAll(template.getLabelsMap());
PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list();
// JENKINS-53370 check for nulls
List<Pod> activeTemplateSlavePods = null;
if (templateSlaveList != null && templateSlaveList.getItems() != null) {
activeTemplateSlavePods = templateSlaveList.getItems().stream()
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
}
if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) {
LOGGER.log(Level.INFO,
"Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}",
new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() });
return false;
}
if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) {
LOGGER.log(Level.INFO,
"Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}",
new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(),
templateNamespace, label == null ? "" : label.toString(), labelsMap });
return false;
}
return true;
} | #vulnerable code
private boolean addProvisionedSlave(@Nonnull PodTemplate template, @CheckForNull Label label) throws Exception {
if (containerCap == 0) {
return true;
}
KubernetesClient client = connect();
String templateNamespace = template.getNamespace();
// If template's namespace is not defined, take the
// Kubernetes Namespace.
if (Strings.isNullOrEmpty(templateNamespace)) {
templateNamespace = client.getNamespace();
}
PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(getLabels()).list();
List<Pod> allActiveSlavePods = null;
// JENKINS-53370 check for nulls
if (slaveList != null && slaveList.getItems() != null) {
allActiveSlavePods = slaveList.getItems().stream() //
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
}
Map<String, String> labelsMap = new HashMap<>(this.getLabels());
labelsMap.putAll(template.getLabelsMap());
PodList templateSlaveList = client.pods().inNamespace(templateNamespace).withLabels(labelsMap).list();
List<Pod> activeTemplateSlavePods = templateSlaveList.getItems().stream()
.filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
.collect(Collectors.toList());
if (allActiveSlavePods != null && containerCap <= allActiveSlavePods.size()) {
LOGGER.log(Level.INFO,
"Total container cap of {0} reached, not provisioning: {1} running or pending in namespace {2} with Kubernetes labels {3}",
new Object[] { containerCap, allActiveSlavePods.size(), templateNamespace, getLabels() });
return false;
}
if (activeTemplateSlavePods != null && allActiveSlavePods != null && template.getInstanceCap() <= activeTemplateSlavePods.size()) {
LOGGER.log(Level.INFO,
"Template instance cap of {0} reached for template {1}, not provisioning: {2} running or pending in namespace {3} with label \"{4}\" and Kubernetes labels {5}",
new Object[] { template.getInstanceCap(), template.getName(), allActiveSlavePods.size(),
templateNamespace, label == null ? "" : label.toString(), labelsMap });
return false;
}
return true;
}
#location 26
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String pop() throws IOException {
if (run == null) {
LOGGER.warning("run is null, cannot pop");
return null;
}
synchronized (getRun()) {
BulkChange bc = new BulkChange(getRun());
try {
AbstractInvisibleRunAction2 action = getRun().getAction(this.getClass());
if (action == null) {
action = createAction(getRun());
getRun().addAction(action);
}
String item = action.stack.pop();
LOGGER.log(Level.INFO, "Popped item {0} from action {1} in run {2}",
new Object[] { item, action, run });
bc.commit();
return item;
} finally {
bc.abort();
}
}
} | #vulnerable code
public String pop() throws IOException {
if (getRun() == null) {
LOGGER.warning("run is null, cannot pop");
return null;
}
synchronized (getRun()) {
BulkChange bc = new BulkChange(getRun());
try {
AbstractInvisibleRunAction2 action = getRun().getAction(AbstractInvisibleRunAction2.class);
if (action == null) {
action = new AbstractInvisibleRunAction2(getRun());
getRun().addAction(action);
}
String template = action.stack.pop();
bc.commit();
return template;
} finally {
bc.abort();
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Pod getPodTemplate(KubernetesSlave slave, Label label) {
DockerTemplate template = getTemplate(label);
String id = getIdForLabel(label);
Pod podTemplate = new Pod();
/*
podTemplate.setId(slave.getNodeName());
// labels
podTemplate.setLabels(getLabelsFor(id));
Container container = new Container();
container.setName(CONTAINER_NAME);
container.setImage(template.getImage());
// environment
// List<EnvironmentVariable> env = new
// ArrayList<EnvironmentVariable>(template.environment.length + 3);
List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3);
// always add some env vars
env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac()));
env.add(new EnvironmentVariable("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl()));
if (!StringUtils.isBlank(jenkinsUrl)) {
env.add(new EnvironmentVariable("JENKINS_URL", jenkinsUrl));
}
if (!StringUtils.isBlank(jenkinsTunnel)) {
env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel));
}
String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl;
url = url.endsWith("/") ? url : url + "/";
env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp"));
// for (int i = 0; i < template.environment.length; i++) {
// String[] split = template.environment[i].split("=");
// env.add(new EnvironmentVariable(split[0], split[1]));
// }
container.setEnv(env);
// ports
// TODO open ports defined in template
// container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) +
// 49152));
// command: SECRET SLAVE_NAME
List<String> cmd = parseDockerCommand(template.dockerCommand);
cmd = cmd == null ? new ArrayList<String>(2) : cmd;
cmd.add(slave.getComputer().getJnlpMac()); // secret
cmd.add(slave.getComputer().getName()); // name
container.setCommand(cmd);
Manifest manifest = new Manifest(Collections.singletonList(container), null);
podTemplate.setDesiredState(new State(manifest));
*/
return podTemplate;
} | #vulnerable code
private Pod getPodTemplate(KubernetesSlave slave, Label label) {
DockerTemplate template = getTemplate(label);
String id = getIdForLabel(label);
Pod podTemplate = new Pod();
podTemplate.setId(slave.getNodeName());
// labels
podTemplate.setLabels(getLabelsFor(id));
Container container = new Container();
container.setName(CONTAINER_NAME);
container.setImage(template.getImage());
// environment
// List<EnvironmentVariable> env = new
// ArrayList<EnvironmentVariable>(template.environment.length + 3);
List<EnvironmentVariable> env = new ArrayList<EnvironmentVariable>(3);
// always add some env vars
env.add(new EnvironmentVariable("JENKINS_SECRET", slave.getComputer().getJnlpMac()));
env.add(new EnvironmentVariable("JENKINS_LOCATION_URL", JenkinsLocationConfiguration.get().getUrl()));
if (!StringUtils.isBlank(jenkinsUrl)) {
env.add(new EnvironmentVariable("JENKINS_URL", jenkinsUrl));
}
if (!StringUtils.isBlank(jenkinsTunnel)) {
env.add(new EnvironmentVariable("JENKINS_TUNNEL", jenkinsTunnel));
}
String url = StringUtils.isBlank(jenkinsUrl) ? JenkinsLocationConfiguration.get().getUrl() : jenkinsUrl;
url = url.endsWith("/") ? url : url + "/";
env.add(new EnvironmentVariable("JENKINS_JNLP_URL", url + slave.getComputer().getUrl() + "slave-agent.jnlp"));
// for (int i = 0; i < template.environment.length; i++) {
// String[] split = template.environment[i].split("=");
// env.add(new EnvironmentVariable(split[0], split[1]));
// }
container.setEnv(env);
// ports
// TODO open ports defined in template
// container.setPorts(new Port(22, RAND.nextInt((65535 - 49152) + 1) +
// 49152));
// command: SECRET SLAVE_NAME
List<String> cmd = parseDockerCommand(template.dockerCommand);
cmd = cmd == null ? new ArrayList<String>(2) : cmd;
cmd.add(slave.getComputer().getJnlpMac()); // secret
cmd.add(slave.getComputer().getName()); // name
container.setCommand(cmd);
Manifest manifest = new Manifest(Collections.singletonList(container), null);
podTemplate.setDesiredState(new State(manifest));
return podTemplate;
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public InputStream getData(String resourceId) throws IOException {
LoadableResource load = this.resources.get(resourceId);
if (Objects.nonNull(load)) {
return load.getDataStream();
}
throw new IllegalArgumentException("No such resource: " + resourceId);
} | #vulnerable code
@Override
public InputStream getData(String resourceId) throws IOException {
LoadableResource load = this.resources.get(resourceId);
if (Objects.nonNull(load)) {
load.getDataStream();
}
throw new IllegalArgumentException("No such resource: " + resourceId);
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected boolean load(URI itemToLoad, boolean fallbackLoad) {
InputStream is = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try{
URLConnection conn;
String proxyPort = this.properties.get("proxy.port");
String proxyHost = this.properties.get("proxy.host");
String proxyType = this.properties.get("procy.type");
if(proxyType!=null){
Proxy proxy = new Proxy(Proxy.Type.valueOf(proxyType.toUpperCase()),
InetSocketAddress.createUnresolved(proxyHost, Integer.parseInt(proxyPort)));
conn = itemToLoad.toURL().openConnection(proxy);
}else{
conn = itemToLoad.toURL().openConnection();
}
byte[] data = new byte[4096];
is = conn.getInputStream();
int read = is.read(data);
while (read > 0) {
stream.write(data, 0, read);
read = is.read(data);
}
setData(stream.toByteArray());
if (!fallbackLoad) {
writeCache();
lastLoaded = System.currentTimeMillis();
loadCount.incrementAndGet();
}
return true;
} catch (Exception e) {
LOG.log(Level.INFO, "Failed to load resource input for " + resourceId + " from " + itemToLoad, e);
} finally {
if (Objects.nonNull(is)) {
try {
is.close();
} catch (Exception e) {
LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e);
}
}
try {
stream.close();
} catch (IOException e) {
LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e);
}
}
return false;
} | #vulnerable code
protected boolean load(URI itemToLoad, boolean fallbackLoad) {
InputStream is = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
URLConnection conn = itemToLoad.toURL().openConnection();
byte[] data = new byte[4096];
is = conn.getInputStream();
int read = is.read(data);
while (read > 0) {
stream.write(data, 0, read);
read = is.read(data);
}
setData(stream.toByteArray());
if (!fallbackLoad) {
writeCache();
lastLoaded = System.currentTimeMillis();
loadCount.incrementAndGet();
}
return true;
} catch (Exception e) {
LOG.log(Level.INFO, "Failed to load resource input for " + resourceId + " from " + itemToLoad, e);
} finally {
if (Objects.nonNull(is)) {
try {
is.close();
} catch (Exception e) {
LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e);
}
}
try {
stream.close();
} catch (IOException e) {
LOG.log(Level.INFO, "Error closing resource input for " + resourceId, e);
}
}
return false;
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
if (!isAvailable(conversionQuery)) {
return null;
}
CurrencyUnit base = conversionQuery.getBaseCurrency();
CurrencyUnit term = conversionQuery.getCurrency();
LocalDate timestamp = getTimeStamp(conversionQuery);
ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp);
ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp);
if (base.equals(SDR)) {
return rate2;
} else if (term.equals(SDR)) {
return rate1;
}
if (Objects.isNull(rate1) || Objects.isNull(rate2)) {
return null;
}
ExchangeRateBuilder builder =
new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC));
builder.setBase(base);
builder.setTerm(term);
builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor()));
builder.setRateChain(rate1, rate2);
return builder.build();
} | #vulnerable code
@Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
if (!isAvailable(conversionQuery)) {
return null;
}
CurrencyUnit base = conversionQuery.getBaseCurrency();
CurrencyUnit term = conversionQuery.getCurrency();
LocalDate timestamp = conversionQuery.get(LocalDate.class);
if (timestamp == null) {
LocalDateTime dateTime = conversionQuery.get(LocalDateTime.class);
if (dateTime != null) {
timestamp = dateTime.toLocalDate();
}
}
ExchangeRate rate1 = lookupRate(currencyToSdr.get(base), timestamp);
ExchangeRate rate2 = lookupRate(sdrToCurrency.get(term), timestamp);
if (base.equals(SDR)) {
return rate2;
} else if (term.equals(SDR)) {
return rate1;
}
if (Objects.isNull(rate1) || Objects.isNull(rate2)) {
return null;
}
ExchangeRateBuilder builder =
new ExchangeRateBuilder(ConversionContext.of(CONTEXT.getProviderName(), RateType.HISTORIC));
builder.setBase(base);
builder.setTerm(term);
builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor()));
builder.setRateChain(rate1, rate2);
return builder.build();
}
#location 29
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void copy(InputStream source, File dest) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(dest);
copy(source, fos);
} finally {
if (fos != null) try {fos.close();} catch (Exception e) {}
}
} | #vulnerable code
public static void copy(InputStream source, File dest) throws IOException {
FileOutputStream fos = new FileOutputStream(dest);
copy(source, fos);
fos.close();
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void deleteNode(Handle handle) throws IOException {
if (cachesize != 0) {
Node n = (Node) cache.get(handle);
if (n != null) synchronized (cache) {
cacheScore.deleteScore(handle);
cache.remove(handle);
}
}
dispose(handle);
} | #vulnerable code
protected void deleteNode(Handle handle) throws IOException {
if (cachesize != 0) {
Node n = (Node) cache.get(handle);
if (n != null) {
cacheScore.deleteScore(handle);
cache.remove(handle);
}
}
dispose(handle);
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() {
serverLog.logSystem("PLASMA INDEXING", "started word cache management");
int check;
// permanently flush cache elements
while (!(terminate)) {
if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {}
while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try {
check = hashScore.size();
flushSpecific(false);
//serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size());
try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {}
} catch (IOException e) {
serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage());
e.printStackTrace();
terminate = true;
cache = null;
}
}
serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush");
// close all;
try {
// first flush everything
while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) {
flushSpecific(false);
}
// then close file cache:
pic.close();
} catch (IOException e) {
serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString());
}
// report
if (hashScore.size() == 0)
serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words");
else
serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost");
// delete data
cache = null;
hashScore = null;
} | #vulnerable code
public void run() {
serverLog.logSystem("PLASMA INDEXING", "started word cache management");
int check;
// permanently flush cache elements
while (!(terminate)) {
if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {}
while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try {
//check = hashScore.size();
flushSpecific(false);
//serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size());
try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {}
} catch (IOException e) {
serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage());
e.printStackTrace();
terminate = true;
cache = null;
}
}
serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush");
// close all;
try {
// first flush everything
while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) {
flushSpecific(false);
}
// then close file cache:
pic.close();
} catch (IOException e) {
serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString());
}
// report
if (hashScore.size() == 0)
serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words");
else
serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost");
// delete data
cache = null;
hashScore = null;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String readLine() throws IOException {
// with these functions, we consider a line as always terminated by CRLF
byte[] bb = new byte[80];
int bbsize = 0;
int c;
while (true) {
c = read();
if (c < 0) {
if (bbsize == 0) return null; else return new String(bb, 0, bbsize);
}
if (c == cr) continue;
if (c == lf) return new String(bb, 0, bbsize);
// append to bb
if (bbsize == bb.length) {
// extend bb size
byte[] newbb = new byte[bb.length * 2];
System.arraycopy(bb, 0, newbb, 0, bb.length);
bb = newbb;
newbb = null;
}
bb[bbsize++] = (byte) c;
}
} | #vulnerable code
public String readLine() throws IOException {
// with these functions, we consider a line as always terminated by CRLF
serverByteBuffer sb = new serverByteBuffer();
int c;
while (true) {
c = read();
if (c < 0) {
if (sb.length() == 0) return null; else return sb.toString();
}
if (c == cr) continue;
if (c == lf) return sb.toString();
sb.append((byte) c);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void respondError(OutputStream respond, String origerror, int errorcase, String url) {
FileInputStream fis = null;
try {
// set rewrite values
serverObjects tp = new serverObjects();
tp.put("errormessage", errorcase);
tp.put("httperror", origerror);
tp.put("url", url);
// rewrite the file
File file = new File(htRootPath, "/proxymsg/error.html");
byte[] result;
ByteArrayOutputStream o = new ByteArrayOutputStream();
fis = new FileInputStream(file);
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes());
o.close();
result = o.toByteArray();
// return header
httpHeader header = new httpHeader();
header.put("Date", httpc.dateString(httpc.nowDate()));
header.put("Content-type", "text/html");
header.put("Content-length", "" + o.size());
header.put("Pragma", "no-cache");
// write the array to the client
respondHeader(respond, origerror, header);
serverFileUtils.write(result, respond);
respond.flush();
} catch (IOException e) {
} finally {
if (fis != null) try { fis.close(); } catch (Exception e) {}
}
} | #vulnerable code
private void respondError(OutputStream respond, String origerror, int errorcase, String url) {
try {
// set rewrite values
serverObjects tp = new serverObjects();
tp.put("errormessage", errorcase);
tp.put("httperror", origerror);
tp.put("url", url);
// rewrite the file
File file = new File(htRootPath, "/proxymsg/error.html");
byte[] result;
ByteArrayOutputStream o = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(file);
httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes());
o.close();
result = o.toByteArray();
// return header
httpHeader header = new httpHeader();
header.put("Date", httpc.dateString(httpc.nowDate()));
header.put("Content-type", "text/html");
header.put("Content-length", "" + o.size());
header.put("Pragma", "no-cache");
// write the array to the client
respondHeader(respond, origerror, header);
serverFileUtils.write(result, respond);
respond.flush();
} catch (IOException e) {
}
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() {
serverLog.logSystem("PLASMA INDEXING", "started word cache management");
int check;
// permanently flush cache elements
while (!(terminate)) {
if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {}
while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try {
check = hashScore.size();
flushSpecific(false);
//serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size());
try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {}
} catch (IOException e) {
serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage());
e.printStackTrace();
terminate = true;
cache = null;
}
}
serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush");
// close all;
try {
// first flush everything
while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) {
flushSpecific(false);
}
// then close file cache:
pic.close();
} catch (IOException e) {
serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString());
}
// report
if (hashScore.size() == 0)
serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words");
else
serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost");
// delete data
cache = null;
hashScore = null;
} | #vulnerable code
public void run() {
serverLog.logSystem("PLASMA INDEXING", "started word cache management");
int check;
// permanently flush cache elements
while (!(terminate)) {
if (hashScore.size() < 100) try {Thread.currentThread().sleep(10000);} catch (InterruptedException e) {}
while ((!(terminate)) && (cache != null) && (hashScore.size() > 0)) try {
//check = hashScore.size();
flushSpecific(false);
//serverLog.logDebug("PLASMA INDEXING", "single flush. bevore=" + check + "; after=" + hashScore.size());
try {Thread.currentThread().sleep(10 + ((maxWords / 10) / (1 + hashScore.size())));} catch (InterruptedException e) {}
} catch (IOException e) {
serverLog.logError("PLASMA INDEXING", "PANIK! exception in main cache loop: " + e.getMessage());
e.printStackTrace();
terminate = true;
cache = null;
}
}
serverLog.logSystem("PLASMA INDEXING", "CATCHED TERMINATION SIGNAL: start final flush");
// close all;
try {
// first flush everything
while ((hashScore.size() > 0) && (System.currentTimeMillis() < terminateUntil)) {
flushSpecific(false);
}
// then close file cache:
pic.close();
} catch (IOException e) {
serverLog.logDebug("PLASMA INDEXING", "interrupted final flush: " + e.toString());
}
// report
if (hashScore.size() == 0)
serverLog.logSystem("PLASMA INDEXING", "finished final flush; flushed all words");
else
serverLog.logError("PLASMA INDEXING", "terminated final flush; " + hashScore.size() + " words lost");
// delete data
cache = null;
hashScore = null;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static TreeMap loadMap(String mapname, String filename, String sep) {
TreeMap map = new TreeMap();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line;
int pos;
while ((line = br.readLine()) != null) {
line = line.trim();
if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0))
map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim());
}
serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename);
} catch (IOException e) {
} finally {
if (br != null) try { br.close(); } catch (Exception e) {}
}
return map;
} | #vulnerable code
private static TreeMap loadMap(String mapname, String filename, String sep) {
TreeMap map = new TreeMap();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
String line;
int pos;
while ((line = br.readLine()) != null) {
line = line.trim();
if ((line.length() > 0) && (!(line.startsWith("#"))) && ((pos = line.indexOf(sep)) > 0))
map.put(line.substring(0, pos).trim().toLowerCase(), line.substring(pos + sep.length()).trim());
}
br.close();
serverLog.logInfo("PROXY", "read " + mapname + " map from file " + filename);
} catch (IOException e) {}
return map;
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private int flushFromMemToLimit() {
if ((hashScore.size() == 0) && (cache.size() == 0)) {
serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty");
return 0;
}
if ((hashScore.size() == 0) && (cache.size() != 0)) {
serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size());
return 0;
}
if ((hashScore.size() != 0) && (cache.size() == 0)) {
serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0");
return 0;
}
//serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size());
int total = 0;
synchronized (hashScore) {
String key;
int count;
Long createTime;
// flush high-scores
while ((total < 100) && (hashScore.size() >= maxWords)) {
key = (String) hashScore.getMaxObject();
createTime = (Long) hashDate.get(key);
count = hashScore.getScore(key);
if (count < 5) {
log.logWarning("flushing of high-key " + key + " not appropriate (too less entries, count=" + count + "): increase cache size");
break;
}
if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) {
//log.logDebug("high-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")");
break;
}
//log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());
total += flushFromMem(key, false);
}
// flush singletons
Iterator i = hashScore.scores(true);
ArrayList al = new ArrayList();
while ((i.hasNext()) && (total < 200)) {
key = (String) i.next();
createTime = (Long) hashDate.get(key);
count = hashScore.getScore(key);
if (count > 1) {
//log.logDebug("flush of singleton-key " + key + ": count too high (count=" + count + ")");
break;
}
if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 90000)) {
//log.logDebug("singleton-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")");
continue;
}
//log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());
al.add(key);
total++;
}
for (int k = 0; k < al.size(); k++) flushFromMem((String) al.get(k), true);
}
return total;
} | #vulnerable code
private int flushFromMemToLimit() {
if ((hashScore.size() == 0) && (cache.size() == 0)) {
serverLog.logDebug("PLASMA INDEXING", "flushToLimit: called but cache is empty");
return 0;
}
if ((hashScore.size() == 0) && (cache.size() != 0)) {
serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=0 but cache.size=" + cache.size());
return 0;
}
if ((hashScore.size() != 0) && (cache.size() == 0)) {
serverLog.logError("PLASMA INDEXING", "flushToLimit: hashScore.size=" + hashScore.size() + " but cache.size=0");
return 0;
}
//serverLog.logDebug("PLASMA INDEXING", "flushSpecific: hashScore.size=" + hashScore.size() + ", cache.size=" + cache.size());
int total = 0;
synchronized (hashScore) {
String key;
int count;
Long createTime;
// flush high-scores
while ((total < 100) && (hashScore.size() >= maxWords)) {
key = (String) hashScore.getMaxObject();
createTime = (Long) hashDate.get(key);
count = hashScore.getScore(key);
if (count < 5) {
log.logWarning("flushing of high-key " + key + " not appropriate (too less entries, count=" + count + "): increase cache size");
break;
}
if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) {
//log.logDebug("high-key " + key + " is too fresh, interrupting flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")");
break;
}
//log.logDebug("flushing high-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());
total += flushFromMem(key);
}
// flush singletons
while ((total < 200) && (hashScore.size() >= maxWords)) {
key = (String) hashScore.getMinObject();
createTime = (Long) hashDate.get(key);
count = hashScore.getScore(key);
if (count > 1) {
//log.logDebug("flush of singleton-key " + key + ": count too high (count=" + count + ")");
break;
}
if ((createTime != null) && ((System.currentTimeMillis() - createTime.longValue()) < 9000)) {
//log.logDebug("singleton-key " + key + " is too fresh, interruptiong flush (count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size() + ")");
break;
}
//log.logDebug("flushing singleton-key " + key + ", count=" + count + ", cachesize=" + cache.size() + ", singleton-size=" + singletons.size());
total += flushFromMem(key);
}
}
return total;
}
#location 36
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void copy(File source, OutputStream dest) throws IOException {
InputStream fis = null;
try {
fis = new FileInputStream(source);
copy(fis, dest);
} finally {
if (fis != null) try { fis.close(); } catch (Exception e) {}
}
} | #vulnerable code
public static void copy(File source, OutputStream dest) throws IOException {
InputStream fis = new FileInputStream(source);
copy(fis, dest);
fis.close();
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static byte[] read(File source) throws IOException {
byte[] buffer = new byte[(int) source.length()];
InputStream fis = null;
try {
fis = new FileInputStream(source);
int p = 0, c;
while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c;
} finally {
if (fis != null) try { fis.close(); } catch (Exception e) {}
}
return buffer;
} | #vulnerable code
public static byte[] read(File source) throws IOException {
byte[] buffer = new byte[(int) source.length()];
InputStream fis = new FileInputStream(source);
int p = 0;
int c;
while ((c = fis.read(buffer, p, buffer.length - p)) > 0) p += c;
fis.close();
return buffer;
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException {
// make space for new words
int flushc = 0;
//serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size());
synchronized (hashScore) {
while (hashScore.size() > maxWords) flushc += flushSpecific(true);
}
//if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries");
// put new words into cache
synchronized (cache) {
Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null
if (v == null) v = new Vector();
v.add(entry);
cache.put(wordHash, v);
hashScore.incScore(wordHash);
}
return flushc;
} | #vulnerable code
public int addEntryToIndexMem(String wordHash, plasmaWordIndexEntry entry) throws IOException {
// make space for new words
int flushc = 0;
//serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem: cache.size=" + cache.size() + "; hashScore.size=" + hashScore.size());
synchronized (hashScore) {
while (hashScore.size() > maxWords) flushc += flushSpecific(true);
}
//if (flushc > 0) serverLog.logDebug("PLASMA INDEXING", "addEntryToIndexMem - flushed " + flushc + " entries");
// put new words into cache
Vector v = (Vector) cache.get(wordHash); // null pointer exception? wordhash != null! must be cache==null
if (v == null) v = new Vector();
v.add(entry);
cache.put(wordHash, v);
hashScore.incScore(wordHash);
return flushc;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.