input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override
public void replaceIndex(String newLuceneIndexPathString) {
LOG.debug(
"Replacing Lucene indexes at {} for dimension {} with new index at {}",
luceneDirectory.toString(),
dimension.getApiName(),
newLuceneIndexPathString
);
lock.writeLock().lock();
try {
Path oldLuceneIndexPath = Paths.get(luceneIndexPath);
String tempDir = oldLuceneIndexPath.resolveSibling(oldLuceneIndexPath.getFileName() + "_old").toString();
LOG.trace("Moving old Lucene index directory from {} to {} ...", luceneIndexPath, tempDir);
moveDirEntries(luceneIndexPath, tempDir);
LOG.trace("Moving all new Lucene indexes from {} to {} ...", newLuceneIndexPathString, luceneIndexPath);
moveDirEntries(newLuceneIndexPathString, luceneIndexPath);
LOG.trace(
"Deleting {} since new Lucene indexes have been moved away from there and is now empty",
newLuceneIndexPathString
);
deleteDir(newLuceneIndexPathString);
LOG.trace("Deleting old Lucene indexes in {} ...", tempDir);
deleteDir(tempDir);
reopenIndexSearcher(false);
} finally {
lock.writeLock().unlock();
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void replaceIndex(String newLuceneIndexPathString) {
LOG.debug(
"Replacing Lucene indexes at {} for dimension {} with new index at {}",
luceneDirectory.toString(),
dimension.getApiName(),
newLuceneIndexPathString
);
writeLock();
try {
Path oldLuceneIndexPath = Paths.get(luceneIndexPath);
String tempDir = oldLuceneIndexPath.resolveSibling(oldLuceneIndexPath.getFileName() + "_old").toString();
LOG.trace("Moving old Lucene index directory from {} to {} ...", luceneIndexPath, tempDir);
moveDirEntries(luceneIndexPath, tempDir);
LOG.trace("Moving all new Lucene indexes from {} to {} ...", newLuceneIndexPathString, luceneIndexPath);
moveDirEntries(newLuceneIndexPathString, luceneIndexPath);
LOG.trace(
"Deleting {} since new Lucene indexes have been moved away from there and is now empty",
newLuceneIndexPathString
);
deleteDir(newLuceneIndexPathString);
LOG.trace("Deleting old Lucene indexes in {} ...", tempDir);
deleteDir(tempDir);
reopenIndexSearcher(false);
} finally {
writeUnlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public LookbackQuery withInnerQueryPostAggregations(Collection<PostAggregation> postAggregations) {
return new LookbackQuery(new QueryDataSource(getInnerQuery().withPostAggregations(postAggregations)), granularity, filter, aggregations, getLookbackPostAggregations(), intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec);
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public LookbackQuery withInnerQueryPostAggregations(Collection<PostAggregation> postAggregations) {
return new LookbackQuery(new QueryDataSource(getInnerQueryUnchecked().withPostAggregations(postAggregations)), granularity, filter, aggregations, getLookbackPostAggregations(), intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected Pagination<DimensionRow> getResultsPage(Query query, PaginationParameters paginationParameters)
throws PageNotFoundException {
int perPage = paginationParameters.getPerPage();
validatePerPage(perPage);
TreeSet<DimensionRow> filteredDimRows;
int documentCount;
initializeIndexSearcher();
LOG.trace("Lucene Query {}", query);
lock.readLock().lock();
try {
ScoreDoc[] hits;
try (TimedPhase timer = RequestLog.startTiming("QueryingLucene")) {
TopDocs hitDocs = getPageOfData(
luceneIndexSearcher,
null,
query,
perPage
);
hits = hitDocs.scoreDocs;
// The change to supprt long document sizes is incompletely supported in Lucene
// Since we can't request up to long documents we'll only expect to receive up to Integer.MAX_VALUE
// responses, and throw an error if we exceed that.
if (hitDocs.totalHits > Integer.MAX_VALUE) {
String message = String.format(TOO_MANY_DOCUMENTS, hitDocs.totalHits);
RowLimitReachedException exception = new RowLimitReachedException(message);
LOG.error(exception.getMessage(), exception);
throw exception;
}
documentCount = (int) hitDocs.totalHits;
int requestedPageNumber = paginationParameters.getPage(documentCount);
if (hits.length == 0) {
if (requestedPageNumber == 1) {
return new SinglePagePagination<>(Collections.emptyList(), paginationParameters, 0);
} else {
throw new PageNotFoundException(requestedPageNumber, perPage, 0);
}
}
for (int currentPage = 1; currentPage < requestedPageNumber; currentPage++) {
ScoreDoc lastEntry = hits[hits.length - 1];
hits = getPageOfData(luceneIndexSearcher, lastEntry, query, perPage).scoreDocs;
if (hits.length == 0) {
throw new PageNotFoundException(requestedPageNumber, perPage, 0);
}
}
}
// convert hits to dimension rows
try (TimedPhase timer = RequestLog.startTiming("LuceneHydratingDimensionRows")) {
String idKey = DimensionStoreKeyUtils.getColumnKey(dimension.getKey().getName());
filteredDimRows = Arrays.stream(hits)
.map(
hit -> {
try {
return luceneIndexSearcher.doc(hit.doc);
} catch (IOException e) {
LOG.error("Unable to convert hit " + hit);
throw new RuntimeException(e);
}
}
)
.map(document -> document.get(idKey))
.map(dimension::findDimensionRowByKeyValue)
.collect(Collectors.toCollection(TreeSet::new));
}
} finally {
lock.readLock().unlock();
}
return new SinglePagePagination<>(
Collections.unmodifiableList(filteredDimRows.stream().collect(Collectors.toList())),
paginationParameters,
documentCount
);
}
#location 52
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected Pagination<DimensionRow> getResultsPage(Query query, PaginationParameters paginationParameters)
throws PageNotFoundException {
int perPage = paginationParameters.getPerPage();
validatePerPage(perPage);
TreeSet<DimensionRow> filteredDimRows;
int documentCount;
initializeIndexSearcher();
LOG.trace("Lucene Query {}", query);
readLock();
try {
ScoreDoc[] hits;
try (TimedPhase timer = RequestLog.startTiming("QueryingLucene")) {
TopDocs hitDocs = getPageOfData(
luceneIndexSearcher,
null,
query,
perPage
);
hits = hitDocs.scoreDocs;
// The change to supprt long document sizes is incompletely supported in Lucene
// Since we can't request up to long documents we'll only expect to receive up to Integer.MAX_VALUE
// responses, and throw an error if we exceed that.
if (hitDocs.totalHits > Integer.MAX_VALUE) {
String message = String.format(TOO_MANY_DOCUMENTS, hitDocs.totalHits);
RowLimitReachedException exception = new RowLimitReachedException(message);
LOG.error(exception.getMessage(), exception);
throw exception;
}
documentCount = (int) hitDocs.totalHits;
int requestedPageNumber = paginationParameters.getPage(documentCount);
if (hits.length == 0) {
if (requestedPageNumber == 1) {
return new SinglePagePagination<>(Collections.emptyList(), paginationParameters, 0);
} else {
throw new PageNotFoundException(requestedPageNumber, perPage, 0);
}
}
for (int currentPage = 1; currentPage < requestedPageNumber; currentPage++) {
ScoreDoc lastEntry = hits[hits.length - 1];
hits = getPageOfData(luceneIndexSearcher, lastEntry, query, perPage).scoreDocs;
if (hits.length == 0) {
throw new PageNotFoundException(requestedPageNumber, perPage, 0);
}
}
}
// convert hits to dimension rows
try (TimedPhase timer = RequestLog.startTiming("LuceneHydratingDimensionRows")) {
String idKey = DimensionStoreKeyUtils.getColumnKey(dimension.getKey().getName());
filteredDimRows = Arrays.stream(hits)
.map(
hit -> {
try {
return luceneIndexSearcher.doc(hit.doc);
} catch (IOException e) {
LOG.error("Unable to convert hit " + hit);
throw new RuntimeException(e);
}
}
)
.map(document -> document.get(idKey))
.map(dimension::findDimensionRowByKeyValue)
.collect(Collectors.toCollection(TreeSet::new));
}
} finally {
readUnlock();
}
return new SinglePagePagination<>(
Collections.unmodifiableList(filteredDimRows.stream().collect(Collectors.toList())),
paginationParameters,
documentCount
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
@JsonIgnore
public Granularity getGranularity() {
return getInnerQuery().getGranularity();
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
@JsonIgnore
public Granularity getGranularity() {
return getInnerQueryUnchecked().getGranularity();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) {
if (executorService.isShutdown()) {
throw new IllegalStateException("ExecutorService has been shutdown.");
}
this.initialPositionInStreamExtended = initialPositionInStreamExtended;
highestSequenceNumber = extendedSequenceNumber.sequenceNumber();
dataFetcher.initialize(extendedSequenceNumber, initialPositionInStreamExtended);
if (!started) {
log.info("{} : Starting prefetching thread.", shardId);
executorService.execute(defaultGetRecordsCacheDaemon);
}
started = true;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) {
if (executorService.isShutdown()) {
throw new IllegalStateException("ExecutorService has been shutdown.");
}
publisherSession.init(extendedSequenceNumber, initialPositionInStreamExtended);
if (!started) {
log.info("{} : Starting prefetching thread.", shardId);
executorService.execute(defaultGetRecordsCacheDaemon);
}
started = true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void initialize() {
boolean isDone = false;
Exception lastException = null;
for (int i = 0; (!isDone) && (i < MAX_INITIALIZATION_ATTEMPTS); i++) {
try {
LOG.info("Initialization attempt " + (i + 1));
LOG.info("Initializing LeaseCoordinator");
leaseCoordinator.initialize();
LOG.info("Syncing Kinesis shard info");
ShardSyncTask shardSyncTask =
new ShardSyncTask(streamConfig.getStreamProxy(),
leaseCoordinator.getLeaseManager(),
initialPosition,
cleanupLeasesUponShardCompletion,
0L);
TaskResult result = new MetricsCollectingTaskDecorator(shardSyncTask, metricsFactory).call();
if (result.getException() == null) {
if (!leaseCoordinator.isRunning()) {
LOG.info("Starting LeaseCoordinator");
leaseCoordinator.start();
} else {
LOG.info("LeaseCoordinator is already running. No need to start it.");
}
isDone = true;
} else {
lastException = result.getException();
}
} catch (LeasingException e) {
LOG.error("Caught exception when initializing LeaseCoordinator", e);
lastException = e;
} catch (Exception e) {
lastException = e;
}
try {
Thread.sleep(parentShardPollIntervalMillis);
} catch (InterruptedException e) {
LOG.debug("Sleep interrupted while initializing worker.");
}
}
if (!isDone) {
throw new RuntimeException(lastException);
}
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
private void initialize() {
boolean isDone = false;
Exception lastException = null;
for (int i = 0; (!isDone) && (i < MAX_INITIALIZATION_ATTEMPTS); i++) {
try {
LOG.info("Initialization attempt " + (i + 1));
LOG.info("Initializing LeaseCoordinator");
leaseCoordinator.initialize();
TaskResult result = null;
if (!skipShardSyncAtWorkerInitializationIfLeasesExist
|| leaseCoordinator.getLeaseManager().isLeaseTableEmpty()) {
LOG.info("Syncing Kinesis shard info");
ShardSyncTask shardSyncTask =
new ShardSyncTask(streamConfig.getStreamProxy(),
leaseCoordinator.getLeaseManager(),
initialPosition,
cleanupLeasesUponShardCompletion,
0L);
result = new MetricsCollectingTaskDecorator(shardSyncTask, metricsFactory).call();
} else {
LOG.info("Skipping shard sync per config setting (and lease table is not empty)");
}
if (result == null || result.getException() == null) {
if (!leaseCoordinator.isRunning()) {
LOG.info("Starting LeaseCoordinator");
leaseCoordinator.start();
} else {
LOG.info("LeaseCoordinator is already running. No need to start it.");
}
isDone = true;
} else {
lastException = result.getException();
}
} catch (LeasingException e) {
LOG.error("Caught exception when initializing LeaseCoordinator", e);
lastException = e;
} catch (Exception e) {
lastException = e;
}
try {
Thread.sleep(parentShardPollIntervalMillis);
} catch (InterruptedException e) {
LOG.debug("Sleep interrupted while initializing worker.");
}
}
if (!isDone) {
throw new RuntimeException(lastException);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Shard getShard(String shardId) {
if (this.listOfShardsSinceLastGet.get() == null) {
//Update this.listOfShardsSinceLastGet as needed.
this.getShardList();
}
for (Shard shard : listOfShardsSinceLastGet.get()) {
if (shard.getShardId().equals(shardId)) {
return shard;
}
}
LOG.warn("Cannot find the shard given the shardId " + shardId);
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Shard getShard(String shardId) {
if (this.cachedShardMap == null) {
synchronized (this) {
if (this.cachedShardMap == null) {
this.getShardList();
}
}
}
Shard shard = cachedShardMap.get(shardId);
if (shard == null) {
if (cacheMisses.incrementAndGet() > MAX_CACHE_MISSES_BEFORE_RELOAD || cacheNeedsTimeUpdate()) {
synchronized (this) {
shard = cachedShardMap.get(shardId);
//
// If after synchronizing we resolve the shard, it means someone else already got it for us.
//
if (shard == null) {
LOG.info("To many shard map cache misses or cache is out of date -- forcing a refresh");
this.getShardList();
shard = verifyAndLogShardAfterCacheUpdate(shardId);
cacheMisses.set(0);
} else {
//
// If someone else got us the shard go ahead and zero cache misses
//
cacheMisses.set(0);
}
}
}
}
if (shard == null) {
String message = "Cannot find the shard given the shardId " + shardId + ". Cache misses: " + cacheMisses;
if (cacheMisses.get() % CACHE_MISS_WARNING_MODULUS == 0) {
LOG.warn(message);
} else {
LOG.debug(message);
}
}
return shard;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if (shutdown) {
return;
}
try {
initialize();
LOG.info("Initialization complete. Starting worker loop.");
} catch (RuntimeException e1) {
LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1);
shutdown();
}
while (!shouldShutdown()) {
try {
boolean foundCompletedShard = false;
Set<ShardInfo> assignedShards = new HashSet<ShardInfo>();
for (ShardInfo shardInfo : getShardInfoForAssignments()) {
ShardConsumer shardConsumer = createOrGetShardConsumer(shardInfo, recordProcessorFactory);
if (shardConsumer.isShutdown()
&& shardConsumer.getShutdownReason().equals(ShutdownReason.TERMINATE)) {
foundCompletedShard = true;
} else {
shardConsumer.consumeShard();
}
assignedShards.add(shardInfo);
}
if (foundCompletedShard) {
controlServer.syncShardAndLeaseInfo(null);
}
// clean up shard consumers for unassigned shards
cleanupShardConsumers(assignedShards);
wlog.info("Sleeping ...");
Thread.sleep(idleTimeInMilliseconds);
} catch (Exception e) {
LOG.error(String.format("Worker.run caught exception, sleeping for %s milli seconds!",
String.valueOf(idleTimeInMilliseconds)),
e);
try {
Thread.sleep(idleTimeInMilliseconds);
} catch (InterruptedException ex) {
LOG.info("Worker: sleep interrupted after catching exception ", ex);
}
}
wlog.resetInfoLogging();
}
finalShutdown();
LOG.info("Worker loop is complete. Exiting from worker.");
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
public void run() {
if (shutdown) {
return;
}
try {
initialize();
LOG.info("Initialization complete. Starting worker loop.");
} catch (RuntimeException e1) {
LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1);
shutdown();
}
while (!shouldShutdown()) {
runProcessLoop();
}
finalShutdown();
LOG.info("Worker loop is complete. Exiting from worker.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) {
if (executorService.isShutdown()) {
throw new IllegalStateException("ExecutorService has been shutdown.");
}
this.initialPositionInStreamExtended = initialPositionInStreamExtended;
highestSequenceNumber = extendedSequenceNumber.sequenceNumber();
dataFetcher.initialize(extendedSequenceNumber, initialPositionInStreamExtended);
if (!started) {
log.info("{} : Starting prefetching thread.", shardId);
executorService.execute(defaultGetRecordsCacheDaemon);
}
started = true;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) {
if (executorService.isShutdown()) {
throw new IllegalStateException("ExecutorService has been shutdown.");
}
publisherSession.init(extendedSequenceNumber, initialPositionInStreamExtended);
if (!started) {
log.info("{} : Starting prefetching thread.", shardId);
executorService.execute(defaultGetRecordsCacheDaemon);
}
started = true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public DescribeStreamResult getStreamInfo(String startShardId)
throws ResourceNotFoundException, LimitExceededException {
final DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest();
describeStreamRequest.setRequestCredentials(credentialsProvider.getCredentials());
describeStreamRequest.setStreamName(streamName);
describeStreamRequest.setExclusiveStartShardId(startShardId);
DescribeStreamResult response = null;
int remainingRetryTimes = this.maxDescribeStreamRetryAttempts;
// Call DescribeStream, with backoff and retries (if we get LimitExceededException).
while ((remainingRetryTimes >= 0) && (response == null)) {
try {
response = client.describeStream(describeStreamRequest);
} catch (LimitExceededException le) {
LOG.info("Got LimitExceededException when describing stream " + streamName + ". Backing off for "
+ this.describeStreamBackoffTimeInMillis + " millis.");
try {
Thread.sleep(this.describeStreamBackoffTimeInMillis);
} catch (InterruptedException ie) {
LOG.debug("Stream " + streamName + " : Sleep was interrupted ", ie);
}
}
remainingRetryTimes--;
}
if (StreamStatus.ACTIVE.toString().equals(response.getStreamDescription().getStreamStatus())
|| StreamStatus.UPDATING.toString().equals(response.getStreamDescription().getStreamStatus())) {
return response;
} else {
LOG.info("Stream is in status " + response.getStreamDescription().getStreamStatus()
+ ", KinesisProxy.DescribeStream returning null (wait until stream is Active or Updating");
return null;
}
}
#location 26
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public DescribeStreamResult getStreamInfo(String startShardId)
throws ResourceNotFoundException, LimitExceededException {
final DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest();
describeStreamRequest.setRequestCredentials(credentialsProvider.getCredentials());
describeStreamRequest.setStreamName(streamName);
describeStreamRequest.setExclusiveStartShardId(startShardId);
DescribeStreamResult response = null;
LimitExceededException lastException = null;
int remainingRetryTimes = this.maxDescribeStreamRetryAttempts;
// Call DescribeStream, with backoff and retries (if we get LimitExceededException).
while (response == null) {
try {
response = client.describeStream(describeStreamRequest);
} catch (LimitExceededException le) {
LOG.info("Got LimitExceededException when describing stream " + streamName + ". Backing off for "
+ this.describeStreamBackoffTimeInMillis + " millis.");
try {
Thread.sleep(this.describeStreamBackoffTimeInMillis);
} catch (InterruptedException ie) {
LOG.debug("Stream " + streamName + " : Sleep was interrupted ", ie);
}
lastException = le;
}
remainingRetryTimes--;
if (remainingRetryTimes <= 0 && response == null) {
if (lastException != null) {
throw lastException;
}
throw new IllegalStateException("Received null from DescribeStream call.");
}
}
if (StreamStatus.ACTIVE.toString().equals(response.getStreamDescription().getStreamStatus())
|| StreamStatus.UPDATING.toString().equals(response.getStreamDescription().getStreamStatus())) {
return response;
} else {
LOG.info("Stream is in status " + response.getStreamDescription().getStreamStatus()
+ ", KinesisProxy.DescribeStream returning null (wait until stream is Active or Updating");
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testRetryableRetrievalExceptionContinues() {
GetRecordsResponse response = GetRecordsResponse.builder().millisBehindLatest(100L).records(Collections.emptyList()).build();
when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenThrow(new RetryableRetrievalException("Timeout", new TimeoutException("Timeout"))).thenReturn(response);
getRecordsCache.start(sequenceNumber, initialPosition);
RecordsRetrieved records = getRecordsCache.getNextResult();
assertThat(records.processRecordsInput().millisBehindLatest(), equalTo(response.millisBehindLatest()));
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void testRetryableRetrievalExceptionContinues() {
GetRecordsResponse response = GetRecordsResponse.builder().millisBehindLatest(100L).records(Collections.emptyList()).build();
when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenThrow(new RetryableRetrievalException("Timeout", new TimeoutException("Timeout"))).thenReturn(response);
getRecordsCache.start(sequenceNumber, initialPosition);
RecordsRetrieved records = blockUntilRecordsAvailable(getRecordsCache::pollNextResultAndUpdatePrefetchCounters, 1000);
assertThat(records.processRecordsInput().millisBehindLatest(), equalTo(response.millisBehindLatest()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void onErrorStopsProcessingTest() throws Exception {
Throwable expected = new Throwable("Wheee");
addItemsToReturn(10);
recordsPublisher.add(new ResponseItem(expected));
addItemsToReturn(10);
setupNotifierAnswer(10);
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
for (int attempts = 0; attempts < 10; attempts++) {
if (subscriber.retrievalFailure() != null) {
break;
}
Thread.sleep(10);
}
verify(shardConsumer, times(10)).handleInput(argThat(eqProcessRecordsInput(processRecordsInput)),
any(Subscription.class));
assertThat(subscriber.retrievalFailure(), equalTo(expected));
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void onErrorStopsProcessingTest() throws Exception {
Throwable expected = new Throwable("Wheee");
addItemsToReturn(10);
recordsPublisher.add(new ResponseItem(expected));
addItemsToReturn(10);
setupNotifierAnswer(10);
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
for (int attempts = 0; attempts < 10; attempts++) {
if (subscriber.retrievalFailure() != null) {
break;
}
Thread.sleep(10);
}
verify(shardConsumer, times(10)).handleInput(any(ProcessRecordsInput.class), any(Subscription.class));
assertThat(subscriber.retrievalFailure(), equalTo(expected));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalStateException.class)
public void testGetNextRecordsWithoutStarting() {
verify(executorService, times(0)).execute(any());
getRecordsCache.pollNextResultAndUpdatePrefetchCounters();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test(expected = IllegalStateException.class)
public void testGetNextRecordsWithoutStarting() {
verify(executorService, times(0)).execute(any());
getRecordsCache.drainQueueForRequests();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void multipleItemTest() throws Exception {
addItemsToReturn(100);
setupNotifierAnswer(recordsPublisher.responses.size());
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
verify(shardConsumer, times(100)).handleInput(argThat(eqProcessRecordsInput(processRecordsInput)),
any(Subscription.class));
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void multipleItemTest() throws Exception {
addItemsToReturn(100);
setupNotifierAnswer(recordsPublisher.responses.size());
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
verify(shardConsumer, times(100)).handleInput(any(ProcessRecordsInput.class), any(Subscription.class));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalStateException.class)
public void testGetNextRecordsWithoutStarting() {
verify(executorService, times(0)).execute(any());
getRecordsCache.getNextResult();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test(expected = IllegalStateException.class)
public void testGetNextRecordsWithoutStarting() {
verify(executorService, times(0)).execute(any());
getRecordsCache.pollNextResultAndUpdatePrefetchCounters();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalStateException.class)
public void testCallAfterShutdown() {
when(executorService.isShutdown()).thenReturn(true);
getRecordsCache.pollNextResultAndUpdatePrefetchCounters();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test(expected = IllegalStateException.class)
public void testCallAfterShutdown() {
when(executorService.isShutdown()).thenReturn(true);
getRecordsCache.drainQueueForRequests();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void consumerErrorSkipsEntryTest() throws Exception {
addItemsToReturn(20);
Throwable testException = new Throwable("ShardConsumerError");
doAnswer(new Answer() {
int expectedInvocations = recordsPublisher.responses.size();
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
expectedInvocations--;
if (expectedInvocations == 10) {
throw testException;
}
if (expectedInvocations <= 0) {
synchronized (processedNotifier) {
processedNotifier.notifyAll();
}
}
return null;
}
}).when(shardConsumer).handleInput(any(ProcessRecordsInput.class), any(Subscription.class));
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
assertThat(subscriber.getAndResetDispatchFailure(), equalTo(testException));
assertThat(subscriber.getAndResetDispatchFailure(), nullValue());
verify(shardConsumer, times(20)).handleInput(argThat(eqProcessRecordsInput(processRecordsInput)),
any(Subscription.class));
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void consumerErrorSkipsEntryTest() throws Exception {
addItemsToReturn(20);
Throwable testException = new Throwable("ShardConsumerError");
doAnswer(new Answer() {
int expectedInvocations = recordsPublisher.responses.size();
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
expectedInvocations--;
if (expectedInvocations == 10) {
throw testException;
}
if (expectedInvocations <= 0) {
synchronized (processedNotifier) {
processedNotifier.notifyAll();
}
}
return null;
}
}).when(shardConsumer).handleInput(any(ProcessRecordsInput.class), any(Subscription.class));
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
assertThat(subscriber.getAndResetDispatchFailure(), equalTo(testException));
assertThat(subscriber.getAndResetDispatchFailure(), nullValue());
verify(shardConsumer, times(20)).handleInput(any(ProcessRecordsInput.class), any(Subscription.class));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testExpiredIteratorException() {
log.info("Starting tests");
when(getRecordsRetrievalStrategy.getRecords(MAX_RECORDS_PER_CALL)).thenThrow(ExpiredIteratorException.class)
.thenReturn(getRecordsResponse);
getRecordsCache.start(sequenceNumber, initialPosition);
doNothing().when(dataFetcher).restartIterator();
getRecordsCache.getNextResult();
sleep(1000);
verify(dataFetcher).restartIterator();
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void testExpiredIteratorException() {
log.info("Starting tests");
when(getRecordsRetrievalStrategy.getRecords(MAX_RECORDS_PER_CALL)).thenThrow(ExpiredIteratorException.class)
.thenReturn(getRecordsResponse);
getRecordsCache.start(sequenceNumber, initialPosition);
doNothing().when(dataFetcher).restartIterator();
blockUntilRecordsAvailable(() -> getRecordsCache.pollNextResultAndUpdatePrefetchCounters(), 1000L);
sleep(1000);
verify(dataFetcher).restartIterator();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGetRecords() {
record = Record.builder().data(createByteBufferWithSize(SIZE_512_KB)).build();
when(records.size()).thenReturn(1000);
final List<KinesisClientRecord> expectedRecords = records.stream()
.map(KinesisClientRecord::fromRecord).collect(Collectors.toList());
getRecordsCache.start(sequenceNumber, initialPosition);
ProcessRecordsInput result = getRecordsCache.getNextResult().processRecordsInput();
assertEquals(expectedRecords, result.records());
verify(executorService).execute(any());
verify(getRecordsRetrievalStrategy, atLeast(1)).getRecords(eq(MAX_RECORDS_PER_CALL));
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void testGetRecords() {
record = Record.builder().data(createByteBufferWithSize(SIZE_512_KB)).build();
when(records.size()).thenReturn(1000);
final List<KinesisClientRecord> expectedRecords = records.stream()
.map(KinesisClientRecord::fromRecord).collect(Collectors.toList());
getRecordsCache.start(sequenceNumber, initialPosition);
ProcessRecordsInput result = blockUntilRecordsAvailable(getRecordsCache::pollNextResultAndUpdatePrefetchCounters, 1000L)
.processRecordsInput();
assertEquals(expectedRecords, result.records());
verify(executorService).execute(any());
verify(getRecordsRetrievalStrategy, atLeast(1)).getRecords(eq(MAX_RECORDS_PER_CALL));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void singleItemTest() throws Exception {
addItemsToReturn(1);
setupNotifierAnswer(1);
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
verify(shardConsumer).handleInput(argThat(eqProcessRecordsInput(processRecordsInput)), any(Subscription.class));
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void singleItemTest() throws Exception {
addItemsToReturn(1);
setupNotifierAnswer(1);
synchronized (processedNotifier) {
subscriber.startSubscriptions();
processedNotifier.wait(5000);
}
verify(shardConsumer).handleInput(any(ProcessRecordsInput.class), any(Subscription.class));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalStateException.class)
public void testCallAfterShutdown() {
when(executorService.isShutdown()).thenReturn(true);
getRecordsCache.getNextResult();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test(expected = IllegalStateException.class)
public void testCallAfterShutdown() {
when(executorService.isShutdown()).thenReturn(true);
getRecordsCache.pollNextResultAndUpdatePrefetchCounters();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(timeout = 10000L)
public void testNoDeadlockOnFullQueue() {
//
// Fixes https://github.com/awslabs/amazon-kinesis-client/issues/448
//
// This test is to verify that the drain of a blocked queue no longer deadlocks.
// If the test times out before starting the subscriber it means something went wrong while filling the queue.
// After the subscriber is started one of the things that can trigger a timeout is a deadlock.
//
final int[] sequenceNumberInResponse = { 0 };
when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenAnswer( i -> GetRecordsResponse.builder().records(
Record.builder().data(SdkBytes.fromByteArray(new byte[] { 1, 2, 3 })).sequenceNumber(++sequenceNumberInResponse[0] + "").build())
.nextShardIterator(NEXT_SHARD_ITERATOR).build());
getRecordsCache.start(sequenceNumber, initialPosition);
//
// Wait for the queue to fill up, and the publisher to block on adding items to the queue.
//
log.info("Waiting for queue to fill up");
while (getRecordsCache.getPublisherSession().prefetchRecordsQueue().size() < MAX_SIZE) {
Thread.yield();
}
log.info("Queue is currently at {} starting subscriber", getRecordsCache.getPublisherSession().prefetchRecordsQueue().size());
AtomicInteger receivedItems = new AtomicInteger(0);
final int expectedItems = MAX_SIZE * 10;
Object lock = new Object();
final boolean[] isRecordNotInorder = { false };
final String[] recordNotInOrderMessage = { "" };
Subscriber<RecordsRetrieved> delegateSubscriber = new Subscriber<RecordsRetrieved>() {
Subscription sub;
int receivedSeqNum = 0;
@Override
public void onSubscribe(Subscription s) {
sub = s;
s.request(1);
}
@Override
public void onNext(RecordsRetrieved recordsRetrieved) {
receivedItems.incrementAndGet();
if (Integer.parseInt(((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved)
.lastBatchSequenceNumber()) != ++receivedSeqNum) {
isRecordNotInorder[0] = true;
recordNotInOrderMessage[0] = "Expected : " + receivedSeqNum + " Actual : "
+ ((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved)
.lastBatchSequenceNumber();
}
if (receivedItems.get() >= expectedItems) {
synchronized (lock) {
log.info("Notifying waiters");
lock.notifyAll();
}
sub.cancel();
} else {
sub.request(1);
}
}
@Override
public void onError(Throwable t) {
log.error("Caught error", t);
throw new RuntimeException(t);
}
@Override
public void onComplete() {
fail("onComplete not expected in this test");
}
};
Subscriber<RecordsRetrieved> subscriber = new ShardConsumerNotifyingSubscriber(delegateSubscriber, getRecordsCache);
synchronized (lock) {
log.info("Awaiting notification");
Flowable.fromPublisher(getRecordsCache).subscribeOn(Schedulers.computation())
.observeOn(Schedulers.computation(), true, 8).subscribe(subscriber);
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
verify(getRecordsRetrievalStrategy, atLeast(expectedItems)).getRecords(anyInt());
assertThat(receivedItems.get(), equalTo(expectedItems));
assertFalse(recordNotInOrderMessage[0], isRecordNotInorder[0]);
}
#location 80
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test(timeout = 10000L)
public void testNoDeadlockOnFullQueue() {
//
// Fixes https://github.com/awslabs/amazon-kinesis-client/issues/448
//
// This test is to verify that the drain of a blocked queue no longer deadlocks.
// If the test times out before starting the subscriber it means something went wrong while filling the queue.
// After the subscriber is started one of the things that can trigger a timeout is a deadlock.
//
final int[] sequenceNumberInResponse = { 0 };
when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenAnswer( i -> GetRecordsResponse.builder().records(
Record.builder().data(SdkBytes.fromByteArray(new byte[] { 1, 2, 3 })).sequenceNumber(++sequenceNumberInResponse[0] + "").build())
.nextShardIterator(NEXT_SHARD_ITERATOR).build());
getRecordsCache.start(sequenceNumber, initialPosition);
//
// Wait for the queue to fill up, and the publisher to block on adding items to the queue.
//
log.info("Waiting for queue to fill up");
while (getRecordsCache.getPublisherSession().prefetchRecordsQueue().size() < MAX_SIZE) {
Thread.yield();
}
log.info("Queue is currently at {} starting subscriber", getRecordsCache.getPublisherSession().prefetchRecordsQueue().size());
AtomicInteger receivedItems = new AtomicInteger(0);
final int expectedItems = MAX_SIZE * 10;
Object lock = new Object();
final boolean[] isRecordNotInorder = { false };
final String[] recordNotInOrderMessage = { "" };
Subscriber<RecordsRetrieved> delegateSubscriber = new Subscriber<RecordsRetrieved>() {
Subscription sub;
int receivedSeqNum = 0;
@Override
public void onSubscribe(Subscription s) {
sub = s;
s.request(1);
}
@Override
public void onNext(RecordsRetrieved recordsRetrieved) {
receivedItems.incrementAndGet();
if (Integer.parseInt(((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved)
.lastBatchSequenceNumber()) != ++receivedSeqNum) {
isRecordNotInorder[0] = true;
recordNotInOrderMessage[0] = "Expected : " + receivedSeqNum + " Actual : "
+ ((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved)
.lastBatchSequenceNumber();
}
if (receivedItems.get() >= expectedItems) {
synchronized (lock) {
log.info("Notifying waiters");
lock.notifyAll();
}
sub.cancel();
} else {
sub.request(1);
}
}
@Override
public void onError(Throwable t) {
log.error("Caught error", t);
throw new RuntimeException(t);
}
@Override
public void onComplete() {
fail("onComplete not expected in this test");
}
};
Subscriber<RecordsRetrieved> subscriber = new ShardConsumerNotifyingSubscriber(delegateSubscriber, getRecordsCache);
synchronized (lock) {
log.info("Awaiting notification");
Flowable.fromPublisher(getRecordsCache).subscribeOn(Schedulers.computation())
.observeOn(Schedulers.computation(), true, 8).subscribe(subscriber);
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
verify(getRecordsRetrievalStrategy, atLeast(expectedItems)).getRecords(anyInt());
assertThat(receivedItems.get(), equalTo(expectedItems));
assertFalse(recordNotInOrderMessage[0], isRecordNotInorder[0]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if (shutdown) {
return;
}
try {
initialize();
LOG.info("Initialization complete. Starting worker loop.");
} catch (RuntimeException e1) {
LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1);
shutdown();
}
while (!shouldShutdown()) {
try {
boolean foundCompletedShard = false;
Set<ShardInfo> assignedShards = new HashSet<ShardInfo>();
for (ShardInfo shardInfo : getShardInfoForAssignments()) {
ShardConsumer shardConsumer = createOrGetShardConsumer(shardInfo, recordProcessorFactory);
if (shardConsumer.isShutdown()
&& shardConsumer.getShutdownReason().equals(ShutdownReason.TERMINATE)) {
foundCompletedShard = true;
} else {
shardConsumer.consumeShard();
}
assignedShards.add(shardInfo);
}
if (foundCompletedShard) {
controlServer.syncShardAndLeaseInfo(null);
}
// clean up shard consumers for unassigned shards
cleanupShardConsumers(assignedShards);
wlog.info("Sleeping ...");
Thread.sleep(idleTimeInMilliseconds);
} catch (Exception e) {
LOG.error(String.format("Worker.run caught exception, sleeping for %s milli seconds!",
String.valueOf(idleTimeInMilliseconds)),
e);
try {
Thread.sleep(idleTimeInMilliseconds);
} catch (InterruptedException ex) {
LOG.info("Worker: sleep interrupted after catching exception ", ex);
}
}
wlog.resetInfoLogging();
}
finalShutdown();
LOG.info("Worker loop is complete. Exiting from worker.");
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
public void run() {
if (shutdown) {
return;
}
try {
initialize();
LOG.info("Initialization complete. Starting worker loop.");
} catch (RuntimeException e1) {
LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1);
shutdown();
}
while (!shouldShutdown()) {
runProcessLoop();
}
finalShutdown();
LOG.info("Worker loop is complete. Exiting from worker.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void reloadConfig() throws IOException {
LOGGER.log(Level.INFO, "Reloading configuration");
loadConfig(new FileReader(WebServer.configFilePath), activeConfig.client);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
protected void reloadConfig() throws IOException {
LOGGER.log(Level.INFO, "Reloading configuration");
FileReader reader = null;
try {
reader = new FileReader(WebServer.configFilePath);
loadConfig(reader, activeConfig.client);
} finally {
reader.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping("/error")
@ResponseStatus(HttpStatus.OK)
public Result<String> error() {
RequestContext ctx = RequestContext.getCurrentContext();
Throwable throwable = ctx.getThrowable();
if(null != throwable && throwable instanceof ZuulException ){
ZuulException e = (ZuulException) ctx.getThrowable();
return Result.error(e.nStatusCode, e.errorCause);
}
return Result.error(99,throwable.getMessage());
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@RequestMapping("/error")
@ResponseStatus(HttpStatus.OK)
public Result<String> error() {
RequestContext ctx = RequestContext.getCurrentContext();
Throwable throwable = ctx.getThrowable();
if(null != throwable && throwable instanceof ZuulException ){
ZuulException e = (ZuulException) ctx.getThrowable();
return Result.error(e.nStatusCode, e.errorCause);
}
return Result.error(ResultEnum.ERROR);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws Exception {
for (int i = 0; i < 5; i++) {
SpecCaptcha specCaptcha = new SpecCaptcha();
//specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
System.out.println(specCaptcha.text());
specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png")));
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() throws Exception {
for (int i = 0; i < 5; i++) {
SpecCaptcha specCaptcha = new SpecCaptcha();
//specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
System.out.println(specCaptcha.text());
//specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png")));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws Exception {
SpecCaptcha specCaptcha = new SpecCaptcha();
System.out.println(specCaptcha.text());
specCaptcha.out(new FileOutputStream(new File("D:/a/aa.png")));
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() throws Exception {
SpecCaptcha specCaptcha = new SpecCaptcha();
System.out.println(specCaptcha.text());
//specCaptcha.out(new FileOutputStream(new File("D:/a/aa.png")));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testHan() throws Exception {
ChineseCaptcha chineseCaptcha = new ChineseCaptcha();
//chineseCaptcha.setFont(new Font("微软雅黑", Font.PLAIN, 25));
System.out.println(chineseCaptcha.text());
chineseCaptcha.out(new FileOutputStream(new File("D:/Java/aa.png")));
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testHan() throws Exception {
ChineseCaptcha chineseCaptcha = new ChineseCaptcha();
//chineseCaptcha.setFont(new Font("微软雅黑", Font.PLAIN, 25));
System.out.println(chineseCaptcha.text());
//chineseCaptcha.out(new FileOutputStream(new File("D:/Java/aa.png")));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws Exception {
for (int i = 0; i < 100; i++) {
SpecCaptcha specCaptcha = new SpecCaptcha();
specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
System.out.println(specCaptcha.text());
specCaptcha.out(new FileOutputStream(new File("D:/a/aa" + i + ".png")));
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() throws Exception {
for (int i = 0; i < 5; i++) {
SpecCaptcha specCaptcha = new SpecCaptcha();
//specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
System.out.println(specCaptcha.text());
//specCaptcha.out(new FileOutputStream(new File("C:/aa" + i + ".png")));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
Map<String, List<LocalLoader>> getPathsUnchecked(final boolean export) {
try {
return getPaths(export);
} catch (ModuleLoadException e) {
throw e.toError();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
boolean linkExports(final Linkage linkage) throws ModuleLoadException {
final HashMap<String, List<LocalLoader>> exportsMap = new HashMap<String, List<LocalLoader>>();
final Dependency[] dependencies = linkage.getSourceList();
final long start = Metrics.getCurrentCPUTime();
long subtractTime = 0L;
try {
final Set<Visited> visited = new FastCopyHashSet<Visited>(16);
final FastCopyHashSet<PathFilter> filterStack = new FastCopyHashSet<PathFilter>(8);
subtractTime += addExportedPaths(dependencies, exportsMap, filterStack, visited);
synchronized (this) {
if (this.linkage == linkage) {
this.linkage = new Linkage(linkage.getSourceList(), LINKED_EXPORTS, linkage.getAllPaths(), exportsMap);
notifyAll();
return true;
}
// else all our efforts were just wasted since someone changed the deps in the meantime
return false;
}
} finally {
moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime);
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void link(final Linkage linkage) throws ModuleLoadException {
final HashMap<String, List<LocalLoader>> importsMap = new HashMap<String, List<LocalLoader>>();
final HashMap<String, List<LocalLoader>> exportsMap = new HashMap<String, List<LocalLoader>>();
final Dependency[] dependencies = linkage.getSourceList();
final long start = Metrics.getCurrentCPUTime();
try {
addPaths(dependencies, importsMap);
addExportedPaths(dependencies, exportsMap);
synchronized (this) {
if (this.linkage == linkage) {
this.linkage = new Linkage(linkage.getSourceList(), Linkage.State.LINKED, importsMap, exportsMap);
notifyAll();
}
// else all our efforts were just wasted since someone changed the deps in the meantime
}
} finally {
moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start);
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
} else {
final FastCopyHashSet<PathFilter> clone = filterStack.clone();
clone.add(importFilter);
clone.add(exportFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited);
}
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void buildIndex(final List<String> index, final File root, final String pathBase) {
for (File file : root.listFiles()) {
if (file.isDirectory()) {
index.add(pathBase + file.getName());
buildIndex(index, file, pathBase + file.getName() + "/");
}
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
private void buildIndex(final List<String> index, final File root, final String pathBase) {
File[] files = root.listFiles();
if (files != null) for (File file : files) {
if (file.isDirectory()) {
index.add(pathBase + file.getName());
buildIndex(index, file, pathBase + file.getName() + "/");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
Map<String, List<LocalLoader>> getPathsUnchecked(final boolean export) {
try {
return getPaths(export);
} catch (ModuleLoadException e) {
throw e.toError();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static IterableResourceLoader createIterableFileResourceLoader(final String name, final File root) {
return new FileResourceLoader(name, root, AccessController.getContext());
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static IterableResourceLoader createIterableFileResourceLoader(final String name, final File root) {
return createFileResourceLoader(name, root);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static FactoryPermissionCollection parsePermissionsXml(final InputStream inputStream, ModuleLoader moduleLoader, final String moduleName) throws XmlPullParserException, IOException {
final MXParser mxParser = new MXParser();
mxParser.setInput(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
return parsePermissionsXml(mxParser, moduleLoader, moduleName);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public static FactoryPermissionCollection parsePermissionsXml(final InputStream inputStream, ModuleLoader moduleLoader, final String moduleName) throws XmlPullParserException, IOException {
final MXParser mxParser = new MXParser();
mxParser.setFeature(FEATURE_PROCESS_NAMESPACES, true);
mxParser.setInput(inputStream, null);
return parsePermissionsXml(mxParser, moduleLoader, moduleName);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
filterStack.add(importFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
filterStack.remove(importFilter);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
Map<String, List<LocalLoader>> getPaths(final boolean exports) throws ModuleLoadException {
Linkage linkage = this.linkage;
Linkage.State state = linkage.getState();
if (state.compareTo(exports ? LINKED_EXPORTS : LINKED) >= 0) {
return linkage.getPaths(exports);
}
// slow path loop
boolean intr = false;
try {
for (;;) {
synchronized (this) {
linkage = this.linkage;
state = linkage.getState();
while (state == (exports ? LINKING_EXPORTS : LINKING) || state == NEW) try {
wait();
linkage = this.linkage;
state = linkage.getState();
} catch (InterruptedException e) {
intr = true;
}
if (state == (exports ? LINKED_EXPORTS : LINKED)) {
return linkage.getPaths(exports);
}
this.linkage = linkage = new Linkage(linkage.getSourceList(), exports ? LINKING_EXPORTS : LINKING);
// fall out and link
}
if (exports) {
linkExports(linkage);
} else {
link(linkage);
}
}
} finally {
if (intr) {
Thread.currentThread().interrupt();
}
}
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ModuleLoader forClass(Class<?> clazz) {
return Module.forClass(clazz).getModuleLoader();
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public static ModuleLoader forClass(Class<?> clazz) {
final Module module = Module.forClass(clazz);
if (module == null) {
return null;
}
return module.getModuleLoader();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void linkIfNecessary() throws ModuleLoadException {
Linkage linkage = this.linkage;
if (linkage.getState().compareTo(LINKING) >= 0) {
return;
}
synchronized (this) {
linkage = this.linkage;
if (linkage.getState().compareTo(LINKING) >= 0) {
return;
}
this.linkage = linkage = new Linkage(linkage.getSourceList(), LINKING);
}
link(linkage);
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack, classFilterStack, resourceFilterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
final FastCopyHashSet<PathFilter> nestedFilters;
final FastCopyHashSet<ClassFilter> nestedClassFilters;
final FastCopyHashSet<PathFilter> nestedResourceFilters;
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
nestedFilters = filterStack;
} else {
nestedFilters = filterStack.clone();
nestedFilters.add(importFilter);
nestedFilters.add(exportFilter);
}
final ClassFilter classImportFilter = dependency.getClassImportFilter();
final ClassFilter classExportFilter = dependency.getClassExportFilter();
if ((classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) && (classExportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classExportFilter))) {
nestedClassFilters = classFilterStack;
} else {
nestedClassFilters = classFilterStack.clone();
if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter);
if (classExportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classExportFilter);
}
final PathFilter resourceImportFilter = dependency.getResourceImportFilter();
final PathFilter resourceExportFilter = dependency.getResourceExportFilter();
if ((resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) && (resourceExportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceExportFilter))) {
nestedResourceFilters = resourceFilterStack;
} else {
nestedResourceFilters = resourceFilterStack.clone();
if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter);
if (resourceExportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceExportFilter);
}
subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
LocalLoader localLoader = classLoaderDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classImportFilter = classLoaderDependency.getClassImportFilter();
if (classImportFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classImportFilter, localLoader);
}
ClassFilter classExportFilter = classLoaderDependency.getClassExportFilter();
if (classExportFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classExportFilter, localLoader);
}
PathFilter resourceImportFilter = classLoaderDependency.getResourceImportFilter();
if (resourceImportFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceImportFilter, localLoader);
}
PathFilter resourceExportFilter = classLoaderDependency.getResourceExportFilter();
if (resourceExportFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceExportFilter, localLoader);
}
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && importFilter.accept(path) && exportFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
LocalLoader localLoader = localDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classFilter = localDependency.getClassExportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
classFilter = localDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
PathFilter resourceFilter = localDependency.getResourceExportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
resourceFilter = localDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
final FastCopyHashSet<PathFilter> nestedFilters;
final FastCopyHashSet<ClassFilter> nestedClassFilters;
final FastCopyHashSet<PathFilter> nestedResourceFilters;
if (filterStack.contains(importFilter)) {
nestedFilters = filterStack;
} else {
nestedFilters = filterStack.clone();
nestedFilters.add(importFilter);
}
final ClassFilter classImportFilter = dependency.getClassImportFilter();
if (classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) {
nestedClassFilters = classFilterStack;
} else {
nestedClassFilters = classFilterStack.clone();
if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter);
}
final PathFilter resourceImportFilter = dependency.getResourceImportFilter();
if (resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) {
nestedResourceFilters = resourceFilterStack;
} else {
nestedResourceFilters = resourceFilterStack.clone();
if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter);
}
subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
LocalLoader localLoader = classLoaderDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classFilter = classLoaderDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
PathFilter resourceFilter = classLoaderDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
LocalLoader localLoader = localDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
final ClassFilter classFilter = localDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
final PathFilter resourceFilter = localDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 54
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
filterStack.add(importFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
filterStack.remove(importFilter);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
filterStack.add(importFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
filterStack.remove(importFilter);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void link(final Linkage linkage) throws ModuleLoadException {
final HashMap<String, List<LocalLoader>> importsMap = new HashMap<String, List<LocalLoader>>();
final HashMap<String, List<LocalLoader>> exportsMap = new HashMap<String, List<LocalLoader>>();
final Dependency[] dependencies = linkage.getSourceList();
final long start = Metrics.getCurrentCPUTime();
long subtractTime = 0L;
try {
final Set<Visited> visited = new FastCopyHashSet<Visited>(16);
final FastCopyHashSet<PathFilter> filterStack = new FastCopyHashSet<PathFilter>(8);
final FastCopyHashSet<ClassFilter> classFilterStack = EMPTY_CLASS_FILTERS;
final FastCopyHashSet<PathFilter> resourceFilterStack = EMPTY_PATH_FILTERS;
subtractTime += addPaths(dependencies, importsMap, filterStack, classFilterStack, resourceFilterStack, visited);
subtractTime += addExportedPaths(dependencies, exportsMap, filterStack, classFilterStack, resourceFilterStack, visited);
synchronized (this) {
if (this.linkage == linkage) {
this.linkage = new Linkage(linkage.getSourceList(), Linkage.State.LINKED, importsMap, exportsMap);
notifyAll();
}
// else all our efforts were just wasted since someone changed the deps in the meantime
}
} finally {
moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime);
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
Map<String, List<LocalLoader>> getPaths(final boolean exports) throws ModuleLoadException {
Linkage oldLinkage = this.linkage;
Linkage linkage;
Linkage.State state = oldLinkage.getState();
if (state == Linkage.State.LINKED) {
return oldLinkage.getPaths(exports);
}
// slow path loop
boolean intr = false;
try {
for (;;) {
synchronized (this) {
oldLinkage = this.linkage;
state = oldLinkage.getState();
while (state == Linkage.State.LINKING || state == Linkage.State.NEW) try {
wait();
oldLinkage = this.linkage;
state = oldLinkage.getState();
} catch (InterruptedException e) {
intr = true;
}
if (state == Linkage.State.LINKED) {
return oldLinkage.getPaths(exports);
}
this.linkage = linkage = new Linkage(oldLinkage.getSourceList(), Linkage.State.LINKING);
// fall out and link
}
boolean ok = false;
try {
link(linkage);
ok = true;
} finally {
if (! ok) {
// restore original (lack of) linkage
synchronized (this) {
if (this.linkage == linkage) {
this.linkage = oldLinkage;
notifyAll();
}
}
}
}
}
} finally {
if (intr) {
Thread.currentThread().interrupt();
}
}
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
filterStack.add(importFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
filterStack.remove(importFilter);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void addClassPath(final ModuleSpec.Builder builder, final String classPath) throws ModuleLoadException {
String[] classPathEntries = (classPath == null ? NO_STRINGS : classPath.split(File.pathSeparator));
final File workingDir = new File(System.getProperty("user.dir"));
for (String entry : classPathEntries) {
if (!entry.isEmpty()) {
try {
// Find the directory
File root = new File(entry);
if (! root.isAbsolute()) {
root = new File(workingDir, root.getPath());
}
if (root.isFile()) {
try {
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createJarResourceLoader(root.getParent(), new JarFile(root, true))));
} catch (Exception e) {
Module.log.trace(e, "Resource %s does not appear to be a valid JAR. Loaded as file resource.", root);
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createFileResourceLoader(entry, root)));
}
} else {
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createFileResourceLoader(entry, root)));
}
} catch (Exception e) {
throw new ModuleLoadException(String.format("File %s in class path not valid.", entry), e);
}
}
}
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
private void addClassPath(final ModuleSpec.Builder builder, final String classPath) throws ModuleLoadException {
String[] classPathEntries = (classPath == null ? NO_STRINGS : classPath.split(File.pathSeparator));
final File workingDir = new File(System.getProperty("user.dir"));
for (String entry : classPathEntries) {
if (!entry.isEmpty()) {
try {
// Find the directory
File root = new File(entry);
if (! root.isAbsolute()) {
root = new File(workingDir, root.getPath());
}
if (root.isFile()) {
try {
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createJarResourceLoader(root.getParent(), JDKSpecific.getJarFile(root, true))));
} catch (Exception e) {
Module.log.trace(e, "Resource %s does not appear to be a valid JAR. Loaded as file resource.", root);
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createFileResourceLoader(entry, root)));
}
} else {
builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createFileResourceLoader(entry, root)));
}
} catch (Exception e) {
throw new ModuleLoadException(String.format("File %s in class path not valid.", entry), e);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
} else {
final FastCopyHashSet<PathFilter> clone = filterStack.clone();
clone.add(importFilter);
clone.add(exportFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited);
}
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
Map<String, List<LocalLoader>> getPaths(final boolean exports) throws ModuleLoadException {
Linkage linkage = this.linkage;
Linkage.State state = linkage.getState();
if (state.compareTo(exports ? LINKED_EXPORTS : LINKED) >= 0) {
return linkage.getPaths(exports);
}
// slow path loop
boolean intr = false;
try {
for (;;) {
synchronized (this) {
linkage = this.linkage;
state = linkage.getState();
while (state == (exports ? LINKING_EXPORTS : LINKING) || state == NEW) try {
wait();
linkage = this.linkage;
state = linkage.getState();
} catch (InterruptedException e) {
intr = true;
}
if (state == (exports ? LINKED_EXPORTS : LINKED)) {
return linkage.getPaths(exports);
}
this.linkage = linkage = new Linkage(linkage.getSourceList(), exports ? LINKING_EXPORTS : LINKING);
// fall out and link
}
if (exports) {
linkExports(linkage);
} else {
link(linkage);
}
}
} finally {
if (intr) {
Thread.currentThread().interrupt();
}
}
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException {
File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name));
if (fp == null) return null;
JarFile jarFile = new JarFile(fp, true);
return ResourceLoaders.createJarResourceLoader(name, jarFile);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException {
File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name));
if (fp == null) return null;
JarFile jarFile = JDKSpecific.getJarFile(fp, true);
return ResourceLoaders.createJarResourceLoader(name, jarFile);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack, classFilterStack, resourceFilterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
final FastCopyHashSet<PathFilter> nestedFilters;
final FastCopyHashSet<ClassFilter> nestedClassFilters;
final FastCopyHashSet<PathFilter> nestedResourceFilters;
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
nestedFilters = filterStack;
} else {
nestedFilters = filterStack.clone();
nestedFilters.add(importFilter);
nestedFilters.add(exportFilter);
}
final ClassFilter classImportFilter = dependency.getClassImportFilter();
final ClassFilter classExportFilter = dependency.getClassExportFilter();
if ((classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) && (classExportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classExportFilter))) {
nestedClassFilters = classFilterStack;
} else {
nestedClassFilters = classFilterStack.clone();
if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter);
if (classExportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classExportFilter);
}
final PathFilter resourceImportFilter = dependency.getResourceImportFilter();
final PathFilter resourceExportFilter = dependency.getResourceExportFilter();
if ((resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) && (resourceExportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceExportFilter))) {
nestedResourceFilters = resourceFilterStack;
} else {
nestedResourceFilters = resourceFilterStack.clone();
if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter);
if (resourceExportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceExportFilter);
}
subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
LocalLoader localLoader = classLoaderDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classImportFilter = classLoaderDependency.getClassImportFilter();
if (classImportFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classImportFilter, localLoader);
}
ClassFilter classExportFilter = classLoaderDependency.getClassExportFilter();
if (classExportFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classExportFilter, localLoader);
}
PathFilter resourceImportFilter = classLoaderDependency.getResourceImportFilter();
if (resourceImportFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceImportFilter, localLoader);
}
PathFilter resourceExportFilter = classLoaderDependency.getResourceExportFilter();
if (resourceExportFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceExportFilter, localLoader);
}
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && importFilter.accept(path) && exportFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
LocalLoader localLoader = localDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classFilter = localDependency.getClassExportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
classFilter = localDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
PathFilter resourceFilter = localDependency.getResourceExportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
resourceFilter = localDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void relinkIfNecessary() throws ModuleLoadException {
Linkage linkage = this.linkage;
if (linkage.getState() != Linkage.State.UNLINKED) {
return;
}
synchronized (this) {
linkage = this.linkage;
if (linkage.getState() != Linkage.State.UNLINKED) {
return;
}
this.linkage = linkage = new Linkage(linkage.getSourceList(), Linkage.State.LINKING);
}
link(linkage);
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack, classFilterStack, resourceFilterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
final FastCopyHashSet<PathFilter> nestedFilters;
final FastCopyHashSet<ClassFilter> nestedClassFilters;
final FastCopyHashSet<PathFilter> nestedResourceFilters;
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
nestedFilters = filterStack;
} else {
nestedFilters = filterStack.clone();
nestedFilters.add(importFilter);
nestedFilters.add(exportFilter);
}
final ClassFilter classImportFilter = dependency.getClassImportFilter();
final ClassFilter classExportFilter = dependency.getClassExportFilter();
if ((classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) && (classExportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classExportFilter))) {
nestedClassFilters = classFilterStack;
} else {
nestedClassFilters = classFilterStack.clone();
if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter);
if (classExportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classExportFilter);
}
final PathFilter resourceImportFilter = dependency.getResourceImportFilter();
final PathFilter resourceExportFilter = dependency.getResourceExportFilter();
if ((resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) && (resourceExportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceExportFilter))) {
nestedResourceFilters = resourceFilterStack;
} else {
nestedResourceFilters = resourceFilterStack.clone();
if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter);
if (resourceExportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceExportFilter);
}
subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
LocalLoader localLoader = classLoaderDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classImportFilter = classLoaderDependency.getClassImportFilter();
if (classImportFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classImportFilter, localLoader);
}
ClassFilter classExportFilter = classLoaderDependency.getClassExportFilter();
if (classExportFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classExportFilter, localLoader);
}
PathFilter resourceImportFilter = classLoaderDependency.getResourceImportFilter();
if (resourceImportFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceImportFilter, localLoader);
}
PathFilter resourceExportFilter = classLoaderDependency.getResourceExportFilter();
if (resourceExportFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceExportFilter, localLoader);
}
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && importFilter.accept(path) && exportFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
LocalLoader localLoader = localDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classFilter = localDependency.getClassExportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
classFilter = localDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
PathFilter resourceFilter = localDependency.getResourceExportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
resourceFilter = localDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
} else {
final FastCopyHashSet<PathFilter> clone = filterStack.clone();
clone.add(importFilter);
clone.add(exportFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited);
}
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException {
if (!visited.add(new Visited(this, filterStack))) {
return 0L;
}
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
final PathFilter exportFilter = dependency.getExportFilter();
// skip non-exported dependencies altogether
if (exportFilter != PathFilters.rejectAll()) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) {
subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited);
} else {
final FastCopyHashSet<PathFilter> clone = filterStack.clone();
clone.add(importFilter);
clone.add(exportFilter);
subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited);
}
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
final LocalLoader localLoader = classLoaderDependency.getLocalLoader();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
final LocalLoader localLoader = localDependency.getLocalLoader();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
boolean accept = true;
for (Object filter : filterStack.getRawArray()) {
if (filter != null && ! ((PathFilter)filter).accept(path)) {
accept = false; break;
}
}
if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>(1));
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
}
return subtract;
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
final FastCopyHashSet<PathFilter> nestedFilters;
final FastCopyHashSet<ClassFilter> nestedClassFilters;
final FastCopyHashSet<PathFilter> nestedResourceFilters;
if (filterStack.contains(importFilter)) {
nestedFilters = filterStack;
} else {
nestedFilters = filterStack.clone();
nestedFilters.add(importFilter);
}
final ClassFilter classImportFilter = dependency.getClassImportFilter();
if (classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) {
nestedClassFilters = classFilterStack;
} else {
nestedClassFilters = classFilterStack.clone();
if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter);
}
final PathFilter resourceImportFilter = dependency.getResourceImportFilter();
if (resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) {
nestedResourceFilters = resourceFilterStack;
} else {
nestedResourceFilters = resourceFilterStack.clone();
if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter);
}
subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
LocalLoader localLoader = classLoaderDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classFilter = classLoaderDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
PathFilter resourceFilter = classLoaderDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
LocalLoader localLoader = localDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
final ClassFilter classFilter = localDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
final PathFilter resourceFilter = localDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 54
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException {
long subtract = 0L;
moduleLoader.incScanCount();
for (Dependency dependency : dependencies) {
if (dependency instanceof ModuleDependency) {
final ModuleDependency moduleDependency = (ModuleDependency) dependency;
final ModuleLoader moduleLoader = moduleDependency.getModuleLoader();
final ModuleIdentifier id = moduleDependency.getIdentifier();
final Module module;
try {
long pauseStart = Metrics.getCurrentCPUTime();
try {
module = moduleLoader.preloadModule(id);
} finally {
subtract += Metrics.getCurrentCPUTime() - pauseStart;
}
} catch (ModuleLoadException ex) {
if (moduleDependency.isOptional()) {
continue;
} else {
throw ex;
}
}
if (module == null) {
if (!moduleDependency.isOptional()) {
throw new ModuleNotFoundException(id.toString());
}
continue;
}
final PathFilter importFilter = dependency.getImportFilter();
final FastCopyHashSet<PathFilter> nestedFilters;
final FastCopyHashSet<ClassFilter> nestedClassFilters;
final FastCopyHashSet<PathFilter> nestedResourceFilters;
if (filterStack.contains(importFilter)) {
nestedFilters = filterStack;
} else {
nestedFilters = filterStack.clone();
nestedFilters.add(importFilter);
}
final ClassFilter classImportFilter = dependency.getClassImportFilter();
if (classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) {
nestedClassFilters = classFilterStack;
} else {
nestedClassFilters = classFilterStack.clone();
if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter);
}
final PathFilter resourceImportFilter = dependency.getResourceImportFilter();
if (resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) {
nestedResourceFilters = resourceFilterStack;
} else {
nestedResourceFilters = resourceFilterStack.clone();
if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter);
}
subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited);
} else if (dependency instanceof ModuleClassLoaderDependency) {
final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency;
LocalLoader localLoader = classLoaderDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
ClassFilter classFilter = classLoaderDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
PathFilter resourceFilter = classLoaderDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final PathFilter importFilter = classLoaderDependency.getImportFilter();
final Set<String> paths = classLoaderDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
} else if (dependency instanceof LocalDependency) {
final LocalDependency localDependency = (LocalDependency) dependency;
LocalLoader localLoader = localDependency.getLocalLoader();
for (Object filter : classFilterStack.getRawArray()) {
if (filter != null && filter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader);
}
}
for (Object filter : resourceFilterStack.getRawArray()) {
if (filter != null && filter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader);
}
}
final ClassFilter classFilter = localDependency.getClassImportFilter();
if (classFilter != ClassFilters.acceptAll()) {
localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader);
}
final PathFilter resourceFilter = localDependency.getResourceImportFilter();
if (resourceFilter != PathFilters.acceptAll()) {
localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader);
}
final PathFilter importFilter = localDependency.getImportFilter();
final Set<String> paths = localDependency.getPaths();
for (String path : paths) {
if (importFilter.accept(path)) {
List<LocalLoader> list = map.get(path);
if (list == null) {
map.put(path, list = new ArrayList<LocalLoader>());
list.add(localLoader);
} else if (! list.contains(localLoader)) {
list.add(localLoader);
}
}
}
}
// else unknown dep type so just skip
}
return subtract;
}
#location 56
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) {
this.moduleLoader = moduleLoader;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
final Map<String, String> properties = spec.getProperties();
this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
Class<?> loadModuleClass(final String className, final boolean exportsOnly, final boolean resolve) {
for (String s : systemPackages) {
if (className.startsWith(s)) {
try {
return moduleClassLoader.loadClass(className, resolve);
} catch (ClassNotFoundException e) {
return null;
}
}
}
final String path = pathOfClass(className);
final Map<String, List<LocalLoader>> paths = getPathsUnchecked(exportsOnly);
final List<LocalLoader> loaders = paths.get(path);
if (loaders != null) {
Class<?> clazz;
for (LocalLoader loader : loaders) {
clazz = loader.loadClassLocal(className, resolve);
if (clazz != null) {
return clazz;
}
}
}
final LocalLoader fallbackLoader = this.fallbackLoader;
if (fallbackLoader != null) {
return fallbackLoader.loadClassLocal(className, resolve);
}
return null;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) {
this.moduleLoader = moduleLoader;
this.myKey = myKey;
// Initialize state from the spec.
identifier = spec.getModuleIdentifier();
mainClassName = spec.getMainClass();
fallbackLoader = spec.getFallbackLoader();
//noinspection ThisEscapedInObjectConstruction
final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer());
final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory();
ModuleClassLoader moduleClassLoader = null;
if (factory != null) moduleClassLoader = factory.create(configuration);
if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration);
this.moduleClassLoader = moduleClassLoader;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSnapshotResolving()throws Exception{
ArtifactCoordinates coordinates = ArtifactCoordinates.fromString("org.wildfly.core:wildfly-version:2.0.5.Final-20151222.144931-1");
String path = MavenArtifactUtil.relativeArtifactPath('/', coordinates.getGroupId(), coordinates.getArtifactId(), coordinates.getVersion());
Assert.assertEquals("org/wildfly/core/wildfly-version/2.0.5.Final-SNAPSHOT/wildfly-version-2.0.5.Final-20151222.144931-1", path);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSnapshotResolving()throws Exception{
ArtifactCoordinates coordinates = ArtifactCoordinates.fromString("org.wildfly.core:wildfly-version:2.0.5.Final-20151222.144931-1");
String path = MavenArtifactUtil.relativeArtifactPath('/', coordinates);
Assert.assertEquals("org/wildfly/core/wildfly-version/2.0.5.Final-SNAPSHOT/wildfly-version-2.0.5.Final-20151222.144931-1", path);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<String> fileToLines(String filename) {
List<String> lines = new LinkedList<String>();
String line = "";
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
while ((line = in.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
return lines;
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public List<String> fileToLines(String filename) {
List<String> lines = new LinkedList<String>();
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filename));
while ((line = in.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore ... any errors should already have been
// reported via an IOException from the final flush.
}
}
}
return lines;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static List<String> fileToLines(String filename) {
List<String> lines = new LinkedList<String>();
String line = "";
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
while ((line = in.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public static List<String> fileToLines(String filename) {
List<String> lines = new LinkedList<String>();
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filename));
while ((line = in.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore ... any errors should already have been
// reported via an IOException from the final flush.
}
}
}
return lines;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
Comparison.Detail controlDetails = comparison.getControlDetails();
Node controlTarget = controlDetails.getTarget();
Comparison.Detail testDetails = comparison.getTestDetails();
Node testTarget = testDetails.getTarget();
// comparing textual content of elements
if (comparison.getType() == ComparisonType.TEXT_VALUE) {
return evaluateConsideringPlaceholders((String) controlDetails.getValue(),
(String) testDetails.getValue(), outcome);
// two possible cases of "test document has no text-like node but control document has"
} else if (comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH &&
Integer.valueOf(1).equals(controlDetails.getValue()) &&
Integer.valueOf(0).equals(testDetails.getValue()) &&
isTextLikeNode(controlTarget.getFirstChild().getNodeType())) {
String controlNodeChildValue = controlTarget.getFirstChild().getNodeValue();
return evaluateConsideringPlaceholders(controlNodeChildValue, null, outcome);
} else if (comparison.getType() == ComparisonType.CHILD_LOOKUP && controlTarget != null &&
isTextLikeNode(controlTarget.getNodeType())) {
String controlNodeValue = controlTarget.getNodeValue();
return evaluateConsideringPlaceholders(controlNodeValue, null, outcome);
// may be comparing TEXT to CDATA
} else if (comparison.getType() == ComparisonType.NODE_TYPE
&& isTextLikeNode(controlTarget.getNodeType())
&& isTextLikeNode(testTarget.getNodeType())) {
return evaluateConsideringPlaceholders(controlTarget.getNodeValue(), testTarget.getNodeValue(), outcome);
// default, don't apply any placeholders at all
} else {
return outcome;
}
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) {
Comparison.Detail controlDetails = comparison.getControlDetails();
Node controlTarget = controlDetails.getTarget();
Comparison.Detail testDetails = comparison.getTestDetails();
Node testTarget = testDetails.getTarget();
// comparing textual content of elements
if (comparison.getType() == ComparisonType.TEXT_VALUE) {
return evaluateConsideringPlaceholders((String) controlDetails.getValue(),
(String) testDetails.getValue(), outcome);
// two versions of "test document has no text-like node but control document has"
} else if (comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH &&
Integer.valueOf(1).equals(controlDetails.getValue()) &&
Integer.valueOf(0).equals(testDetails.getValue()) &&
isTextLikeNode(controlTarget.getFirstChild().getNodeType())) {
String controlNodeChildValue = controlTarget.getFirstChild().getNodeValue();
return evaluateConsideringPlaceholders(controlNodeChildValue, null, outcome);
} else if (comparison.getType() == ComparisonType.CHILD_LOOKUP && controlTarget != null &&
isTextLikeNode(controlTarget.getNodeType())) {
String controlNodeValue = controlTarget.getNodeValue();
return evaluateConsideringPlaceholders(controlNodeValue, null, outcome);
// may be comparing TEXT to CDATA
} else if (comparison.getType() == ComparisonType.NODE_TYPE
&& isTextLikeNode(controlTarget.getNodeType())
&& isTextLikeNode(testTarget.getNodeType())) {
return evaluateConsideringPlaceholders(controlTarget.getNodeValue(), testTarget.getNodeValue(), outcome);
// comparing textual content of attributes
} else if (comparison.getType() == ComparisonType.ATTR_VALUE) {
return evaluateConsideringPlaceholders((String) controlDetails.getValue(),
(String) testDetails.getValue(), outcome);
// two versions of "test document has no attribute but control document has"
} else if (comparison.getType() == ComparisonType.ELEMENT_NUM_ATTRIBUTES) {
Map<QName, String> controlAttrs = Nodes.getAttributes(controlTarget);
Map<QName, String> testAttrs = Nodes.getAttributes(testTarget);
int cAttrsMatched = 0;
for (Map.Entry<QName, String> cAttr : controlAttrs.entrySet()) {
String testValue = testAttrs.get(cAttr.getKey());
if (testValue == null) {
ComparisonResult o = evaluateConsideringPlaceholders(cAttr.getValue(), null, outcome);
if (o != ComparisonResult.EQUAL) {
return outcome;
}
} else {
cAttrsMatched++;
}
}
if (cAttrsMatched != testAttrs.size()) {
// there are unmatched test attributes
return outcome;
}
return ComparisonResult.EQUAL;
} else if (comparison.getType() == ComparisonType.ATTR_NAME_LOOKUP && controlTarget != null
&& controlDetails.getValue() != null) {
String controlAttrValue = Nodes.getAttributes(controlTarget).get((QName) controlDetails.getValue());
return evaluateConsideringPlaceholders(controlAttrValue, null, outcome);
// default, don't apply any placeholders at all
} else {
return outcome;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public NodeAssert hasAttribute(String attributeName, String attributeValue) {
isNotNull();
final Map.Entry<QName, String> attribute = requestAttributeForName(attributeName);
if (!attribute.getValue().equals(attributeValue)) {
throwAssertionError(shouldHaveAttributeWithValue(actual, attributeName, attributeValue));
}
return this;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public NodeAssert hasAttribute(String attributeName, String attributeValue) {
isNotNull();
final Map.Entry<QName, String> attribute = attributeForName(attributeName);
if (attribute == null || !attribute.getValue().equals(attributeValue)) {
throwAssertionError(shouldHaveAttributeWithValue(actual.getNodeName(), attributeName, attributeValue));
}
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void configure(Map<String, ?> operand) {
super.configure(operand);
if (getRowType() == null) {
throw new IllegalStateException("Custom tables not yet supported for Kafka");
}
int epoch = (Integer) operand.get("epoch");
org.apache.avro.Schema avroSchema = (org.apache.avro.Schema) operand.get("avroSchema");
Pair<org.apache.avro.Schema, org.apache.avro.Schema> schemas = getKeyValueSchemas(avroSchema);
String id = getName() + "_" + epoch;
Map<String, Object> configs = new HashMap<>(operand);
configs.put(KafkaCacheConfig.KAFKACACHE_TOPIC_CONFIG, id);
configs.put(KafkaCacheConfig.KAFKACACHE_GROUP_ID_CONFIG, id);
configs.put(KafkaCacheConfig.KAFKACACHE_CLIENT_ID_CONFIG, id);
configs.put(KafkaCacheConfig.KAFKACACHE_ENABLE_OFFSET_COMMIT_CONFIG, true);
String enableRocksDbStr = (String) configs.getOrDefault(KarelDbConfig.ROCKS_DB_ENABLE_CONFIG, "true");
boolean enableRocksDb = Boolean.parseBoolean(enableRocksDbStr);
String rootDir = (String) configs.getOrDefault(
KarelDbConfig.ROCKS_DB_ROOT_DIR_CONFIG, KarelDbConfig.ROCKS_DB_ROOT_DIR_DEFAULT);
Comparator<byte[]> cmp = new AvroKeyComparator(schemas.left);
Cache<byte[], byte[]> cache = enableRocksDb
? new RocksDBCache<>(id, "rocksdb", rootDir, Serdes.ByteArray(), Serdes.ByteArray(), cmp)
: new InMemoryCache<>(cmp);
this.rows = new KafkaCache<>(
new KafkaCacheConfig(configs), Serdes.ByteArray(), Serdes.ByteArray(), null, cache);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void configure(Map<String, ?> operand) {
super.configure(operand);
if (getRowType() == null) {
throw new IllegalStateException("Custom tables not yet supported for Kafka");
}
Map<String, Object> configs = new HashMap<>(operand);
String groupId = (String) configs.getOrDefault(KafkaCacheConfig.KAFKACACHE_GROUP_ID_CONFIG, "kareldb-1");
int epoch = (Integer) configs.get("epoch");
org.apache.avro.Schema avroSchema = (org.apache.avro.Schema) configs.get("avroSchema");
Pair<org.apache.avro.Schema, org.apache.avro.Schema> schemas = getKeyValueSchemas(avroSchema);
String topic = getName() + "_" + epoch;
configs.put(KafkaCacheConfig.KAFKACACHE_TOPIC_CONFIG, topic);
configs.put(KafkaCacheConfig.KAFKACACHE_GROUP_ID_CONFIG, groupId);
configs.put(KafkaCacheConfig.KAFKACACHE_CLIENT_ID_CONFIG, groupId + "-" + topic);
configs.put(KafkaCacheConfig.KAFKACACHE_ENABLE_OFFSET_COMMIT_CONFIG, true);
String enableRocksDbStr = (String) configs.getOrDefault(KarelDbConfig.ROCKS_DB_ENABLE_CONFIG, "true");
boolean enableRocksDb = Boolean.parseBoolean(enableRocksDbStr);
String rootDir = (String) configs.getOrDefault(
KarelDbConfig.ROCKS_DB_ROOT_DIR_CONFIG, KarelDbConfig.ROCKS_DB_ROOT_DIR_DEFAULT);
Comparator<byte[]> cmp = new AvroKeyComparator(schemas.left);
Cache<byte[], byte[]> cache = enableRocksDb
? new RocksDBCache<>(topic, "rocksdb", rootDir, Serdes.ByteArray(), Serdes.ByteArray(), cmp)
: new InMemoryCache<>(cmp);
this.rows = new KafkaCache<>(
new KafkaCacheConfig(configs), Serdes.ByteArray(), Serdes.ByteArray(), null, cache);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void sendSecureMessage(
final AsyncWrite msg,
final SecurityToken token,
final int requestId,
final int messageType,
final AtomicInteger sendSequenceNumber
)
{
assert(token!=null);
ByteBuffer chunks[], plaintexts[];
boolean concurrent;
try {
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setQueued();
}
//Probably more efficient to check isTraceEnabled before executing ObjectUtils.printFieldsDeep
if (logger.isTraceEnabled())
logger.trace("sendSecureMessage: " + ObjectUtils.printFieldsDeep(msg.getMessage()));
EncoderCalc calc = new EncoderCalc();
calc.setEncoderContext(encoderCtx);
calc.putMessage(msg.getMessage());
int len = calc.getLength();
if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
SecurityPolicy policy = token.getSecurityPolicy();
MessageSecurityMode mode = token.getMessageSecurityMode();
SecurityAlgorithm symmEncryptAlgo = policy.getSymmetricEncryptionAlgorithm();
SecurityAlgorithm symmSignAlgo = policy.getSymmetricSignatureAlgorithm();
int cipherBlockSize = CryptoUtil.getCipherBlockSize(symmEncryptAlgo, null);
int signatureSize = CryptoUtil.getSignatureSize(symmSignAlgo, null);
int keySize = mode == MessageSecurityMode.SignAndEncrypt ? token.getRemoteEncryptingKey().length : 0;
int paddingSize = mode == MessageSecurityMode.SignAndEncrypt ? keySize > 2048 ? 2 : 1 : 0;
int maxPlaintextSize = ctx.maxSendChunkSize - 24 - paddingSize - signatureSize;
maxPlaintextSize -= (maxPlaintextSize + paddingSize + signatureSize + 8) % cipherBlockSize;
final int CORES = StackUtils.cores();
int optimalPayloadSize = (len+CORES-1) / CORES;
if (optimalPayloadSize > maxPlaintextSize)
optimalPayloadSize = maxPlaintextSize;
if (optimalPayloadSize < 4096)
optimalPayloadSize = 4096;
int optimalChunkSize = optimalPayloadSize + 24 + paddingSize + signatureSize;
ChunkFactory cf = new ChunkFactory(
optimalChunkSize,
8,
8,
8,
signatureSize,
cipherBlockSize,
mode,
keySize);
// Calculate chunk count
final int count = (len + cf.maxPlaintextSize-1) / cf.maxPlaintextSize;
if (count>ctx.maxSendChunkCount && ctx.maxSendChunkCount!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
concurrent = (count > 1) && (CORES>0) && (mode != MessageSecurityMode.None);
// Allocate chunks
int bytesLeft = len;
plaintexts = new ByteBuffer[count];
chunks = new ByteBuffer[count];
for (int i=0; i<count; i++) {
plaintexts[i] = cf.allocate(bytesLeft);
chunks[i] = cf.expandToCompleteChunk(plaintexts[i]);
bytesLeft -= plaintexts[i].remaining();
}
assert(bytesLeft==0);
// Start write
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setWriting();
}
} catch (ServiceResultException se) {
msg.setError(se);
return;
}
final ByteBuffer _chunks[] = chunks;
final ByteBuffer _plaintexts[] = plaintexts;
final int count = chunks.length;
final boolean parallel = concurrent;
int sequenceNumber = 0;
synchronized(this) {
sequenceNumber = sendSequenceNumber.getAndAdd(chunks.length);
startChunkSend(chunks);
}
// Add chunk headers
for (ByteBuffer chunk : chunks) {
boolean finalChunk = chunk == chunks[chunks.length-1];
chunk.rewind();
chunk.putInt( messageType | (finalChunk ? TcpMessageType.FINAL : TcpMessageType.CONTINUE) );
chunk.position(8);
chunk.putInt(token.getSecureChannelId());
// -- Security Header --
chunk.putInt(token.getTokenId());
// -- Sequence Header --
chunk.putInt(sequenceNumber++);
chunk.putInt(requestId);
}
// a Chunk-has-been-encoded handler
final AtomicInteger chunksComplete = new AtomicInteger();
ChunkListener completitionListener = new ChunkListener() {
@Override
public void onChunkComplete(ByteBuffer[] bufs, final int index) {
Runnable action = new Runnable() {
@Override
public void run() {
// Chunk contains message data, it needs to be encrypted and signed
// try {
// Encrypt & sign
new ChunkSymmEncryptSigner(_chunks[index], _plaintexts[index], token).run();
_chunks[index].rewind();
// Write chunk
endChunkSend(_chunks[index]);
// All chunks are completed
if (chunksComplete.incrementAndGet()==count)
msg.setWritten();
// } catch (ServiceResultException se) {
// msg.setError(se);
// }
}};
if (parallel && count>1) {
StackUtils.getNonBlockingWorkExecutor().execute(action);
} else {
action.run();
}
}
};
// Create encoder
ByteBufferArrayWriteable2 out = new ByteBufferArrayWriteable2(plaintexts, completitionListener);
out.order(ByteOrder.LITTLE_ENDIAN);
final BinaryEncoder enc = new BinaryEncoder(out);
enc.setEncoderContext(encoderCtx);
enc.setEncoderMode(EncoderMode.NonStrict);
Runnable encoder = new Runnable() {
@Override
public void run() {
try {
enc.putMessage(msg.getMessage());
} catch (ServiceResultException e) {
msg.setError( StackUtils.toServiceResultException(e) );
}
}};
StackUtils.getBlockingWorkExecutor().execute(encoder);
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
protected void sendSecureMessage(
final AsyncWrite msg,
final SecurityToken token,
final int requestId,
final int messageType,
final AtomicInteger sendSequenceNumber
)
{
assert(token!=null);
ByteBuffer chunks[], plaintexts[];
boolean concurrent;
try {
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setQueued();
}
//Probably more efficient to check isTraceEnabled before executing ObjectUtils.printFieldsDeep
if (logger.isTraceEnabled())
logger.trace("sendSecureMessage: " + ObjectUtils.printFieldsDeep(msg.getMessage()));
EncoderCalc calc = new EncoderCalc();
calc.setEncoderContext(encoderCtx);
calc.putMessage(msg.getMessage());
int len = calc.getLength();
if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
SecurityPolicy policy = token.getSecurityPolicy();
MessageSecurityMode mode = token.getMessageSecurityMode();
SecurityAlgorithm symmEncryptAlgo = policy.getSymmetricEncryptionAlgorithm();
SecurityAlgorithm symmSignAlgo = policy.getSymmetricSignatureAlgorithm();
int cipherBlockSize = CryptoUtil.getCipherBlockSize(symmEncryptAlgo, null);
int signatureSize = CryptoUtil.getSignatureSize(symmSignAlgo, null);
int keySize = mode == MessageSecurityMode.SignAndEncrypt ? token.getRemoteEncryptingKey().length : 0;
int paddingSize = mode == MessageSecurityMode.SignAndEncrypt ? keySize > 2048 ? 2 : 1 : 0;
int maxPlaintextSize = ctx.maxSendChunkSize - 24 - paddingSize - signatureSize;
maxPlaintextSize -= (maxPlaintextSize + paddingSize + signatureSize + 8) % cipherBlockSize;
final int CORES = StackUtils.cores();
int optimalPayloadSize = (len+CORES-1) / CORES;
if (optimalPayloadSize > maxPlaintextSize)
optimalPayloadSize = maxPlaintextSize;
if (optimalPayloadSize < 4096)
optimalPayloadSize = 4096;
int optimalChunkSize = optimalPayloadSize + 24 + paddingSize + signatureSize;
ChunkFactory cf = new ChunkFactory(
optimalChunkSize,
8,
8,
8,
signatureSize,
cipherBlockSize,
mode,
keySize);
// Calculate chunk count
final int count = (len + cf.maxPlaintextSize-1) / cf.maxPlaintextSize;
if (count>ctx.maxSendChunkCount && ctx.maxSendChunkCount!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
concurrent = (count > 1) && (CORES>0) && (mode != MessageSecurityMode.None);
// Allocate chunks
int bytesLeft = len;
plaintexts = new ByteBuffer[count];
chunks = new ByteBuffer[count];
for (int i=0; i<count; i++) {
plaintexts[i] = cf.allocate(bytesLeft);
chunks[i] = cf.expandToCompleteChunk(plaintexts[i]);
bytesLeft -= plaintexts[i].remaining();
}
assert(bytesLeft==0);
// Start write
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setWriting();
}
} catch (ServiceResultException se) {
msg.setError(se);
return;
}
final ByteBuffer _chunks[] = chunks;
final ByteBuffer _plaintexts[] = plaintexts;
final int count = chunks.length;
final boolean parallel = concurrent;
int sequenceNumber = 0;
synchronized(this) {
sequenceNumber = sendSequenceNumber.getAndAdd(chunks.length);
startChunkSend(chunks);
}
// Add chunk headers
for (ByteBuffer chunk : chunks) {
boolean finalChunk = chunk == chunks[chunks.length-1];
chunk.rewind();
chunk.putInt( messageType | (finalChunk ? TcpMessageType.FINAL : TcpMessageType.CONTINUE) );
chunk.position(8);
chunk.putInt(token.getSecureChannelId());
// -- Security Header --
chunk.putInt(token.getTokenId());
// -- Sequence Header --
chunk.putInt(sequenceNumber++);
chunk.putInt(requestId);
}
// a Chunk-has-been-encoded handler
final AtomicInteger chunksComplete = new AtomicInteger();
ChunkListener completitionListener = new ChunkListener() {
@Override
public void onChunkComplete(ByteBuffer[] bufs, final int index) {
Runnable action = new Runnable() {
@Override
public void run() {
// Chunk contains message data, it needs to be encrypted and signed
// try {
// Encrypt & sign
new ChunkSymmEncryptSigner(_chunks[index], _plaintexts[index], token).run();
_chunks[index].rewind();
// Write chunk
endChunkSend(_chunks[index]);
// All chunks are completed
if (chunksComplete.incrementAndGet()==count)
msg.setWritten();
// } catch (ServiceResultException se) {
// msg.setError(se);
// }
}};
if (parallel && count>1) {
StackUtils.getNonBlockingWorkExecutor().execute(action);
} else {
action.run();
}
}
};
// Create encoder
ByteBufferArrayWriteable2 out = new ByteBufferArrayWriteable2(plaintexts, completitionListener);
out.order(ByteOrder.LITTLE_ENDIAN);
final BinaryEncoder enc = new BinaryEncoder(out);
enc.setEncoderContext(encoderCtx);
Runnable encoder = new Runnable() {
@Override
public void run() {
try {
enc.putMessage(msg.getMessage());
} catch (ServiceResultException e) {
msg.setError( StackUtils.toServiceResultException(e) );
}
}};
StackUtils.getBlockingWorkExecutor().execute(encoder);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ExtensionObject binaryEncode(Structure encodeable, IEncodeableSerializer serializer, EncoderContext ctx)
throws EncodingException {
ctx.setEncodeableSerializer(serializer);
int limit = ctx.getMaxByteStringLength();
if(limit == 0) {
limit = ctx.getMaxMessageSize();
}
if(limit == 0) {
limit = Integer.MAX_VALUE;
}
LimitedByteArrayOutputStream stream = LimitedByteArrayOutputStream.withSizeLimit(limit);
BinaryEncoder enc = new BinaryEncoder(stream);
enc.setEncoderContext(ctx);
enc.putEncodeable(null, encodeable);
return new ExtensionObject(encodeable.getBinaryEncodeId(), stream.toByteArray());
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public static ExtensionObject binaryEncode(Structure encodeable, IEncodeableSerializer serializer, EncoderContext ctx)
throws EncodingException {
ctx.setEncodeableSerializer(serializer);
int limit = ctx.getMaxByteStringLength();
if(limit == 0) {
limit = ctx.getMaxMessageSize();
}
if(limit == 0) {
limit = Integer.MAX_VALUE;
}
LimitedByteArrayOutputStream buf = LimitedByteArrayOutputStream.withSizeLimit(limit);
BinaryEncoder enc = new BinaryEncoder(buf);
enc.setEncoderContext(ctx);
enc.putEncodeable(null, encodeable);
return new ExtensionObject(encodeable.getBinaryEncodeId(), buf.toByteArray());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void putDecimal(String fieldName, BigDecimal bd) throws EncodingException{
int scaleInt = bd.scale();
if(scaleInt > Short.MAX_VALUE) {
throw new EncodingException("Decimal scale overflow Short max value: "+scaleInt);
}
if(scaleInt < Short.MIN_VALUE) {
throw new EncodingException("Decimal scale underflow Short min value: "+scaleInt);
}
short scale = (short)scaleInt;
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putShort(scale);
byte[] scalebytes = bb.array();
//NOTE BigInteger uses big-endian, and UA Decimal encoding uses little-endian
byte[] valuebytes = EncoderUtils.reverse(bd.unscaledValue().toByteArray());
byte[] combined = EncoderUtils.concat(scalebytes, valuebytes);
ExpandedNodeId id = new ExpandedNodeId(NamespaceTable.OPCUA_NAMESPACE, Identifiers.Decimal.getValue());
ExtensionObject eo = new ExtensionObject(id, combined);
putExtensionObject(fieldName, eo);
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
private void putDecimal(String fieldName, BigDecimal bd) throws EncodingException{
ExtensionObject eo = EncoderUtils.decimalToExtensionObject(bd);
putExtensionObject(fieldName, eo);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void sendResponse(int statusCode, IEncodeable responseObject)
{
try {
HttpResponse responseHandle = httpExchange.getResponse();
responseHandle.setHeader("Content-Type", "application/octet-stream");
responseHandle.setStatusCode( statusCode );
if ( responseObject != null ) {
try {
logger.trace("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject);
logger.debug("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject.getClass().getSimpleName());
//Check isDebugEnabled() here for possible performance reasons.
if (logger.isDebugEnabled() && channel.getConnection() != null) {
NHttpServerConnection nHttpServerConnection = ((HttpsServerConnection) channel.getConnection()).getNHttpServerConnection();
logger.debug("sendResponse: timeout={} {} context={}", httpExchange.getTimeout(), nHttpServerConnection.getSocketTimeout(), nHttpServerConnection.getContext());
}
SizeCalculationOutputStream tmp = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(tmp);
calc.setEncoderContext( endpoint.getEncoderContext() );
calc.putMessage( responseObject );
int len = tmp.getLength();
byte[] data = new byte[ len ];
BinaryEncoder enc = new BinaryEncoder( data );
enc.setEncoderContext( endpoint.getEncoderContext() );
enc.putMessage( responseObject );
responseHandle.setEntity( new NByteArrayEntity(data) );
} catch (EncodingException e) {
logger.info("sendResponse: Encoding failed", e);
// Internal Error
if ( responseObject instanceof ErrorMessage == false ) {
responseHandle.setStatusCode( 500 );
}
}
}
logger.debug("sendResponse: {} length={}", responseHandle, responseHandle.getEntity().getContentLength());
httpExchange.submitResponse(new BasicAsyncResponseProducer(responseHandle));
} finally {
endpoint.pendingRequests.remove(requestId);
}
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
void sendResponse(int statusCode, IEncodeable responseObject)
{
try {
HttpResponse responseHandle = httpExchange.getResponse();
responseHandle.setHeader("Content-Type", "application/octet-stream");
responseHandle.setStatusCode( statusCode );
if ( responseObject != null ) {
try {
logger.trace("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject);
logger.debug("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject.getClass().getSimpleName());
//Check isDebugEnabled() here for possible performance reasons.
if (logger.isDebugEnabled() && channel.getConnection() != null) {
NHttpServerConnection nHttpServerConnection = ((HttpsServerConnection) channel.getConnection()).getNHttpServerConnection();
logger.debug("sendResponse: timeout={} {} context={}", httpExchange.getTimeout(), nHttpServerConnection.getSocketTimeout(), nHttpServerConnection.getContext());
}
ByteArrayOutputStream data = new ByteArrayOutputStream();
BinaryEncoder enc = new BinaryEncoder( data );
enc.setEncoderContext( endpoint.getEncoderContext() );
enc.putMessage( responseObject );
responseHandle.setEntity( new NByteArrayEntity(data.toByteArray()) );
} catch (EncodingException e) {
logger.info("sendResponse: Encoding failed", e);
// Internal Error
if ( responseObject instanceof ErrorMessage == false ) {
responseHandle.setStatusCode( 500 );
}
}
}
logger.debug("sendResponse: {} length={}", responseHandle, responseHandle.getEntity().getContentLength());
httpExchange.submitResponse(new BasicAsyncResponseProducer(responseHandle));
} finally {
endpoint.pendingRequests.remove(requestId);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getSecurityProviderName() {
if (securityProviderName == null) {
Provider provider = null;
if (LOGGER.isDebugEnabled())
LOGGER.debug("Providers={}",
Arrays.toString(Security.getProviders()));
boolean isAndroid = System.getProperty("java.runtime.name")
.toLowerCase().contains("android");
if (isAndroid) {
if (Security.getProvider("SC") != null)
securityProviderName = "SC";
else {
provider = hasClass("org.spongycastle.jce.provider.BouncyCastleProvider");
if (provider != null)
securityProviderName = "SC";
}
} else if (Security.getProvider("BC") != null)
securityProviderName = "BC";
else {
if (provider == null) {
provider = hasClass("org.bouncycastle.jce.provider.BouncyCastleProvider");
if (provider != null)
securityProviderName = "BC";
}
if (provider == null) {
provider = hasClass("com.sun.crypto.provider.SunJCE");
if (provider != null)
{
throw new RuntimeException("BouncyCastle Security Provider not available! Not recommended SunJCE Security Provider is found, use it with CryptoUtil.setSecurityProviderName.");
}
}
if (provider != null)
securityProviderName = provider.getName();
}
if (securityProviderName != null)
LOGGER.info("Using SecurityProvider {}", securityProviderName);
else
throw new RuntimeException("NO SECURITY PROVIDER AVAILABLE!");
}
return securityProviderName;
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getSecurityProviderName() {
if (securityProviderName == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Providers={}",
Arrays.toString(Security.getProviders()));
}
boolean isAndroid = System.getProperty("java.vendor")
.toLowerCase().contains("android");
if (isAndroid) {
securityProviderName = "SC";
} else{
securityProviderName = "BC";
}
}
return securityProviderName;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void sendRequest(ServiceRequest request, int secureChannelId, int requestId) throws ServiceResultException {
if (request == null)
logger.warn("sendRequest: request=null");
boolean asymm = request instanceof OpenSecureChannelRequest;
final Socket s = getSocket();
logger.debug("sendRequest: socket={}", s);
try {
if (s == null || !s.isConnected() || s.isClosed()) {
throw new ServiceResultException(Bad_ServerNotConnected);
}
logger.debug("sendRequest: {} Sending Request rid:{}", secureChannelId, requestId);
logger.trace("sendrequest: request={}", request);
SecurityToken token = null;
// Count message size
SizeCalculationOutputStream tmp = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(tmp);
calc.setEncoderContext(ctx);
calc.putMessage(request);
int len = tmp.getLength();
if (secureChannelId != 0) {
token = getSecurityTokenToUse(secureChannelId);
}
logger.debug("sendRequest: token={}", token);
SecurityMode securityMode = getSecurityMode(asymm, request, token);
int keySize = token != null ? token.getSecurityPolicy().getEncryptionKeySize() : 0;
logger.debug("sendRequest: keySize={}", keySize);
// Lock output stream, but getChunkFactory must also be guarded
// with lock
// as the connection may otherwise be disposed in between
ChunkFactory cf = getChunkFactory(asymm, securityMode, keySize);
if (cf != null) {
MessageBuffers buffers = encodeMessage(cf, len, request);
if (buffers != null) {
ByteBuffer[] chunks = buffers.getChunks();
ByteBuffer[] plaintexts = buffers.getPlaintexts();
if ((chunks != null) & (plaintexts != null)) {
try {
lock.lock();
try {
if (asymm) {
// Capture ClientNonce of the request
// message
ByteString clientNonce = ((OpenSecureChannelRequest) request).getClientNonce();
clientNonces.put(requestId, clientNonce);
//
for (int i = 0; i < chunks.length; i++) {
boolean finalChunk = i == chunks.length - 1;
sendAsymmChunk(secureChannelId, requestId, securityMode, chunks[i], plaintexts[i], finalChunk);
plaintexts[i] = null;
chunks[i] = null;
}
} else {
activeTokenIdMap.put(secureChannelId, token);
SequenceNumber seq = sequenceNumbers.get(secureChannelId);
// Add chunk headers
for (int i = 0; i < chunks.length; i++) {
ByteBuffer chunk = chunks[i];
final ByteBuffer plaintext = plaintexts[i];
boolean finalChunk = chunk == chunks[chunks.length - 1];
int msgType = TcpMessageType.MSGC;
if(finalChunk) msgType = TcpMessageType.MSGF;
if(request instanceof CloseSecureChannelRequest)
msgType = TcpMessageType.CLOSE | TcpMessageType.FINAL;
sendSymmChunk(requestId, token, seq, chunk, plaintext, msgType);
plaintexts[i] = null;
chunks[i] = null;
}
}
out.flush();
} catch (IOException e) {
clientNonces.remove(requestId);
logger.info(addr + " Connect failed", e);
close();
throw new ServiceResultException(Bad_CommunicationError, e);
}
} finally {
lock.unlock();
}
}
}
}
} catch (RuntimeException e) {
logger.warn(
String.format(
"sendRequest %s failed: socket=%s, asymm=%s",
request.getClass().getName(), s, asymm), e);
throw e;
}
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public void sendRequest(ServiceRequest request, int secureChannelId, int requestId) throws ServiceResultException {
if (request == null)
logger.warn("sendRequest: request=null");
boolean asymm = request instanceof OpenSecureChannelRequest;
final Socket s = getSocket();
logger.debug("sendRequest: socket={}", s);
try {
if (s == null || !s.isConnected() || s.isClosed()) {
throw new ServiceResultException(Bad_ServerNotConnected);
}
logger.debug("sendRequest: {} Sending Request rid:{}", secureChannelId, requestId);
logger.trace("sendrequest: request={}", request);
SecurityToken token = null;
// Count message size
SizeCalculationOutputStream calcBuf = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(calcBuf);
calc.setEncoderContext(ctx);
calc.putMessage(request);
int len = calcBuf.getLength();
if (secureChannelId != 0) {
token = getSecurityTokenToUse(secureChannelId);
}
logger.debug("sendRequest: token={}", token);
SecurityMode securityMode = getSecurityMode(asymm, request, token);
int keySize = token != null ? token.getSecurityPolicy().getEncryptionKeySize() : 0;
logger.debug("sendRequest: keySize={}", keySize);
// Lock output stream, but getChunkFactory must also be guarded
// with lock
// as the connection may otherwise be disposed in between
ChunkFactory cf = getChunkFactory(asymm, securityMode, keySize);
if (cf != null) {
MessageBuffers buffers = encodeMessage(cf, len, request);
if (buffers != null) {
ByteBuffer[] chunks = buffers.getChunks();
ByteBuffer[] plaintexts = buffers.getPlaintexts();
if ((chunks != null) & (plaintexts != null)) {
try {
lock.lock();
try {
if (asymm) {
// Capture ClientNonce of the request
// message
ByteString clientNonce = ((OpenSecureChannelRequest) request).getClientNonce();
clientNonces.put(requestId, clientNonce);
//
for (int i = 0; i < chunks.length; i++) {
boolean finalChunk = i == chunks.length - 1;
sendAsymmChunk(secureChannelId, requestId, securityMode, chunks[i], plaintexts[i], finalChunk);
plaintexts[i] = null;
chunks[i] = null;
}
} else {
activeTokenIdMap.put(secureChannelId, token);
SequenceNumber seq = sequenceNumbers.get(secureChannelId);
// Add chunk headers
for (int i = 0; i < chunks.length; i++) {
ByteBuffer chunk = chunks[i];
final ByteBuffer plaintext = plaintexts[i];
boolean finalChunk = chunk == chunks[chunks.length - 1];
int msgType = TcpMessageType.MSGC;
if(finalChunk) msgType = TcpMessageType.MSGF;
if(request instanceof CloseSecureChannelRequest)
msgType = TcpMessageType.CLOSE | TcpMessageType.FINAL;
sendSymmChunk(requestId, token, seq, chunk, plaintext, msgType);
plaintexts[i] = null;
chunks[i] = null;
}
}
out.flush();
} catch (IOException e) {
clientNonces.remove(requestId);
logger.info(addr + " Connect failed", e);
close();
throw new ServiceResultException(Bad_CommunicationError, e);
}
} finally {
lock.unlock();
}
}
}
}
} catch (RuntimeException e) {
logger.warn(
String.format(
"sendRequest %s failed: socket=%s, asymm=%s",
request.getClass().getName(), s, asymm), e);
throw e;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void sendSecureMessage(
final AsyncWrite msg,
final SecurityToken token,
final int requestId,
final int messageType,
final AtomicInteger sendSequenceNumber
)
{
assert(token!=null);
ByteBuffer chunks[], plaintexts[];
boolean concurrent;
try {
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setQueued();
}
//Probably more efficient to check isTraceEnabled before executing ObjectUtils.printFieldsDeep
if (logger.isTraceEnabled())
logger.trace("sendSecureMessage: " + ObjectUtils.printFieldsDeep(msg.getMessage()));
SizeCalculationOutputStream tmp = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(tmp);
calc.setEncoderContext(encoderCtx);
calc.putMessage(msg.getMessage());
int len = tmp.getLength();
if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
SecurityPolicy policy = token.getSecurityPolicy();
MessageSecurityMode mode = token.getMessageSecurityMode();
SecurityAlgorithm symmEncryptAlgo = policy.getSymmetricEncryptionAlgorithm();
SecurityAlgorithm symmSignAlgo = policy.getSymmetricSignatureAlgorithm();
int cipherBlockSize = CryptoUtil.getCipherBlockSize(symmEncryptAlgo, null);
int signatureSize = CryptoUtil.getSignatureSize(symmSignAlgo, null);
int keySize = mode == MessageSecurityMode.SignAndEncrypt ? token.getRemoteEncryptingKey().length : 0;
int paddingSize = mode == MessageSecurityMode.SignAndEncrypt ? keySize > 2048 ? 2 : 1 : 0;
int maxPlaintextSize = ctx.maxSendChunkSize - 24 - paddingSize - signatureSize;
maxPlaintextSize -= (maxPlaintextSize + paddingSize + signatureSize + 8) % cipherBlockSize;
final int CORES = StackUtils.cores();
int optimalPayloadSize = (len+CORES-1) / CORES;
if (optimalPayloadSize > maxPlaintextSize)
optimalPayloadSize = maxPlaintextSize;
if (optimalPayloadSize < 4096)
optimalPayloadSize = 4096;
int optimalChunkSize = optimalPayloadSize + 24 + paddingSize + signatureSize;
ChunkFactory cf = new ChunkFactory(
optimalChunkSize,
8,
8,
8,
signatureSize,
cipherBlockSize,
mode,
keySize);
// Calculate chunk count
final int count = (len + cf.maxPlaintextSize-1) / cf.maxPlaintextSize;
if (count>ctx.maxSendChunkCount && ctx.maxSendChunkCount!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
concurrent = (count > 1) && (CORES>0) && (mode != MessageSecurityMode.None);
// Allocate chunks
int bytesLeft = len;
plaintexts = new ByteBuffer[count];
chunks = new ByteBuffer[count];
for (int i=0; i<count; i++) {
plaintexts[i] = cf.allocate(bytesLeft);
chunks[i] = cf.expandToCompleteChunk(plaintexts[i]);
bytesLeft -= plaintexts[i].remaining();
}
assert(bytesLeft==0);
// Start write
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setWriting();
}
} catch (ServiceResultException se) {
msg.setError(se);
return;
}
final ByteBuffer _chunks[] = chunks;
final ByteBuffer _plaintexts[] = plaintexts;
final int count = chunks.length;
final boolean parallel = concurrent;
int sequenceNumber = 0;
synchronized(this) {
sequenceNumber = sendSequenceNumber.getAndAdd(chunks.length);
startChunkSend(chunks);
}
// Add chunk headers
for (ByteBuffer chunk : chunks) {
boolean finalChunk = chunk == chunks[chunks.length-1];
chunk.rewind();
chunk.putInt( messageType | (finalChunk ? TcpMessageType.FINAL : TcpMessageType.CONTINUE) );
chunk.position(8);
chunk.putInt(token.getSecureChannelId());
// -- Security Header --
chunk.putInt(token.getTokenId());
// -- Sequence Header --
chunk.putInt(sequenceNumber++);
chunk.putInt(requestId);
}
// a Chunk-has-been-encoded handler
final AtomicInteger chunksComplete = new AtomicInteger();
ChunkListener completitionListener = new ChunkListener() {
@Override
public void onChunkComplete(ByteBuffer[] bufs, final int index) {
Runnable action = new Runnable() {
@Override
public void run() {
// Chunk contains message data, it needs to be encrypted and signed
// try {
// Encrypt & sign
new ChunkSymmEncryptSigner(_chunks[index], _plaintexts[index], token).run();
_chunks[index].rewind();
// Write chunk
endChunkSend(_chunks[index]);
// All chunks are completed
if (chunksComplete.incrementAndGet()==count)
msg.setWritten();
// } catch (ServiceResultException se) {
// msg.setError(se);
// }
}};
if (parallel && count>1) {
StackUtils.getNonBlockingWorkExecutor().execute(action);
} else {
action.run();
}
}
};
// Create encoder
ByteBufferArrayWriteable2 out = new ByteBufferArrayWriteable2(plaintexts, completitionListener);
out.order(ByteOrder.LITTLE_ENDIAN);
final BinaryEncoder enc = new BinaryEncoder(out);
enc.setEncoderContext(encoderCtx);
Runnable encoder = new Runnable() {
@Override
public void run() {
try {
enc.putMessage(msg.getMessage());
} catch (ServiceResultException e) {
msg.setError( StackUtils.toServiceResultException(e) );
}
}};
StackUtils.getBlockingWorkExecutor().execute(encoder);
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void sendSecureMessage(
final AsyncWrite msg,
final SecurityToken token,
final int requestId,
final int messageType,
final AtomicInteger sendSequenceNumber
)
{
assert(token!=null);
ByteBuffer chunks[], plaintexts[];
boolean concurrent;
try {
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setQueued();
}
//Probably more efficient to check isTraceEnabled before executing ObjectUtils.printFieldsDeep
if (logger.isTraceEnabled())
logger.trace("sendSecureMessage: " + ObjectUtils.printFieldsDeep(msg.getMessage()));
SizeCalculationOutputStream calcBuf = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(calcBuf);
calc.setEncoderContext(encoderCtx);
calc.putMessage(msg.getMessage());
int len = calcBuf.getLength();
if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
SecurityPolicy policy = token.getSecurityPolicy();
MessageSecurityMode mode = token.getMessageSecurityMode();
SecurityAlgorithm symmEncryptAlgo = policy.getSymmetricEncryptionAlgorithm();
SecurityAlgorithm symmSignAlgo = policy.getSymmetricSignatureAlgorithm();
int cipherBlockSize = CryptoUtil.getCipherBlockSize(symmEncryptAlgo, null);
int signatureSize = CryptoUtil.getSignatureSize(symmSignAlgo, null);
int keySize = mode == MessageSecurityMode.SignAndEncrypt ? token.getRemoteEncryptingKey().length : 0;
int paddingSize = mode == MessageSecurityMode.SignAndEncrypt ? keySize > 2048 ? 2 : 1 : 0;
int maxPlaintextSize = ctx.maxSendChunkSize - 24 - paddingSize - signatureSize;
maxPlaintextSize -= (maxPlaintextSize + paddingSize + signatureSize + 8) % cipherBlockSize;
final int CORES = StackUtils.cores();
int optimalPayloadSize = (len+CORES-1) / CORES;
if (optimalPayloadSize > maxPlaintextSize)
optimalPayloadSize = maxPlaintextSize;
if (optimalPayloadSize < 4096)
optimalPayloadSize = 4096;
int optimalChunkSize = optimalPayloadSize + 24 + paddingSize + signatureSize;
ChunkFactory cf = new ChunkFactory(
optimalChunkSize,
8,
8,
8,
signatureSize,
cipherBlockSize,
mode,
keySize);
// Calculate chunk count
final int count = (len + cf.maxPlaintextSize-1) / cf.maxPlaintextSize;
if (count>ctx.maxSendChunkCount && ctx.maxSendChunkCount!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
concurrent = (count > 1) && (CORES>0) && (mode != MessageSecurityMode.None);
// Allocate chunks
int bytesLeft = len;
plaintexts = new ByteBuffer[count];
chunks = new ByteBuffer[count];
for (int i=0; i<count; i++) {
plaintexts[i] = cf.allocate(bytesLeft);
chunks[i] = cf.expandToCompleteChunk(plaintexts[i]);
bytesLeft -= plaintexts[i].remaining();
}
assert(bytesLeft==0);
// Start write
synchronized(msg) {
if (msg.isCanceled()) return;
msg.setWriting();
}
} catch (ServiceResultException se) {
msg.setError(se);
return;
}
final ByteBuffer _chunks[] = chunks;
final ByteBuffer _plaintexts[] = plaintexts;
final int count = chunks.length;
final boolean parallel = concurrent;
int sequenceNumber = 0;
synchronized(this) {
sequenceNumber = sendSequenceNumber.getAndAdd(chunks.length);
startChunkSend(chunks);
}
// Add chunk headers
for (ByteBuffer chunk : chunks) {
boolean finalChunk = chunk == chunks[chunks.length-1];
chunk.rewind();
chunk.putInt( messageType | (finalChunk ? TcpMessageType.FINAL : TcpMessageType.CONTINUE) );
chunk.position(8);
chunk.putInt(token.getSecureChannelId());
// -- Security Header --
chunk.putInt(token.getTokenId());
// -- Sequence Header --
chunk.putInt(sequenceNumber++);
chunk.putInt(requestId);
}
// a Chunk-has-been-encoded handler
final AtomicInteger chunksComplete = new AtomicInteger();
ChunkListener completitionListener = new ChunkListener() {
@Override
public void onChunkComplete(ByteBuffer[] bufs, final int index) {
Runnable action = new Runnable() {
@Override
public void run() {
// Chunk contains message data, it needs to be encrypted and signed
// try {
// Encrypt & sign
new ChunkSymmEncryptSigner(_chunks[index], _plaintexts[index], token).run();
_chunks[index].rewind();
// Write chunk
endChunkSend(_chunks[index]);
// All chunks are completed
if (chunksComplete.incrementAndGet()==count)
msg.setWritten();
// } catch (ServiceResultException se) {
// msg.setError(se);
// }
}};
if (parallel && count>1) {
StackUtils.getNonBlockingWorkExecutor().execute(action);
} else {
action.run();
}
}
};
// Create encoder
ByteBufferArrayWriteable2 out = new ByteBufferArrayWriteable2(plaintexts, completitionListener);
out.order(ByteOrder.LITTLE_ENDIAN);
final BinaryEncoder enc = new BinaryEncoder(out);
enc.setEncoderContext(encoderCtx);
Runnable encoder = new Runnable() {
@Override
public void run() {
try {
enc.putMessage(msg.getMessage());
} catch (ServiceResultException e) {
msg.setError( StackUtils.toServiceResultException(e) );
}
}};
StackUtils.getBlockingWorkExecutor().execute(encoder);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void run() {
try {
// Abort exit branch
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode ) );
return;
}
// Http Post
InetSocketAddress inetAddress = UriUtil.getSocketAddress( httpsClient.connectUrl );
String host = inetAddress.getHostName();
int port = inetAddress.getPort();
String scheme = UriUtil.getTransportProtocol( httpsClient.connectUrl );
HttpHost httpHost = new HttpHost(host, port, scheme);
String url = httpsClient.transportChannelSettings.getDescription().getEndpointUrl();
String endpointId = url == null ? "" : url; //UriUtil.getEndpointName(url);
httpPost = new HttpPost( endpointId );
httpPost.addHeader("OPCUA-SecurityPolicy", httpsClient.securityPolicyUri);
httpPost.addHeader("Content-Type", "application/octet-stream");
// Calculate message length
SizeCalculationOutputStream tmp = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(tmp);
calc.setEncoderContext( httpsClient.encoderCtx );
calc.putMessage( requestMessage );
int len = tmp.getLength();
// Assert max size is not exceeded
int maxLen = httpsClient.encoderCtx.getMaxMessageSize();
if ( maxLen != 0 && len > maxLen ) {
final EncodingException encodingException = new EncodingException(StatusCodes.Bad_EncodingLimitsExceeded, "MaxStringLength "+maxLen+" < "+len);
logger.warn("run: failed", encodingException);
throw encodingException;
}
// Encode message
byte[] data = new byte[ len ];
BinaryEncoder enc = new BinaryEncoder( data );
enc.setEncoderContext( httpsClient.encoderCtx );
enc.putMessage( requestMessage );
httpPost.setEntity( new NByteArrayEntity(data) );
// Abort exit branch
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode ) );
return;
}
// Execute Post
HttpResponse httpResponse;
try {
httpResponse = httpsClient.httpclient.execute( httpHost, httpPost );
} catch (SSLPeerUnverifiedException e) {
// Currently, TLS_1_2 is not supported by JSSE implementations, for some odd reason
// and it will give this exception when used.
// Also, if the server certificate is rejected, we will get this error
result.setError( new ServiceResultException(StatusCodes.Bad_SecurityPolicyRejected, e,
"Could not negotiate a TLS security cipher or the server did not provide a valid certificate."));
return;
}
HttpEntity entity = httpResponse.getEntity();
// Error response
int statusCode = httpResponse.getStatusLine().getStatusCode();
if ( statusCode != 200 ) {
UnsignedInteger uacode = StatusCodes.Bad_UnknownResponse;
if ( statusCode == 501 ) uacode = StatusCodes.Bad_ServiceUnsupported;
String msg = EntityUtils.toString( entity );
result.setError( new ServiceResultException( uacode, statusCode+": "+msg ) );
return;
}
// Abort exit branch
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode ) );
return;
}
// Decode Message
data = EntityUtils.toByteArray(entity);
BinaryDecoder dec = new BinaryDecoder( data );
dec.setEncoderContext( httpsClient.encoderCtx );
IEncodeable response = dec.getMessage();
// Client sent an error
if ( response instanceof ErrorMessage ) {
ErrorMessage error = (ErrorMessage) response;
ServiceResultException errorResult = new ServiceResultException(new StatusCode(error.getError()), error.getReason());
result.setError(errorResult);
return;
}
try {
// Client sent a valid message
result.setResult((ServiceResponse) response);
} catch (ClassCastException e) {
result.setError(new ServiceResultException(e));
logger.error(
"Cannot cast response to ServiceResponse, response="
+ response.getClass(), e);
}
} catch (EncodingException e) {
// Internal Error
result.setError( new ServiceResultException( StatusCodes.Bad_EncodingError, e ) );
} catch (ClientProtocolException e) {
result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e) );
} catch (IOException e) {
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode, e ) );
} else {
result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e ) );
}
} catch (DecodingException e) {
result.setError( new ServiceResultException( StatusCodes.Bad_DecodingError, e ) );
} catch (ServiceResultException e) {
result.setError( e );
} catch (RuntimeException rte) {
// http-client seems to be throwing these, IllegalArgumentException for one
result.setError( new ServiceResultException( rte ) );
} catch(StackOverflowError e){
// Payloads of high nesting levels may cause stack overflow. Structure, VariantArray and DiagnosticInfo at least may cause this.
// JVM setting -Xss influences possible level of nesting. At least 100 levels of nesting must be supported, this should not be a problem with normal thread stack sizes.
// Inform receiving side that error has happened.
result.setError(new ServiceResultException(StatusCodes.Bad_DecodingError, "Stack overflow: " + Arrays.toString(Arrays.copyOf(e.getStackTrace(), 30)) + "..."));
} finally {
httpsClient.requests.remove( requestId );
}
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void run() {
try {
// Abort exit branch
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode ) );
return;
}
// Http Post
InetSocketAddress inetAddress = UriUtil.getSocketAddress( httpsClient.connectUrl );
String host = inetAddress.getHostName();
int port = inetAddress.getPort();
String scheme = UriUtil.getTransportProtocol( httpsClient.connectUrl );
HttpHost httpHost = new HttpHost(host, port, scheme);
String url = httpsClient.transportChannelSettings.getDescription().getEndpointUrl();
String endpointId = url == null ? "" : url; //UriUtil.getEndpointName(url);
httpPost = new HttpPost( endpointId );
httpPost.addHeader("OPCUA-SecurityPolicy", httpsClient.securityPolicyUri);
httpPost.addHeader("Content-Type", "application/octet-stream");
// Calculate message length
SizeCalculationOutputStream calcBuf = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(calcBuf);
calc.setEncoderContext( httpsClient.encoderCtx );
calc.putMessage( requestMessage );
int len = calcBuf.getLength();
// Assert max size is not exceeded
int maxLen = httpsClient.encoderCtx.getMaxMessageSize();
if ( maxLen != 0 && len > maxLen ) {
final EncodingException encodingException = new EncodingException(StatusCodes.Bad_EncodingLimitsExceeded, "MaxStringLength "+maxLen+" < "+len);
logger.warn("run: failed", encodingException);
throw encodingException;
}
// Encode message
byte[] data = new byte[ len ];
BinaryEncoder enc = new BinaryEncoder( data );
enc.setEncoderContext( httpsClient.encoderCtx );
enc.putMessage( requestMessage );
httpPost.setEntity( new NByteArrayEntity(data) );
// Abort exit branch
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode ) );
return;
}
// Execute Post
HttpResponse httpResponse;
try {
httpResponse = httpsClient.httpclient.execute( httpHost, httpPost );
} catch (SSLPeerUnverifiedException e) {
// Currently, TLS_1_2 is not supported by JSSE implementations, for some odd reason
// and it will give this exception when used.
// Also, if the server certificate is rejected, we will get this error
result.setError( new ServiceResultException(StatusCodes.Bad_SecurityPolicyRejected, e,
"Could not negotiate a TLS security cipher or the server did not provide a valid certificate."));
return;
}
HttpEntity entity = httpResponse.getEntity();
// Error response
int statusCode = httpResponse.getStatusLine().getStatusCode();
if ( statusCode != 200 ) {
UnsignedInteger uacode = StatusCodes.Bad_UnknownResponse;
if ( statusCode == 501 ) uacode = StatusCodes.Bad_ServiceUnsupported;
String msg = EntityUtils.toString( entity );
result.setError( new ServiceResultException( uacode, statusCode+": "+msg ) );
return;
}
// Abort exit branch
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode ) );
return;
}
// Decode Message
data = EntityUtils.toByteArray(entity);
BinaryDecoder dec = new BinaryDecoder( data );
dec.setEncoderContext( httpsClient.encoderCtx );
IEncodeable response = dec.getMessage();
// Client sent an error
if ( response instanceof ErrorMessage ) {
ErrorMessage error = (ErrorMessage) response;
ServiceResultException errorResult = new ServiceResultException(new StatusCode(error.getError()), error.getReason());
result.setError(errorResult);
return;
}
try {
// Client sent a valid message
result.setResult((ServiceResponse) response);
} catch (ClassCastException e) {
result.setError(new ServiceResultException(e));
logger.error(
"Cannot cast response to ServiceResponse, response="
+ response.getClass(), e);
}
} catch (EncodingException e) {
// Internal Error
result.setError( new ServiceResultException( StatusCodes.Bad_EncodingError, e ) );
} catch (ClientProtocolException e) {
result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e) );
} catch (IOException e) {
if ( abortCode != null ) {
result.setError( new ServiceResultException( abortCode, e ) );
} else {
result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e ) );
}
} catch (DecodingException e) {
result.setError( new ServiceResultException( StatusCodes.Bad_DecodingError, e ) );
} catch (ServiceResultException e) {
result.setError( e );
} catch (RuntimeException rte) {
// http-client seems to be throwing these, IllegalArgumentException for one
result.setError( new ServiceResultException( rte ) );
} catch(StackOverflowError e){
// Payloads of high nesting levels may cause stack overflow. Structure, VariantArray and DiagnosticInfo at least may cause this.
// JVM setting -Xss influences possible level of nesting. At least 100 levels of nesting must be supported, this should not be a problem with normal thread stack sizes.
// Inform receiving side that error has happened.
result.setError(new ServiceResultException(StatusCodes.Bad_DecodingError, "Stack overflow: " + Arrays.toString(Arrays.copyOf(e.getStackTrace(), 30)) + "..."));
} finally {
httpsClient.requests.remove( requestId );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public ByteBuffer[] call() throws RuntimeServiceResultException {
try {
SizeCalculationOutputStream tmp = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(tmp);
calc.setEncoderContext(encoderCtx);
if (type == MessageType.Encodeable)
calc.putEncodeable(null, msg);
else
calc.putMessage(msg);
int len = tmp.getLength();
if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
ByteQueue bq = new ByteQueue();
bq.order(ByteOrder.LITTLE_ENDIAN);
bq.setWriteLimit(len);
bq.setByteBufferFactory(chunkFactory);
bq.setChunkSize(chunkFactory.maxPlaintextSize);
ByteBufferArrayWriteable array = new ByteBufferArrayWriteable(bq);
array.order(ByteOrder.LITTLE_ENDIAN);
BinaryEncoder enc = new BinaryEncoder(array);
enc.setEncoderContext(encoderCtx);
if (type == MessageType.Message)
enc.putMessage(msg);
else
enc.putEncodeable(null, msg);
ByteBuffer[] plaintexts = bq.getChunks(len);
if (plaintexts.length>ctx.maxRecvChunkCount && ctx.maxRecvChunkCount!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
return plaintexts;
} catch (ServiceResultException e) {
throw new RuntimeServiceResultException(e);
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public ByteBuffer[] call() throws RuntimeServiceResultException {
try {
SizeCalculationOutputStream calcBuf = new SizeCalculationOutputStream();
BinaryEncoder calc = new BinaryEncoder(calcBuf);
calc.setEncoderContext(encoderCtx);
if (type == MessageType.Encodeable)
calc.putEncodeable(null, msg);
else
calc.putMessage(msg);
int len = calcBuf.getLength();
if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
ByteQueue bq = new ByteQueue();
bq.order(ByteOrder.LITTLE_ENDIAN);
bq.setWriteLimit(len);
bq.setByteBufferFactory(chunkFactory);
bq.setChunkSize(chunkFactory.maxPlaintextSize);
ByteBufferArrayWriteable array = new ByteBufferArrayWriteable(bq);
array.order(ByteOrder.LITTLE_ENDIAN);
BinaryEncoder enc = new BinaryEncoder(array);
enc.setEncoderContext(encoderCtx);
if (type == MessageType.Message)
enc.putMessage(msg);
else
enc.putEncodeable(null, msg);
ByteBuffer[] plaintexts = bq.getChunks(len);
if (plaintexts.length>ctx.maxRecvChunkCount && ctx.maxRecvChunkCount!=0)
throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge);
return plaintexts;
} catch (ServiceResultException e) {
throw new RuntimeServiceResultException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void putDecimal(String fieldName, BigDecimal bd) throws EncodingException{
int scaleInt = bd.scale();
if(scaleInt > Short.MAX_VALUE) {
throw new EncodingException("Decimal scale overflow Short max value: "+scaleInt);
}
if(scaleInt < Short.MIN_VALUE) {
throw new EncodingException("Decimal scale underflow Short min value: "+scaleInt);
}
short scale = (short)scaleInt;
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putShort(scale);
bb.rewind();
byte[] scalebytes = bb.array();
//NOTE BigInteger uses big-endian, and UA Decimal encoding uses little-endian
byte[] valuebytes = EncoderUtils.reverse(bd.unscaledValue().toByteArray());
byte[] combined = EncoderUtils.concat(scalebytes, valuebytes);
ExpandedNodeId id = new ExpandedNodeId(NamespaceTable.OPCUA_NAMESPACE, Identifiers.Decimal.getValue());
ExtensionObject eo = new ExtensionObject(id, combined);
putExtensionObject(fieldName, eo);
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
private void putDecimal(String fieldName, BigDecimal bd) throws EncodingException{
ExtensionObject eo = EncoderUtils.decimalToExtensionObject(bd);
putExtensionObject(fieldName, eo);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void onStructureGrow(StructureGrowEvent event) {
Location location = event.getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
TreeTable treeTable = gw.getTableManager().getTreeTable();
if (treeTable.getLocationMap().containsKey(location)) {
Long uuid = treeTable.getLocationMap().get(location);
Tree tree = treeTable.getTreeMap().get(uuid);
UUID ownerUUID = tree.getOwner().getUuid();
GPlayer planter = gw.getTableManager().getPlayerTable().getPlayers().get(ownerUUID);
Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks());
int carbonScore = planter.getCarbonScore();
planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue()));
tree.setSapling(false);
// TODO: Queue tree DB update
// TODO: Queue planter score DB update
// TODO: Queue new reduction DB insert
} else {
gw.getLogger().severe("Untracked structure grow occured:");
gw.getLogger().severe("@ " + location.toString());
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void onStructureGrow(StructureGrowEvent event) {
Location location = event.getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
TreeTable treeTable = gw.getTableManager().getTreeTable();
GPlayer planter;
// TODO: Add TreeType species to reduction model
if (treeTable.getLocationMap().containsKey(location)) {
Tree tree = treeTable.getTreeMap().get(treeTable.getLocationMap().get(location));
planter = tree.getOwner();
Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks());
int carbonScore = planter.getCarbonScore();
planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue()));
tree.setSapling(false);
tree.setSize(event.getBlocks().size()); // TODO: Only consider core species blocks as tree size
// Queue tree update query
TreeUpdateQuery treeUpdateQuery = new TreeUpdateQuery(tree);
AsyncDBQueue.getInstance().queueUpdateQuery(treeUpdateQuery);
} else {
PlayerTable playerTable = GlobalWarming.getInstance().getTableManager().getPlayerTable();
planter = playerTable.getOrCreatePlayer(untrackedUUID, true);
// First create a new tree object and store it
Long uniqueId = GlobalWarming.getInstance().getRandom().nextLong();
// TODO: Only consider core species blocks as tree size
Tree tree = new Tree(uniqueId, planter, location, false, event.getBlocks().size());
TreeInsertQuery insertQuery = new TreeInsertQuery(tree);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
gw.getLogger().warning("Untracked structure grow occured:");
gw.getLogger().warning("@ " + location.toString());
}
// Create a new reduction object using the worlds climate engine
Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks());
int carbonScore = planter.getCarbonScore();
planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue()));
// Queue player update query
PlayerUpdateQuery playerUpdateQuery = new PlayerUpdateQuery(planter);
AsyncDBQueue.getInstance().queueUpdateQuery(playerUpdateQuery);
// Queue reduction insert query
ReductionInsertQuery insertQuery = new ReductionInsertQuery(reduction);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void blockFormEvent(BlockFormEvent event) {
if (event.getBlock().getType() == Material.SNOW) {
double temp = ClimateEngine.getInstance().getClimateEngine(event.getBlock().getWorld().getName()).getTemperature();
if (event.getBlock().getY() < MapUtil.searchTreeMap(heightMap, temp)) {
event.setCancelled(true);
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void blockFormEvent(BlockFormEvent event) {
if (event.getNewState().getType() == Material.ICE) {
double temp = ClimateEngine.getInstance().getClimateEngine(event.getBlock().getWorld().getName()).getTemperature();
if (event.getBlock().getY() < heightMap.getValue(temp)) {
event.setCancelled(true);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void onFurnaceSmelt(FurnaceBurnEvent event) {
Location location = event.getBlock().getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
FurnaceTable furnaceTable = gw.getTableManager().getFurnaceTable();
if (furnaceTable.getLocationMap().containsKey(location)) {
Long uuid = furnaceTable.getLocationMap().get(location);
Furnace furnace = furnaceTable.getFurnaceMap().get(uuid);
// Note: We hold the owner of the furnace responsible for emissions
// If the furnace isn't protected, the furnace owner is still charged
GPlayer polluter = gw.getTableManager().getPlayerTable().getPlayers().get(furnace.getOwner().getUuid());
Contribution emissions = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).furnaceBurn(polluter, event.getFuel());
int carbonScore = polluter.getCarbonScore();
polluter.setCarbonScore((int) (carbonScore + emissions.getContributionValue()));
// TODO: Queue polluter score DB update
// TODO: Queue new contribution DB insert
} else {
gw.getLogger().severe(event.getFuel().getType().name() + " burned as fuel in an untracked furnace!");
gw.getLogger().severe("@ " + location.toString());
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void onFurnaceSmelt(FurnaceBurnEvent event) {
Location location = event.getBlock().getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
FurnaceTable furnaceTable = gw.getTableManager().getFurnaceTable();
GPlayer polluter;
if (furnaceTable.getLocationMap().containsKey(location)) {
Furnace furnace = furnaceTable.getFurnaceMap().get(furnaceTable.getLocationMap().get(location));
polluter = furnace.getOwner(); // whoever placed the furnace is charged.
} else {
/*
* This might happen if a player has a redstone hopper setup that feeds untracked furnaces
* In this case, just consider it to be untracked emissions.
*/
PlayerTable playerTable = GlobalWarming.getInstance().getTableManager().getPlayerTable();
polluter = playerTable.getOrCreatePlayer(untrackedUUID, true);
// First create a new furnace object and store it
Long uniqueId = GlobalWarming.getInstance().getRandom().nextLong();
Furnace furnace = new Furnace(uniqueId, polluter, location, true);
// Update all furnace collections
furnaceTable.updateFurnace(furnace);
// Create a new furnace insert query and queue it
FurnaceInsertQuery insertQuery = new FurnaceInsertQuery(furnace);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
gw.getLogger().warning(event.getFuel().getType().name() + " burned as fuel in an untracked furnace!");
gw.getLogger().warning("@ " + location.toString());
}
// Create a contribution object using this worlds climate engine
Contribution contrib = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).furnaceBurn(polluter, event.getFuel());
int carbonScore = polluter.getCarbonScore();
polluter.setCarbonScore((int) (carbonScore + contrib.getContributionValue()));
// Queue an update to the player table
PlayerUpdateQuery updateQuery = new PlayerUpdateQuery(polluter);
AsyncDBQueue.getInstance().queueUpdateQuery(updateQuery);
// Queue an insert into the contributions table
ContributionInsertQuery insertQuery = new ContributionInsertQuery(contrib);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void onStructureGrow(StructureGrowEvent event) {
Location location = event.getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
TreeTable treeTable = gw.getTableManager().getTreeTable();
if (treeTable.getLocationMap().containsKey(location)) {
Long uuid = treeTable.getLocationMap().get(location);
Tree tree = treeTable.getTreeMap().get(uuid);
UUID ownerUUID = tree.getOwner().getUuid();
GPlayer planter = gw.getTableManager().getPlayerTable().getPlayers().get(ownerUUID);
Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks());
int carbonScore = planter.getCarbonScore();
planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue()));
tree.setSapling(false);
// TODO: Queue tree DB update
// TODO: Queue planter score DB update
// TODO: Queue new reduction DB insert
} else {
gw.getLogger().severe("Untracked structure grow occured:");
gw.getLogger().severe("@ " + location.toString());
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void onStructureGrow(StructureGrowEvent event) {
Location location = event.getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
TreeTable treeTable = gw.getTableManager().getTreeTable();
GPlayer planter;
// TODO: Add TreeType species to reduction model
if (treeTable.getLocationMap().containsKey(location)) {
Tree tree = treeTable.getTreeMap().get(treeTable.getLocationMap().get(location));
planter = tree.getOwner();
Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks());
int carbonScore = planter.getCarbonScore();
planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue()));
tree.setSapling(false);
tree.setSize(event.getBlocks().size()); // TODO: Only consider core species blocks as tree size
// Queue tree update query
TreeUpdateQuery treeUpdateQuery = new TreeUpdateQuery(tree);
AsyncDBQueue.getInstance().queueUpdateQuery(treeUpdateQuery);
} else {
PlayerTable playerTable = GlobalWarming.getInstance().getTableManager().getPlayerTable();
planter = playerTable.getOrCreatePlayer(untrackedUUID, true);
// First create a new tree object and store it
Long uniqueId = GlobalWarming.getInstance().getRandom().nextLong();
// TODO: Only consider core species blocks as tree size
Tree tree = new Tree(uniqueId, planter, location, false, event.getBlocks().size());
TreeInsertQuery insertQuery = new TreeInsertQuery(tree);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
gw.getLogger().warning("Untracked structure grow occured:");
gw.getLogger().warning("@ " + location.toString());
}
// Create a new reduction object using the worlds climate engine
Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks());
int carbonScore = planter.getCarbonScore();
planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue()));
// Queue player update query
PlayerUpdateQuery playerUpdateQuery = new PlayerUpdateQuery(planter);
AsyncDBQueue.getInstance().queueUpdateQuery(playerUpdateQuery);
// Queue reduction insert query
ReductionInsertQuery insertQuery = new ReductionInsertQuery(reduction);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void loadKeys() {
sensitivity = CarbonSensitivity.LOW;
String carbonSensitivity = conf.getString("carbonSensitivity");
if (carbonSensitivity != null && !carbonSensitivity.isEmpty()) {
try {
sensitivity = CarbonSensitivity.valueOf(carbonSensitivity);
} catch (Exception e) {
GlobalWarming.getInstance().getLogger().warning(
String.format(
"Unknown carbon sensitivity for: [%s], defaulting to [%s]",
getDisplayName(worldId),
sensitivity));
}
}
this.enabled = this.conf.getBoolean("enabled");
this.associatedWorldId = Bukkit.getWorld(this.conf.getString("association")).getUID();
this.enabledEffects = new HashSet<>();
this.blastFurnaceMultiplier = this.conf.getDouble("blastFurnaceMultiplier", 1.2);
this.methaneTicksLivedModifier = this.conf.getDouble("methaneTicksLivedModifier", 0.01);
this.bonemealReductionAllowed = this.conf.getBoolean("bonemealReductionAllowed", true);
this.bonemealReductionModifier = this.conf.getDouble("bonemealReductionModifier", 0.5);
for (String effect : this.conf.getStringList("enabledEffects")) {
try {
this.enabledEffects.add(ClimateEffectType.valueOf(effect));
} catch (IllegalArgumentException ex) {
GlobalWarming.getInstance().getLogger().severe(String.format(
"Could not load effect: [%s] for world: [%s]",
effect,
getDisplayName(worldId)));
}
}
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void loadKeys() {
sensitivity = CarbonSensitivity.LOW;
String carbonSensitivity = conf.getString("carbonSensitivity");
if (carbonSensitivity != null && !carbonSensitivity.isEmpty()) {
try {
sensitivity = CarbonSensitivity.valueOf(carbonSensitivity);
} catch (Exception e) {
GlobalWarming.getInstance().getLogger().warning(
String.format(
"Unknown carbon sensitivity for: [%s], defaulting to [%s]",
getDisplayName(worldId),
sensitivity));
}
}
this.enabled = this.conf.getBoolean("enabled");
this.associatedWorldId = Bukkit.getWorld(this.conf.getString("association")).getUID();
this.enabledEffects = new HashSet<>();
this.methaneTicksLivedModifier = this.conf.getDouble("methaneTicksLivedModifier", 0.01);
this.bonemealReductionAllowed = this.conf.getBoolean("bonemealReductionAllowed", true);
this.bonemealReductionModifier = this.conf.getDouble("bonemealReductionModifier", 0.5);
for (String effect : this.conf.getStringList("enabledEffects")) {
try {
this.enabledEffects.add(ClimateEffectType.valueOf(effect));
} catch (IllegalArgumentException ex) {
GlobalWarming.getInstance().getLogger().severe(String.format(
"Could not load effect: [%s] for world: [%s]",
effect,
getDisplayName(worldId)));
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void blockFormEvent(BlockFormEvent event) {
if (event.getBlock().getType() == Material.ICE) {
double temp = ClimateEngine.getInstance().getClimateEngine(event.getBlock().getWorld().getName()).getTemperature();
if (event.getBlock().getY() < MapUtil.searchTreeMap(heightMap, temp)) {
event.setCancelled(true);
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void blockFormEvent(BlockFormEvent event) {
if (event.getNewState().getType() == Material.SNOW) {
double temp = ClimateEngine.getInstance().getClimateEngine(event.getBlock().getWorld().getName()).getTemperature();
if (event.getBlock().getY() < heightMap.getValue(temp)) {
event.setCancelled(true);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateGlobalScores() {
for (World world : Bukkit.getWorlds()) {
//Do not update worlds with disabled climate-engines:
WorldClimateEngine climateEngine = ClimateEngine.getInstance().getClimateEngine(world.getUID());
if (climateEngine != null && climateEngine.isEnabled()) {
//Get the scoreboard for this world:
Scoreboard scoreboard = getScoreboard(world.getUID(), false);
//Get its objective (scoreboard title / group):
Objective objective = null;
if (scoreboard != null) {
objective = scoreboard.getObjective(GLOBAL_WARMING);
}
//Update the title to show this world's temperature:
if (objective != null) {
double temperature = climateEngine.getTemperature();
String format = GlobalWarming.getInstance().getConf().getTemperatureFormat();
DecimalFormat decimalFormat = new DecimalFormat(format);
objective.setDisplayName(String.format(
Lang.SCORE_TEMPERATURE.get(),
GeneralCommands.getTemperatureColor(temperature),
decimalFormat.format(temperature)));
}
}
}
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateGlobalScores() {
for (World world : Bukkit.getWorlds()) {
//Do not update worlds with disabled climate-engines:
WorldClimateEngine climateEngine = ClimateEngine.getInstance().getClimateEngine(world.getUID());
if (climateEngine != null && climateEngine.isEnabled()) {
//Get the scoreboard for this world:
Scoreboard scoreboard = getScoreboard(world.getUID(), false);
//Get its objective (scoreboard title / group):
Objective objective = null;
if (scoreboard != null) {
objective = scoreboard.getObjective(GLOBAL_WARMING);
}
//Update the title to show this world's temperature:
if (objective != null) {
double temperature = climateEngine.getTemperature();
objective.setDisplayName(String.format(
Lang.SCORE_TEMPERATURE.get(),
Colorizer.getTemperatureColor(temperature),
climateEngine.formatTemp(temperature)));
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler
public void onFurnaceSmelt(FurnaceBurnEvent event) {
Location location = event.getBlock().getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
FurnaceTable furnaceTable = gw.getTableManager().getFurnaceTable();
if (furnaceTable.getLocationMap().containsKey(location)) {
Long uuid = furnaceTable.getLocationMap().get(location);
Furnace furnace = furnaceTable.getFurnaceMap().get(uuid);
// Note: We hold the owner of the furnace responsible for emissions
// If the furnace isn't protected, the furnace owner is still charged
GPlayer polluter = gw.getTableManager().getPlayerTable().getPlayers().get(furnace.getOwner().getUuid());
Contribution emissions = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).furnaceBurn(polluter, event.getFuel());
int carbonScore = polluter.getCarbonScore();
polluter.setCarbonScore((int) (carbonScore + emissions.getContributionValue()));
// TODO: Queue polluter score DB update
// TODO: Queue new contribution DB insert
} else {
gw.getLogger().severe(event.getFuel().getType().name() + " burned as fuel in an untracked furnace!");
gw.getLogger().severe("@ " + location.toString());
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler
public void onFurnaceSmelt(FurnaceBurnEvent event) {
Location location = event.getBlock().getLocation();
GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName());
FurnaceTable furnaceTable = gw.getTableManager().getFurnaceTable();
GPlayer polluter;
if (furnaceTable.getLocationMap().containsKey(location)) {
Furnace furnace = furnaceTable.getFurnaceMap().get(furnaceTable.getLocationMap().get(location));
polluter = furnace.getOwner(); // whoever placed the furnace is charged.
} else {
/*
* This might happen if a player has a redstone hopper setup that feeds untracked furnaces
* In this case, just consider it to be untracked emissions.
*/
PlayerTable playerTable = GlobalWarming.getInstance().getTableManager().getPlayerTable();
polluter = playerTable.getOrCreatePlayer(untrackedUUID, true);
// First create a new furnace object and store it
Long uniqueId = GlobalWarming.getInstance().getRandom().nextLong();
Furnace furnace = new Furnace(uniqueId, polluter, location, true);
// Update all furnace collections
furnaceTable.updateFurnace(furnace);
// Create a new furnace insert query and queue it
FurnaceInsertQuery insertQuery = new FurnaceInsertQuery(furnace);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
gw.getLogger().warning(event.getFuel().getType().name() + " burned as fuel in an untracked furnace!");
gw.getLogger().warning("@ " + location.toString());
}
// Create a contribution object using this worlds climate engine
Contribution contrib = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).furnaceBurn(polluter, event.getFuel());
int carbonScore = polluter.getCarbonScore();
polluter.setCarbonScore((int) (carbonScore + contrib.getContributionValue()));
// Queue an update to the player table
PlayerUpdateQuery updateQuery = new PlayerUpdateQuery(polluter);
AsyncDBQueue.getInstance().queueUpdateQuery(updateQuery);
// Queue an insert into the contributions table
ContributionInsertQuery insertQuery = new ContributionInsertQuery(contrib);
AsyncDBQueue.getInstance().queueInsertQuery(insertQuery);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
OutputStream createSortedOutputStream() {
try {
return new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sortedFile)));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
OutputStream createUnsortedOutputStream() {
try {
return new BufferedOutputStream(new FileOutputStream(unsortedFile));
} catch (IOException e) {
throw new RuntimeException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
OutputStream createUnsortedOutputStream() {
try {
return new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(unsortedFile)));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
OutputStream createUnsortedOutputStream() {
try {
return new BufferedOutputStream(new FileOutputStream(unsortedFile));
} catch (IOException e) {
throw new RuntimeException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void verify() {
idAndVersionFactory = createIdAndVersionFactory();
ElasticSearchIdAndVersionStream elasticSearchIdAndVersionStream = createElasticSearchIdAndVersionStream(options);
JdbcIdAndVersionStream jdbcIdAndVersionStream = createJdbcIdAndVersionStream(options);
verify(elasticSearchIdAndVersionStream, jdbcIdAndVersionStream, new IdAndVersionStreamVerifier());
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public void verify() {
Function<Long, Object> formatter = createFormatter();
IdAndVersionStreamVerifierListener verifierListener = createVerifierListener(formatter);
this.verify(verifierListener);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
InputStream createUnSortedInputStream() {
try {
return new ObjectInputStream(new BufferedInputStream(new FileInputStream(unsortedFile)));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
OutputStream createUnsortedOutputStream() {
try {
return new BufferedOutputStream(new FileOutputStream(unsortedFile));
} catch (IOException e) {
throw new RuntimeException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void parseDomainTopologyYaml() {
ConfigMapHelper.DomainTopology domainTopology =
ConfigMapHelper.parseDomainTopologyYaml(DOMAIN_TOPOLOGY);
assertNotNull(domainTopology);
assertTrue(domainTopology.getDomainValid());
WlsDomainConfig wlsDomainConfig = domainTopology.getDomain();
assertNotNull(wlsDomainConfig);
assertEquals("base_domain", wlsDomainConfig.getName());
assertEquals("admin-server", wlsDomainConfig.getAdminServerName());
Map<String, WlsClusterConfig> wlsClusterConfigs = wlsDomainConfig.getClusterConfigs();
assertEquals(1, wlsClusterConfigs.size());
WlsClusterConfig wlsClusterConfig = wlsClusterConfigs.get("cluster-1");
assertNotNull(wlsClusterConfig);
List<WlsServerConfig> wlsServerConfigs = wlsClusterConfig.getServers();
assertEquals(2, wlsServerConfigs.size());
Map<String, WlsServerConfig> serverConfigMap = wlsDomainConfig.getServerConfigs();
assertEquals(3, serverConfigMap.size());
assertTrue(serverConfigMap.containsKey("admin-server"));
assertTrue(serverConfigMap.containsKey("server1"));
assertTrue(serverConfigMap.containsKey("server2"));
WlsServerConfig server2Config = serverConfigMap.get("server2");
assertEquals("domain1-managed-server2", server2Config.getListenAddress());
assertEquals(9004, server2Config.getListenPort().intValue());
assertEquals(8004, server2Config.getSslListenPort().intValue());
assertFalse(server2Config.isSslPortEnabled());
List<NetworkAccessPoint> server2ConfigNAPs = server2Config.getNetworkAccessPoints();
assertEquals(1, server2ConfigNAPs.size());
NetworkAccessPoint server2ConfigNAP = server2ConfigNAPs.get(0);
assertEquals("nap2", server2ConfigNAP.getName());
assertEquals("t3", server2ConfigNAP.getProtocol());
assertEquals(8005, server2ConfigNAP.getListenPort().intValue());
assertEquals(8005, server2ConfigNAP.getPublicPort().intValue());
}
#location 32
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void parseDomainTopologyYaml() {
ConfigMapHelper.DomainTopology domainTopology =
ConfigMapHelper.parseDomainTopologyYaml(DOMAIN_TOPOLOGY);
assertNotNull(domainTopology);
assertTrue(domainTopology.getDomainValid());
WlsDomainConfig wlsDomainConfig = domainTopology.getDomain();
assertNotNull(wlsDomainConfig);
assertEquals("base_domain", wlsDomainConfig.getName());
assertEquals("admin-server", wlsDomainConfig.getAdminServerName());
Map<String, WlsClusterConfig> wlsClusterConfigs = wlsDomainConfig.getClusterConfigs();
assertEquals(1, wlsClusterConfigs.size());
WlsClusterConfig wlsClusterConfig = wlsClusterConfigs.get("cluster-1");
assertNotNull(wlsClusterConfig);
List<WlsServerConfig> wlsServerConfigs = wlsClusterConfig.getServers();
assertEquals(2, wlsServerConfigs.size());
Map<String, WlsServerConfig> serverConfigMap = wlsDomainConfig.getServerConfigs();
assertEquals(3, serverConfigMap.size());
assertTrue(serverConfigMap.containsKey("admin-server"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCustomResourceWatch() {
Assume.assumeTrue(System.getProperty("os.name").toLowerCase().contains("nix"));
ClientHolder client = ClientHelper.getInstance().take();
try {
// create a watch
Watch<Domain> watch = Watch.createWatch(
client.getApiClient(),
client.getWeblogicApiClient().listWebLogicOracleV1DomainForAllNamespacesCall(null,
null,
null,
null,
5,
null,
null,
60,
Boolean.TRUE,
null,
null),
new TypeToken<Watch.Response<Domain>>() {
}.getType());
for (Watch.Response<Domain> item : watch) {
System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName());
}
} catch (ApiException e) {
if (e.getCode() == 404) {
System.out.println("***\n***This test is not able to run because the CRD that I want to watch does not exist on the server\n***");
} else {
fail();
}
} catch (RuntimeException e) {
System.out.println("stream finished");
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCustomResourceWatch() throws Exception {
Assume.assumeTrue(TestUtils.isKubernetesAvailable());
ClientHolder client = ClientHelper.getInstance().take();
Watch<Domain> watch = Watch.createWatch(
client.getApiClient(),
client.getWeblogicApiClient().listWebLogicOracleV1DomainForAllNamespacesCall(null,
null,
null,
null,
5,
null,
null,
60,
Boolean.TRUE,
null,
null),
new TypeToken<Watch.Response<Domain>>() {
}.getType());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void serverStartupInfo_containsEnvironmentVariable() {
configureServer("ms1")
.withEnvironmentVariable("item1", "value1")
.withEnvironmentVariable("item2", "value2");
addWlsServer("ms1");
invokeStep();
assertThat(
getServerStartupInfo("ms1").getEnvironment(),
containsInAnyOrder(envVar("item1", "value1"), envVar("item2", "value2")));
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void serverStartupInfo_containsEnvironmentVariable() {
configureServer("wls1")
.withEnvironmentVariable("item1", "value1")
.withEnvironmentVariable("item2", "value2");
addWlsServer("wls1");
invokeStep();
assertThat(
getServerStartupInfo("wls1").getEnvironment(),
containsInAnyOrder(envVar("item1", "value1"), envVar("item2", "value2")));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void run() {
// Clear the interrupted status, if present
Thread.interrupted();
final Fiber oldFiber = CURRENT_FIBER.get();
CURRENT_FIBER.set(this);
Container oldContainer = ContainerResolver.getDefault().enterContainer(owner.getContainer());
try {
// doRun returns true to indicate an early exit from fiber processing
if (!doRun(next)) {
completionCheck();
}
// Trigger exitCallback
synchronized (this) {
if (exitCallback != null && exitCallback != PLACEHOLDER) {
if (LOGGER.isFineEnabled()) {
LOGGER.fine("{0} invoking exit callback", new Object[] { getName() });
}
exitCallback.onExit();
}
exitCallback = PLACEHOLDER;
}
} finally {
ContainerResolver.getDefault().exitContainer(oldContainer);
CURRENT_FIBER.set(oldFiber);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void run() {
if (status.get() == NOT_COMPLETE) {
// Clear the interrupted status, if present
Thread.interrupted();
final Fiber oldFiber = CURRENT_FIBER.get();
CURRENT_FIBER.set(this);
Container oldContainer = ContainerResolver.getDefault().enterContainer(owner.getContainer());
try {
// doRun returns true to indicate an early exit from fiber processing
if (!doRun(next)) {
completionCheck();
}
} finally {
ContainerResolver.getDefault().exitContainer(oldContainer);
CURRENT_FIBER.set(oldFiber);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void whenDomainReadFromYaml_unconfiguredServerHasDomainDefaults() throws IOException {
Domain domain = readDomain(DOMAIN_V2_SAMPLE_YAML);
ServerSpec serverSpec = domain.getServer("server0", null);
assertThat(serverSpec.getImage(), equalTo(DEFAULT_IMAGE));
assertThat(serverSpec.getImagePullPolicy(), equalTo(IFNOTPRESENT_IMAGEPULLPOLICY));
assertThat(serverSpec.getImagePullSecret().getName(), equalTo("pull-secret"));
assertThat(serverSpec.getEnvironmentVariables(), empty());
assertThat(serverSpec.getNodePort(), nullValue());
assertThat(serverSpec.getDesiredState(), equalTo("RUNNING"));
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void whenDomainReadFromYaml_unconfiguredServerHasDomainDefaults() throws IOException {
Domain domain = readDomain(DOMAIN_V2_SAMPLE_YAML);
ServerSpec serverSpec = domain.getServer("server0", null);
assertThat(serverSpec.getImage(), equalTo(DEFAULT_IMAGE));
assertThat(serverSpec.getImagePullPolicy(), equalTo(IFNOTPRESENT_IMAGEPULLPOLICY));
assertThat(serverSpec.getImagePullSecrets().get(0).getName(), equalTo("pull-secret"));
assertThat(serverSpec.getEnvironmentVariables(), empty());
assertThat(serverSpec.getNodePort(), nullValue());
assertThat(serverSpec.getDesiredState(), equalTo("RUNNING"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void serverStartupInfo_containsWlsServerStartupAndConfig() {
configureServer("ms1").withNodePort(17);
addWlsServer("ms1");
invokeStep();
assertThat(getServerStartupInfo("ms1").serverConfig, sameInstance(getWlsServer("ms1")));
assertThat(getServerStartupInfo("ms1").getNodePort(), equalTo(17));
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void serverStartupInfo_containsWlsServerStartupAndConfig() {
configureServer("wls1").withNodePort(17);
addWlsServer("wls1");
invokeStep();
assertThat(getServerStartupInfo("wls1").serverConfig, sameInstance(getWlsServer("wls1")));
assertThat(getServerStartupInfo("wls1").getNodePort(), equalTo(17));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void createLoadBalancer() throws Exception {
Yaml yaml = new Yaml();
InputStream lbIs =
new FileInputStream(
new File(
BaseTest.getProjectRoot()
+ "/kubernetes/samples/scripts/create-weblogic-domain-load-balancer/create-load-balancer-inputs.yaml"));
Map<String, Object> lbMap = yaml.load(lbIs);
lbIs.close();
lbMap.put("domainName", domainMap.get("domainName"));
lbMap.put("domainUID", domainUid);
lbMap.put("namespace", domainNS);
if (domainMap.get("loadBalancer") != null) {
lbMap.put("loadBalancer", domainMap.get("loadBalancer"));
}
if (domainMap.get("loadBalancerWebPort") != null) {
lbMap.put("loadBalancerWebPort", domainMap.get("loadBalancerWebPort"));
}
if (domainMap.get("loadBalancerDashboardPort") != null) {
lbMap.put("loadBalancerDashboardPort", domainMap.get("loadBalancerDashboardPort"));
}
if (domainMap.get("loadBalancerVolumePath") != null) {
lbMap.put("loadBalancerVolumePath", domainMap.get("loadBalancerVolumePath"));
}
loadBalancer = (String) lbMap.get("loadBalancer");
loadBalancerWebPort = ((Integer) lbMap.get("loadBalancerWebPort")).intValue();
loadBalancerDashboardPort = ((Integer) lbMap.get("loadBalancerDashboardPort")).intValue();
if (domainUid.equals("domain7") && loadBalancer.equals("APACHE")) {
lbMap.put("loadBalancerAppPrepath", "/weblogic");
lbMap.put("loadBalancerExposeAdminPort", new Boolean(true));
}
lbMap.values().removeIf(Objects::isNull);
new LoadBalancer(lbMap);
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
private void createLoadBalancer() throws Exception {
Map<String, Object> lbMap = new HashMap<String, Object>();
lbMap.put("name", "traefik-hostrouting-" + domainUid);
lbMap.put("namespace", domainNS);
lbMap.put("host", domainUid + ".org");
lbMap.put("domainUID", domainUid);
lbMap.put("serviceName", domainUid + "-cluster-" + domainMap.get("clusterName"));
lbMap.put("loadBalancer", domainMap.getOrDefault("loadBalancer", loadBalancer));
loadBalancer = (String) lbMap.get("loadBalancer");
if (domainUid.equals("domain7") && loadBalancer.equals("APACHE")) {
/* lbMap.put("loadBalancerAppPrepath", "/weblogic");
lbMap.put("loadBalancerExposeAdminPort", new Boolean(true)); */
}
lbMap.values().removeIf(Objects::isNull);
new LoadBalancer(lbMap);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public NextAction apply(Packet packet) {
Collection<StepAndPacket> startDetails = new ArrayList<>();
for (Map.Entry<String, ServerKubernetesObjects> entry : c) {
startDetails.add(
new StepAndPacket(
new ServerDownStep(entry.getKey(), entry.getValue(), null), packet.clone()));
}
if (LOGGER.isFineEnabled()) {
DomainPresenceInfo info = packet.getSPI(DomainPresenceInfo.class);
Domain dom = info.getDomain();
DomainSpec spec = dom.getSpec();
Collection<String> stopList = new ArrayList<>();
for (Map.Entry<String, ServerKubernetesObjects> entry : c) {
stopList.add(entry.getKey());
}
LOGGER.fine(
"Stopping servers for domain with UID: "
+ spec.getDomainUID()
+ ", stop list: "
+ stopList);
}
if (startDetails.isEmpty()) {
return doNext(packet);
}
return doForkJoin(getNext(), packet, startDetails);
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public NextAction apply(Packet packet) {
Collection<StepAndPacket> startDetails = new ArrayList<>();
for (Map.Entry<String, ServerKubernetesObjects> entry : c) {
startDetails.add(
new StepAndPacket(
new ServerDownStep(entry.getKey(), entry.getValue(), null), packet.clone()));
}
if (startDetails.isEmpty()) {
return doNext(packet);
}
return doForkJoin(getNext(), packet, startDetails);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTwoDomainsManagedByTwoOperators() throws Exception {
Assume.assumeFalse(QUICKTEST);
String testMethodName = new Object() {}.getClass().getEnclosingMethod().getName();
logTestBegin(testMethodName);
logger.info("Creating Domain domain4 & verifing the domain creation");
logger.info("Checking if operator1 and domain1 are running, if not creating");
if (operator1 == null) {
operator1 = TestUtils.createOperator(opManagingdefaultAndtest1NSYamlFile);
}
Domain domain1 = null, domain2 = null;
boolean testCompletedSuccessfully = false;
try {
// load input yaml to map and add configOverrides
Map<String, Object> wlstDomainMap = TestUtils.loadYaml(domainOnPVUsingWLSTYamlFile);
wlstDomainMap.put("domainUID", "domain1onpvwlst");
wlstDomainMap.put("adminNodePort", new Integer("30702"));
wlstDomainMap.put("t3ChannelPort", new Integer("30031"));
domain1 = TestUtils.createDomain(wlstDomainMap);
domain1.verifyDomainCreated();
testBasicUseCases(domain1);
logger.info("Checking if operator2 is running, if not creating");
if (operator2 == null) {
operator2 = TestUtils.createOperator(opManagingtest2NSYamlFile);
}
// create domain5 with configured cluster
// ToDo: configured cluster support is removed from samples, modify the test to create
// configured cluster
Map<String, Object> wdtDomainMap = TestUtils.loadYaml(domainOnPVUsingWDTYamlFile);
wdtDomainMap.put("domainUID", "domain2onpvwdt");
wdtDomainMap.put("adminNodePort", new Integer("30703"));
wdtDomainMap.put("t3ChannelPort", new Integer("30041"));
// wdtDomainMap.put("clusterType", "Configured");
domain2 = TestUtils.createDomain(wdtDomainMap);
domain2.verifyDomainCreated();
testBasicUseCases(domain2);
logger.info("Verify the only remaining running domain domain1 is unaffected");
domain1.verifyDomainCreated();
testClusterScaling(operator2, domain2);
logger.info("Verify the only remaining running domain domain1 is unaffected");
domain1.verifyDomainCreated();
logger.info("Destroy and create domain4 and verify no impact on domain2");
domain1.destroy();
domain1.create();
logger.info("Verify no impact on domain2");
domain2.verifyDomainCreated();
testCompletedSuccessfully = true;
} finally {
String domainUidsToBeDeleted = "";
if (domain1 != null && (JENKINS || testCompletedSuccessfully)) {
domainUidsToBeDeleted = domain1.getDomainUid();
}
if (domain2 != null && (JENKINS || testCompletedSuccessfully)) {
domainUidsToBeDeleted = domainUidsToBeDeleted + "," + domain2.getDomainUid();
}
if (!domainUidsToBeDeleted.equals("")) {
logger.info("About to delete domains: " + domainUidsToBeDeleted);
TestUtils.deleteWeblogicDomainResources(domainUidsToBeDeleted);
logger.info("domain1 domainMap " + domain1.getDomainMap());
TestUtils.verifyAfterDeletion(domain1);
logger.info("domain2 domainMap " + domain2.getDomainMap());
TestUtils.verifyAfterDeletion(domain2);
}
}
logger.info("SUCCESS - " + testMethodName);
}
#location 69
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testTwoDomainsManagedByTwoOperators() throws Exception {
Assume.assumeFalse(QUICKTEST);
String testMethodName = new Object() {}.getClass().getEnclosingMethod().getName();
logTestBegin(testMethodName);
logger.info("Creating Domain domain4 & verifing the domain creation");
logger.info("Checking if operator1 and domain1 are running, if not creating");
if (operator1 == null) {
operator1 = TestUtils.createOperator(opManagingdefaultAndtest1NSYamlFile);
}
Domain domain1 = null, domain2 = null;
boolean testCompletedSuccessfully = false;
try {
// load input yaml to map and add configOverrides
Map<String, Object> wlstDomainMap = TestUtils.loadYaml(domainOnPVUsingWLSTYamlFile);
wlstDomainMap.put("domainUID", "domain1onpvwlst");
wlstDomainMap.put("adminNodePort", new Integer("30702"));
wlstDomainMap.put("t3ChannelPort", new Integer("30031"));
domain1 = TestUtils.createDomain(wlstDomainMap);
domain1.verifyDomainCreated();
testBasicUseCases(domain1);
logger.info("Checking if operator2 is running, if not creating");
if (operator2 == null) {
operator2 = TestUtils.createOperator(opManagingtest2NSYamlFile);
}
// create domain5 with configured cluster
// ToDo: configured cluster support is removed from samples, modify the test to create
// configured cluster
Map<String, Object> wdtDomainMap = TestUtils.loadYaml(domainOnPVUsingWDTYamlFile);
wdtDomainMap.put("domainUID", "domain2onpvwdt");
wdtDomainMap.put("adminNodePort", new Integer("30703"));
wdtDomainMap.put("t3ChannelPort", new Integer("30041"));
// wdtDomainMap.put("clusterType", "Configured");
domain2 = TestUtils.createDomain(wdtDomainMap);
domain2.verifyDomainCreated();
testBasicUseCases(domain2);
logger.info("Verify the only remaining running domain domain1 is unaffected");
domain1.verifyDomainCreated();
testClusterScaling(operator2, domain2);
logger.info("Verify the only remaining running domain domain1 is unaffected");
domain1.verifyDomainCreated();
logger.info("Destroy and create domain4 and verify no impact on domain2");
domain1.destroy();
domain1.create();
logger.info("Verify no impact on domain2");
domain2.verifyDomainCreated();
testCompletedSuccessfully = true;
} finally {
String domainUidsToBeDeleted = "";
if (domain1 != null && (JENKINS || testCompletedSuccessfully)) {
domainUidsToBeDeleted = domain1.getDomainUid();
}
if (domain2 != null && (JENKINS || testCompletedSuccessfully)) {
domainUidsToBeDeleted = domainUidsToBeDeleted + "," + domain2.getDomainUid();
}
if (!domainUidsToBeDeleted.equals("")) {
logger.info("About to delete domains: " + domainUidsToBeDeleted);
TestUtils.deleteWeblogicDomainResources(domainUidsToBeDeleted);
TestUtils.verifyAfterDeletion(domain1);
TestUtils.verifyAfterDeletion(domain2);
}
}
logger.info("SUCCESS - " + testMethodName);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void whenDesiredStateIsAdmin_serverStartupAddsToJavaOptionsEnvironment() {
configureServer("ms1")
.withDesiredState(ADMIN_STATE)
.withEnvironmentVariable("JAVA_OPTIONS", "value1");
addWlsServer("ms1");
invokeStep();
assertThat(
getServerStartupInfo("ms1").getEnvironment(),
hasItem(envVar("JAVA_OPTIONS", "-Dweblogic.management.startupMode=ADMIN value1")));
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void whenDesiredStateIsAdmin_serverStartupAddsToJavaOptionsEnvironment() {
configureServer("wls1")
.withDesiredState(ADMIN_STATE)
.withEnvironmentVariable("JAVA_OPTIONS", "value1");
addWlsServer("wls1");
invokeStep();
assertThat(
getServerStartupInfo("wls1").getEnvironment(),
hasItem(envVar("JAVA_OPTIONS", "-Dweblogic.management.startupMode=ADMIN value1")));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String readEntityAsString(ContainerRequestContext req) throws Exception {
LOGGER.entering();
// Read the entire input stream into a String
// This should be OK since JSON input shouldn't be monstrously big
BufferedReader ir = new BufferedReader(new InputStreamReader(req.getEntityStream()));
StringBuilder sb = new StringBuilder();
String line = null;
Charset cs = MessageUtils.getCharset(req.getMediaType());
// TBD - is all the Charset handling correct?
do {
line = ir.readLine();
if (line != null) {
sb.append(line);
}
} while (line != null);
ir.close();
String entity = sb.toString();
// Set the request input stream to a clone of the original input stream
// so that it can be read again
req.setEntityStream(new ByteArrayInputStream(entity.getBytes(cs)));
LOGGER.exiting(entity);
return entity;
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
private String readEntityAsString(ContainerRequestContext req) throws Exception {
LOGGER.entering();
// Read the entire input stream into a String
// This should be OK since JSON input shouldn't be monstrously big
try (BufferedReader ir = new BufferedReader(new InputStreamReader(req.getEntityStream()))) {
StringBuilder sb = new StringBuilder();
String line = null;
Charset cs = MessageUtils.getCharset(req.getMediaType());
// TBD - is all the Charset handling correct?
do {
line = ir.readLine();
if (line != null) {
sb.append(line);
}
} while (line != null);
ir.close();
String entity = sb.toString();
// Set the request input stream to a clone of the original input stream
// so that it can be read again
req.setEntityStream(new ByteArrayInputStream(entity.getBytes(cs)));
LOGGER.exiting(entity);
return entity;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void verifyValidateClusterStartupWarnsIfNoServersInCluster() {
WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1");
ClusterStartup cs = new ClusterStartup().withClusterName("cluster1").withReplicas(1);
wlsClusterConfig.validateClusterStartup(cs, null);
assertThat(logRecords, containsWarning(NO_WLS_SERVER_IN_CLUSTER, "cluster1"));
assertThat(logRecords, containsWarning(REPLICA_MORE_THAN_WLS_SERVERS));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void verifyValidateClusterStartupWarnsIfNoServersInCluster() {
WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1");
wlsClusterConfig.validateCluster(1, null);
assertThat(logRecords, containsWarning(NO_WLS_SERVER_IN_CLUSTER, "cluster1"));
} | 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.