output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
private static void tearDownTxManager() throws SQLException {
TransactionFactory.getTransactionProvider().getTransactionContext().tearDownTxManager();
}
|
#vulnerable code
private static void tearDownTxManager() throws SQLException {
TransactionFactory.getTransactionFactory().getTransactionContext().tearDownTxManager();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testSelectWithOldClient() throws Exception {
// Insert data with new client and read with old client
executeQueriesWithCurrentVersion(CREATE_ADD);
executeQueryWithClientVersion(compatibleClientVersion, QUERY);
assertExpectedOutput(CREATE_ADD, QUERY);
}
|
#vulnerable code
@Test
public void testSelectWithOldClient() throws Exception {
checkForPreConditions();
// Insert data with new client and read with old client
executeQueriesWithCurrentVersion(CREATE_ADD);
executeQueryWithClientVersion(compatibleClientVersion, QUERY);
assertTrue(compareOutput(CREATE_ADD, QUERY));
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected static void setTxnConfigs() throws IOException {
TransactionFactory.getTransactionProvider().getTransactionContext().setTxnConfigs(config, tmpFolder.newFolder().getAbsolutePath(), DEFAULT_TXN_TIMEOUT_SECONDS);
}
|
#vulnerable code
protected static void setTxnConfigs() throws IOException {
TransactionFactory.getTransactionFactory().getTransactionContext().setTxnConfigs(config, tmpFolder.newFolder().getAbsolutePath(), DEFAULT_TXN_TIMEOUT_SECONDS);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean seekToPreviousRow(Cell key) throws IOException {
KeyValue kv = PhoenixKeyValueUtil.maybeCopyCell(key);
if (reader.isTop()) {
Optional<Cell> firstKey = reader.getFirstKey();
// This will be null when the file is empty in which we can not seekBefore to
// any key
if (firstKey.isPresent()) {
return false;
}
if (this.comparator.compare(kv, firstKey.get(), true) <= 0) {
return super.seekToPreviousRow(key);
}
Cell replacedKey = getKeyPresentInHFiles(kv);
boolean seekToPreviousRow = super.seekToPreviousRow(replacedKey);
while(super.peek()!=null && !isSatisfiedMidKeyCondition(super.peek())) {
seekToPreviousRow = super.seekToPreviousRow(super.peek());
}
return seekToPreviousRow;
} else {
// The equals sign isn't strictly necessary just here to be consistent with
// seekTo
KeyValue splitKeyValue = new KeyValue.KeyOnlyKeyValue(reader.getSplitkey());
if (this.comparator.compare(kv, splitKeyValue, true) >= 0) {
boolean seekToPreviousRow = super.seekToPreviousRow(kv);
while(super.peek()!=null && !isSatisfiedMidKeyCondition(super.peek())) {
seekToPreviousRow = super.seekToPreviousRow(super.peek());
}
return seekToPreviousRow;
}
}
boolean seekToPreviousRow = super.seekToPreviousRow(kv);
while(super.peek()!=null && !isSatisfiedMidKeyCondition(super.peek())) {
seekToPreviousRow = super.seekToPreviousRow(super.peek());
}
return seekToPreviousRow;
}
|
#vulnerable code
@Override
public boolean seekToPreviousRow(Cell key) throws IOException {
KeyValue kv = PhoenixKeyValueUtil.maybeCopyCell(key);
if (reader.isTop()) {
Optional<Cell> firstKey = reader.getFirstKey();
// This will be null when the file is empty in which we can not seekBefore to
// any key
if (firstKey.isPresent()) {
return false;
}
byte[] fk = PhoenixKeyValueUtil.maybeCopyCell(firstKey.get()).getKey();
if (getComparator().compare(kv, firstKey.get()) <= 0) {
return super.seekToPreviousRow(key);
}
KeyValue replacedKey = getKeyPresentInHFiles(kv.getRowArray());
boolean seekToPreviousRow = super.seekToPreviousRow(replacedKey);
while(super.peek()!=null && !isSatisfiedMidKeyCondition(super.peek())) {
seekToPreviousRow = super.seekToPreviousRow(super.peek());
}
return seekToPreviousRow;
} else {
// The equals sign isn't strictly necessary just here to be consistent with
// seekTo
KeyValue splitKeyValue = KeyValueUtil.createKeyValueFromKey(reader.getSplitkey());
if (getComparator().compare(kv, splitKeyValue) >= 0) {
boolean seekToPreviousRow = super.seekToPreviousRow(kv);
while(super.peek()!=null && !isSatisfiedMidKeyCondition(super.peek())) {
seekToPreviousRow = super.seekToPreviousRow(super.peek());
}
return seekToPreviousRow;
}
}
boolean seekToPreviousRow = super.seekToPreviousRow(kv);
while(super.peek()!=null && !isSatisfiedMidKeyCondition(super.peek())) {
seekToPreviousRow = super.seekToPreviousRow(super.peek());
}
return seekToPreviousRow;
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static long getWallClockTimeFromCellTimeStamp(long tsOfCell) {
return TransactionFactory.getTransactionProvider().getTransactionContext().isPreExistingVersion(tsOfCell) ? tsOfCell : TransactionUtil.convertToMilliseconds(tsOfCell);
}
|
#vulnerable code
public static long getWallClockTimeFromCellTimeStamp(long tsOfCell) {
return TransactionFactory.getTransactionFactory().getTransactionContext().isPreExistingVersion(tsOfCell) ? tsOfCell : TransactionUtil.convertToMilliseconds(tsOfCell);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void batchStarted(MiniBatchOperationInProgress<Mutation> miniBatchOp, IndexMetaData context) throws IOException {
}
|
#vulnerable code
@Override
public void batchStarted(MiniBatchOperationInProgress<Mutation> miniBatchOp, IndexMetaData context) throws IOException {
// The entire purpose of this method impl is to get the existing rows for the
// table rows being indexed into the block cache, as the index maintenance code
// does a point scan per row.
List<IndexMaintainer> indexMaintainers = ((PhoenixIndexMetaData)context).getIndexMaintainers();
List<KeyRange> keys = Lists.newArrayListWithExpectedSize(miniBatchOp.size());
Map<ImmutableBytesWritable, IndexMaintainer> maintainers =
new HashMap<ImmutableBytesWritable, IndexMaintainer>();
ImmutableBytesWritable indexTableName = new ImmutableBytesWritable();
for (int i = 0; i < miniBatchOp.size(); i++) {
Mutation m = miniBatchOp.getOperation(i);
keys.add(PVarbinary.INSTANCE.getKeyRange(m.getRow()));
for(IndexMaintainer indexMaintainer: indexMaintainers) {
if (indexMaintainer.isImmutableRows()) continue;
indexTableName.set(indexMaintainer.getIndexTableName());
if (maintainers.get(indexTableName) != null) continue;
maintainers.put(indexTableName, indexMaintainer);
}
}
if (maintainers.isEmpty()) return;
Scan scan = IndexManagementUtil.newLocalStateScan(new ArrayList<IndexMaintainer>(maintainers.values()));
ScanRanges scanRanges = ScanRanges.createPointLookup(keys);
scanRanges.initializeScan(scan);
scan.setFilter(new SkipScanFilter(scanRanges.getSkipScanFilter(),true));
Region region = env.getRegion();
RegionScanner scanner = region.getScanner(scan);
// Run through the scanner using internal nextRaw method
region.startRegionOperation();
try {
synchronized (scanner) {
boolean hasMore;
do {
List<Cell> results = Lists.newArrayList();
// Results are potentially returned even when the return value of s.next is
// false since this is an indication of whether or not there are more values
// after the ones returned
hasMore = scanner.nextRaw(results);
} while (hasMore);
}
} finally {
try {
scanner.close();
} finally {
region.closeRegionOperation();
}
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected RegionScanner doPostScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Scan scan, final RegionScanner s) throws IOException, SQLException {
RegionCoprocessorEnvironment env = c.getEnvironment();
Region region = env.getRegion();
long ts = scan.getTimeRange().getMax();
boolean localIndexScan = ScanUtil.isLocalIndex(scan);
if (ScanUtil.isAnalyzeTable(scan)) {
byte[] gp_width_bytes =
scan.getAttribute(BaseScannerRegionObserver.GUIDEPOST_WIDTH_BYTES);
byte[] gp_per_region_bytes =
scan.getAttribute(BaseScannerRegionObserver.GUIDEPOST_PER_REGION);
// Let this throw, as this scan is being done for the sole purpose of collecting stats
StatisticsCollector statsCollector = StatisticsCollectorFactory.createStatisticsCollector(
env, region.getRegionInfo().getTable().getNameAsString(), ts,
gp_width_bytes, gp_per_region_bytes);
return collectStats(s, statsCollector, region, scan, env.getConfiguration());
} else if (ScanUtil.isIndexRebuild(scan)) { return rebuildIndices(s, region, scan, env.getConfiguration()); }
int offsetToBe = 0;
if (localIndexScan) {
/*
* For local indexes, we need to set an offset on row key expressions to skip
* the region start key.
*/
offsetToBe = region.getRegionInfo().getStartKey().length != 0 ? region.getRegionInfo().getStartKey().length :
region.getRegionInfo().getEndKey().length;
ScanUtil.setRowKeyOffset(scan, offsetToBe);
}
final int offset = offsetToBe;
PTable projectedTable = null;
PTable writeToTable = null;
byte[][] values = null;
byte[] descRowKeyTableBytes = scan.getAttribute(UPGRADE_DESC_ROW_KEY);
boolean isDescRowKeyOrderUpgrade = descRowKeyTableBytes != null;
if (isDescRowKeyOrderUpgrade) {
logger.debug("Upgrading row key for " + region.getRegionInfo().getTable().getNameAsString());
projectedTable = deserializeTable(descRowKeyTableBytes);
try {
writeToTable = PTableImpl.makePTable(projectedTable, true);
} catch (SQLException e) {
ServerUtil.throwIOException("Upgrade failed", e); // Impossible
}
values = new byte[projectedTable.getPKColumns().size()][];
}
byte[] localIndexBytes = scan.getAttribute(LOCAL_INDEX_BUILD);
List<IndexMaintainer> indexMaintainers = localIndexBytes == null ? null : IndexMaintainer.deserialize(localIndexBytes);
List<Mutation> indexMutations = localIndexBytes == null ? Collections.<Mutation>emptyList() : Lists.<Mutation>newArrayListWithExpectedSize(1024);
RegionScanner theScanner = s;
byte[] indexUUID = scan.getAttribute(PhoenixIndexCodec.INDEX_UUID);
byte[] txState = scan.getAttribute(BaseScannerRegionObserver.TX_STATE);
List<Expression> selectExpressions = null;
byte[] upsertSelectTable = scan.getAttribute(BaseScannerRegionObserver.UPSERT_SELECT_TABLE);
boolean isUpsert = false;
boolean isDelete = false;
byte[] deleteCQ = null;
byte[] deleteCF = null;
byte[] emptyCF = null;
HTable targetHTable = null;
boolean areMutationInSameRegion = true;
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
if (upsertSelectTable != null) {
isUpsert = true;
projectedTable = deserializeTable(upsertSelectTable);
targetHTable = new HTable(env.getConfiguration(), projectedTable.getPhysicalName().getBytes());
selectExpressions = deserializeExpressions(scan.getAttribute(BaseScannerRegionObserver.UPSERT_SELECT_EXPRS));
values = new byte[projectedTable.getPKColumns().size()][];
areMutationInSameRegion = Bytes.compareTo(targetHTable.getTableName(),
region.getTableDesc().getTableName().getName()) == 0
&& !isPkPositionChanging(new TableRef(projectedTable), selectExpressions);
} else {
byte[] isDeleteAgg = scan.getAttribute(BaseScannerRegionObserver.DELETE_AGG);
isDelete = isDeleteAgg != null && Bytes.compareTo(PDataType.TRUE_BYTES, isDeleteAgg) == 0;
if (!isDelete) {
deleteCF = scan.getAttribute(BaseScannerRegionObserver.DELETE_CF);
deleteCQ = scan.getAttribute(BaseScannerRegionObserver.DELETE_CQ);
}
emptyCF = scan.getAttribute(BaseScannerRegionObserver.EMPTY_CF);
}
TupleProjector tupleProjector = null;
byte[][] viewConstants = null;
ColumnReference[] dataColumns = IndexUtil.deserializeDataTableColumnsToJoin(scan);
final TupleProjector p = TupleProjector.deserializeProjectorFromScan(scan);
final HashJoinInfo j = HashJoinInfo.deserializeHashJoinFromScan(scan);
if ((localIndexScan && !isDelete && !isDescRowKeyOrderUpgrade) || (j == null && p != null)) {
if (dataColumns != null) {
tupleProjector = IndexUtil.getTupleProjector(scan, dataColumns);
viewConstants = IndexUtil.deserializeViewConstantsFromScan(scan);
}
ImmutableBytesWritable tempPtr = new ImmutableBytesWritable();
theScanner =
getWrappedScanner(c, theScanner, offset, scan, dataColumns, tupleProjector,
region, indexMaintainers == null ? null : indexMaintainers.get(0), viewConstants, p, tempPtr);
}
if (j != null) {
theScanner = new HashJoinRegionScanner(theScanner, p, j, ScanUtil.getTenantId(scan), env);
}
int batchSize = 0;
long batchSizeBytes = 0L;
List<Mutation> mutations = Collections.emptyList();
boolean needToWrite = false;
Configuration conf = c.getEnvironment().getConfiguration();
long flushSize = region.getTableDesc().getMemStoreFlushSize();
if (flushSize <= 0) {
flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE,
HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE);
}
/**
* Slow down the writes if the memstore size more than
* (hbase.hregion.memstore.block.multiplier - 1) times hbase.hregion.memstore.flush.size
* bytes. This avoids flush storm to hdfs for cases like index building where reads and
* write happen to all the table regions in the server.
*/
final long blockingMemStoreSize = flushSize * (
conf.getLong(HConstants.HREGION_MEMSTORE_BLOCK_MULTIPLIER,
HConstants.DEFAULT_HREGION_MEMSTORE_BLOCK_MULTIPLIER)-1) ;
boolean buildLocalIndex = indexMaintainers != null && dataColumns==null && !localIndexScan;
if (isDescRowKeyOrderUpgrade || isDelete || isUpsert || (deleteCQ != null && deleteCF != null) || emptyCF != null || buildLocalIndex) {
needToWrite = true;
// TODO: size better
mutations = Lists.newArrayListWithExpectedSize(1024);
batchSize = env.getConfiguration().getInt(MUTATE_BATCH_SIZE_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE);
batchSizeBytes = env.getConfiguration().getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
}
Aggregators aggregators = ServerAggregators.deserialize(
scan.getAttribute(BaseScannerRegionObserver.AGGREGATORS), env.getConfiguration());
Aggregator[] rowAggregators = aggregators.getAggregators();
boolean hasMore;
boolean hasAny = false;
MultiKeyValueTuple result = new MultiKeyValueTuple();
if (logger.isDebugEnabled()) {
logger.debug(LogUtil.addCustomAnnotations("Starting ungrouped coprocessor scan " + scan + " "+region.getRegionInfo(), ScanUtil.getCustomAnnotations(scan)));
}
long rowCount = 0;
final RegionScanner innerScanner = theScanner;
byte[] indexMaintainersPtr = scan.getAttribute(PhoenixIndexCodec.INDEX_MD);
boolean acquiredLock = false;
try {
if(needToWrite) {
synchronized (lock) {
scansReferenceCount++;
}
}
region.startRegionOperation();
acquiredLock = true;
synchronized (innerScanner) {
do {
List<Cell> results = new ArrayList<Cell>();
// Results are potentially returned even when the return value of s.next is false
// since this is an indication of whether or not there are more values after the
// ones returned
hasMore = innerScanner.nextRaw(results);
if (!results.isEmpty()) {
rowCount++;
result.setKeyValues(results);
if (isDescRowKeyOrderUpgrade) {
Arrays.fill(values, null);
Cell firstKV = results.get(0);
RowKeySchema schema = projectedTable.getRowKeySchema();
int maxOffset = schema.iterator(firstKV.getRowArray(), firstKV.getRowOffset() + offset, firstKV.getRowLength(), ptr);
for (int i = 0; i < schema.getFieldCount(); i++) {
Boolean hasValue = schema.next(ptr, i, maxOffset);
if (hasValue == null) {
break;
}
Field field = schema.getField(i);
if (field.getSortOrder() == SortOrder.DESC) {
// Special case for re-writing DESC ARRAY, as the actual byte value needs to change in this case
if (field.getDataType().isArrayType()) {
field.getDataType().coerceBytes(ptr, null, field.getDataType(),
field.getMaxLength(), field.getScale(), field.getSortOrder(),
field.getMaxLength(), field.getScale(), field.getSortOrder(), true); // force to use correct separator byte
}
// Special case for re-writing DESC CHAR or DESC BINARY, to force the re-writing of trailing space characters
else if (field.getDataType() == PChar.INSTANCE || field.getDataType() == PBinary.INSTANCE) {
int len = ptr.getLength();
while (len > 0 && ptr.get()[ptr.getOffset() + len - 1] == StringUtil.SPACE_UTF8) {
len--;
}
ptr.set(ptr.get(), ptr.getOffset(), len);
// Special case for re-writing DESC FLOAT and DOUBLE, as they're not inverted like they should be (PHOENIX-2171)
} else if (field.getDataType() == PFloat.INSTANCE || field.getDataType() == PDouble.INSTANCE) {
byte[] invertedBytes = SortOrder.invert(ptr.get(), ptr.getOffset(), ptr.getLength());
ptr.set(invertedBytes);
}
} else if (field.getDataType() == PBinary.INSTANCE) {
// Remove trailing space characters so that the setValues call below will replace them
// with the correct zero byte character. Note this is somewhat dangerous as these
// could be legit, but I don't know what the alternative is.
int len = ptr.getLength();
while (len > 0 && ptr.get()[ptr.getOffset() + len - 1] == StringUtil.SPACE_UTF8) {
len--;
}
ptr.set(ptr.get(), ptr.getOffset(), len);
}
values[i] = ptr.copyBytes();
}
writeToTable.newKey(ptr, values);
if (Bytes.compareTo(
firstKV.getRowArray(), firstKV.getRowOffset() + offset, firstKV.getRowLength(),
ptr.get(),ptr.getOffset() + offset,ptr.getLength()) == 0) {
continue;
}
byte[] newRow = ByteUtil.copyKeyBytesIfNecessary(ptr);
if (offset > 0) { // for local indexes (prepend region start key)
byte[] newRowWithOffset = new byte[offset + newRow.length];
System.arraycopy(firstKV.getRowArray(), firstKV.getRowOffset(), newRowWithOffset, 0, offset);;
System.arraycopy(newRow, 0, newRowWithOffset, offset, newRow.length);
newRow = newRowWithOffset;
}
byte[] oldRow = Bytes.copy(firstKV.getRowArray(), firstKV.getRowOffset(), firstKV.getRowLength());
for (Cell cell : results) {
// Copy existing cell but with new row key
Cell newCell = new KeyValue(newRow, 0, newRow.length,
cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(),
cell.getTimestamp(), KeyValue.Type.codeToType(cell.getTypeByte()),
cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
switch (KeyValue.Type.codeToType(cell.getTypeByte())) {
case Put:
// If Put, point delete old Put
Delete del = new Delete(oldRow);
del.addDeleteMarker(new KeyValue(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
cell.getQualifierArray(), cell.getQualifierOffset(),
cell.getQualifierLength(), cell.getTimestamp(), KeyValue.Type.Delete,
ByteUtil.EMPTY_BYTE_ARRAY, 0, 0));
mutations.add(del);
Put put = new Put(newRow);
put.add(newCell);
mutations.add(put);
break;
case Delete:
case DeleteColumn:
case DeleteFamily:
case DeleteFamilyVersion:
Delete delete = new Delete(newRow);
delete.addDeleteMarker(newCell);
mutations.add(delete);
break;
}
}
} else if (buildLocalIndex) {
for (IndexMaintainer maintainer : indexMaintainers) {
if (!results.isEmpty()) {
result.getKey(ptr);
ValueGetter valueGetter =
maintainer.createGetterFromKeyValues(
ImmutableBytesPtr.copyBytesIfNecessary(ptr),
results);
Put put = maintainer.buildUpdateMutation(kvBuilder,
valueGetter, ptr, results.get(0).getTimestamp(),
env.getRegion().getRegionInfo().getStartKey(),
env.getRegion().getRegionInfo().getEndKey());
indexMutations.add(put);
}
}
result.setKeyValues(results);
} else if (isDelete) {
// FIXME: the version of the Delete constructor without the lock
// args was introduced in 0.94.4, thus if we try to use it here
// we can no longer use the 0.94.2 version of the client.
Cell firstKV = results.get(0);
Delete delete = new Delete(firstKV.getRowArray(),
firstKV.getRowOffset(), firstKV.getRowLength(),ts);
mutations.add(delete);
// force tephra to ignore this deletes
delete.setAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY, new byte[0]);
} else if (isUpsert) {
Arrays.fill(values, null);
int bucketNumOffset = 0;
if (projectedTable.getBucketNum() != null) {
values[0] = new byte[] { 0 };
bucketNumOffset = 1;
}
int i = bucketNumOffset;
List<PColumn> projectedColumns = projectedTable.getColumns();
for (; i < projectedTable.getPKColumns().size(); i++) {
Expression expression = selectExpressions.get(i - bucketNumOffset);
if (expression.evaluate(result, ptr)) {
values[i] = ptr.copyBytes();
// If SortOrder from expression in SELECT doesn't match the
// column being projected into then invert the bits.
if (expression.getSortOrder() !=
projectedColumns.get(i).getSortOrder()) {
SortOrder.invert(values[i], 0, values[i], 0,
values[i].length);
}
}else{
values[i] = ByteUtil.EMPTY_BYTE_ARRAY;
}
}
projectedTable.newKey(ptr, values);
PRow row = projectedTable.newRow(kvBuilder, ts, ptr, false);
for (; i < projectedColumns.size(); i++) {
Expression expression = selectExpressions.get(i - bucketNumOffset);
if (expression.evaluate(result, ptr)) {
PColumn column = projectedColumns.get(i);
if (!column.getDataType().isSizeCompatible(ptr, null,
expression.getDataType(), expression.getSortOrder(),
expression.getMaxLength(), expression.getScale(),
column.getMaxLength(), column.getScale())) {
throw new DataExceedsCapacityException(
column.getDataType(), column.getMaxLength(),
column.getScale(), column.getName().getString(), ptr);
}
column.getDataType().coerceBytes(ptr, null,
expression.getDataType(), expression.getMaxLength(),
expression.getScale(), expression.getSortOrder(),
column.getMaxLength(), column.getScale(),
column.getSortOrder(), projectedTable.rowKeyOrderOptimizable());
byte[] bytes = ByteUtil.copyKeyBytesIfNecessary(ptr);
row.setValue(column, bytes);
}
}
for (Mutation mutation : row.toRowMutations()) {
mutations.add(mutation);
}
for (i = 0; i < selectExpressions.size(); i++) {
selectExpressions.get(i).reset();
}
} else if (deleteCF != null && deleteCQ != null) {
// No need to search for delete column, since we project only it
// if no empty key value is being set
if (emptyCF == null ||
result.getValue(deleteCF, deleteCQ) != null) {
Delete delete = new Delete(results.get(0).getRowArray(),
results.get(0).getRowOffset(),
results.get(0).getRowLength());
delete.deleteColumns(deleteCF, deleteCQ, ts);
// force tephra to ignore this deletes
delete.setAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY, new byte[0]);
mutations.add(delete);
}
}
if (emptyCF != null) {
/*
* If we've specified an emptyCF, then we need to insert an empty
* key value "retroactively" for any key value that is visible at
* the timestamp that the DDL was issued. Key values that are not
* visible at this timestamp will not ever be projected up to
* scans past this timestamp, so don't need to be considered.
* We insert one empty key value per row per timestamp.
*/
Set<Long> timeStamps =
Sets.newHashSetWithExpectedSize(results.size());
for (Cell kv : results) {
long kvts = kv.getTimestamp();
if (!timeStamps.contains(kvts)) {
Put put = new Put(kv.getRowArray(), kv.getRowOffset(),
kv.getRowLength());
put.add(emptyCF, QueryConstants.EMPTY_COLUMN_BYTES, kvts,
ByteUtil.EMPTY_BYTE_ARRAY);
mutations.add(put);
}
}
// Commit in batches based on UPSERT_BATCH_SIZE_BYTES_ATTRIB in config
List<List<Mutation>> batchMutationList =
MutationState.getMutationBatchList(batchSize, batchSizeBytes, mutations);
for (List<Mutation> batchMutations : batchMutationList) {
commit(region, batchMutations, indexUUID, blockingMemStoreSize, indexMaintainersPtr,
txState, areMutationInSameRegion, targetHTable);
batchMutations.clear();
}
mutations.clear();
// Commit in batches based on UPSERT_BATCH_SIZE_BYTES_ATTRIB in config
List<List<Mutation>> batchIndexMutationList =
MutationState.getMutationBatchList(batchSize, batchSizeBytes, indexMutations);
for (List<Mutation> batchIndexMutations : batchIndexMutationList) {
commitBatch(region, batchIndexMutations, null, blockingMemStoreSize, null, txState);
batchIndexMutations.clear();
}
indexMutations.clear();
}
aggregators.aggregate(rowAggregators, result);
hasAny = true;
}
} while (hasMore);
if (!mutations.isEmpty()) {
commit(region, mutations, indexUUID, blockingMemStoreSize, indexMaintainersPtr, txState,
areMutationInSameRegion, targetHTable);
mutations.clear();
}
if (!indexMutations.isEmpty()) {
commitBatch(region, indexMutations, null, blockingMemStoreSize, indexMaintainersPtr, txState);
indexMutations.clear();
}
}
} finally {
if(needToWrite) {
synchronized (lock) {
scansReferenceCount--;
}
}
if (targetHTable != null) {
targetHTable.close();
}
try {
innerScanner.close();
} finally {
if (acquiredLock) region.closeRegionOperation();
}
}
if (logger.isDebugEnabled()) {
logger.debug(LogUtil.addCustomAnnotations("Finished scanning " + rowCount + " rows for ungrouped coprocessor scan " + scan, ScanUtil.getCustomAnnotations(scan)));
}
final boolean hadAny = hasAny;
KeyValue keyValue = null;
if (hadAny) {
byte[] value = aggregators.toBytes(rowAggregators);
keyValue = KeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY, SINGLE_COLUMN_FAMILY, SINGLE_COLUMN, AGG_TIMESTAMP, value, 0, value.length);
}
final KeyValue aggKeyValue = keyValue;
RegionScanner scanner = new BaseRegionScanner(innerScanner) {
private boolean done = !hadAny;
@Override
public boolean isFilterDone() {
return done;
}
@Override
public boolean next(List<Cell> results) throws IOException {
if (done) return false;
done = true;
results.add(aggKeyValue);
return false;
}
@Override
public long getMaxResultSize() {
return scan.getMaxResultSize();
}
};
return scanner;
}
|
#vulnerable code
@Override
protected RegionScanner doPostScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Scan scan, final RegionScanner s) throws IOException, SQLException {
RegionCoprocessorEnvironment env = c.getEnvironment();
Region region = env.getRegion();
long ts = scan.getTimeRange().getMax();
boolean localIndexScan = ScanUtil.isLocalIndex(scan);
if (ScanUtil.isAnalyzeTable(scan)) {
byte[] gp_width_bytes =
scan.getAttribute(BaseScannerRegionObserver.GUIDEPOST_WIDTH_BYTES);
byte[] gp_per_region_bytes =
scan.getAttribute(BaseScannerRegionObserver.GUIDEPOST_PER_REGION);
// Let this throw, as this scan is being done for the sole purpose of collecting stats
StatisticsCollector statsCollector = StatisticsCollectorFactory.createStatisticsCollector(
env, region.getRegionInfo().getTable().getNameAsString(), ts,
gp_width_bytes, gp_per_region_bytes);
return collectStats(s, statsCollector, region, scan, env.getConfiguration());
} else if (ScanUtil.isIndexRebuild(scan)) { return rebuildIndices(s, region, scan, env.getConfiguration()); }
int offsetToBe = 0;
if (localIndexScan) {
/*
* For local indexes, we need to set an offset on row key expressions to skip
* the region start key.
*/
offsetToBe = region.getRegionInfo().getStartKey().length != 0 ? region.getRegionInfo().getStartKey().length :
region.getRegionInfo().getEndKey().length;
ScanUtil.setRowKeyOffset(scan, offsetToBe);
}
final int offset = offsetToBe;
PTable projectedTable = null;
PTable writeToTable = null;
byte[][] values = null;
byte[] descRowKeyTableBytes = scan.getAttribute(UPGRADE_DESC_ROW_KEY);
boolean isDescRowKeyOrderUpgrade = descRowKeyTableBytes != null;
if (isDescRowKeyOrderUpgrade) {
logger.debug("Upgrading row key for " + region.getRegionInfo().getTable().getNameAsString());
projectedTable = deserializeTable(descRowKeyTableBytes);
try {
writeToTable = PTableImpl.makePTable(projectedTable, true);
} catch (SQLException e) {
ServerUtil.throwIOException("Upgrade failed", e); // Impossible
}
values = new byte[projectedTable.getPKColumns().size()][];
}
byte[] localIndexBytes = scan.getAttribute(LOCAL_INDEX_BUILD);
List<IndexMaintainer> indexMaintainers = localIndexBytes == null ? null : IndexMaintainer.deserialize(localIndexBytes);
List<Mutation> indexMutations = localIndexBytes == null ? Collections.<Mutation>emptyList() : Lists.<Mutation>newArrayListWithExpectedSize(1024);
RegionScanner theScanner = s;
byte[] indexUUID = scan.getAttribute(PhoenixIndexCodec.INDEX_UUID);
byte[] txState = scan.getAttribute(BaseScannerRegionObserver.TX_STATE);
List<Expression> selectExpressions = null;
byte[] upsertSelectTable = scan.getAttribute(BaseScannerRegionObserver.UPSERT_SELECT_TABLE);
boolean isUpsert = false;
boolean isDelete = false;
byte[] deleteCQ = null;
byte[] deleteCF = null;
byte[] emptyCF = null;
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
if (upsertSelectTable != null) {
isUpsert = true;
projectedTable = deserializeTable(upsertSelectTable);
selectExpressions = deserializeExpressions(scan.getAttribute(BaseScannerRegionObserver.UPSERT_SELECT_EXPRS));
values = new byte[projectedTable.getPKColumns().size()][];
} else {
byte[] isDeleteAgg = scan.getAttribute(BaseScannerRegionObserver.DELETE_AGG);
isDelete = isDeleteAgg != null && Bytes.compareTo(PDataType.TRUE_BYTES, isDeleteAgg) == 0;
if (!isDelete) {
deleteCF = scan.getAttribute(BaseScannerRegionObserver.DELETE_CF);
deleteCQ = scan.getAttribute(BaseScannerRegionObserver.DELETE_CQ);
}
emptyCF = scan.getAttribute(BaseScannerRegionObserver.EMPTY_CF);
}
TupleProjector tupleProjector = null;
byte[][] viewConstants = null;
ColumnReference[] dataColumns = IndexUtil.deserializeDataTableColumnsToJoin(scan);
final TupleProjector p = TupleProjector.deserializeProjectorFromScan(scan);
final HashJoinInfo j = HashJoinInfo.deserializeHashJoinFromScan(scan);
if ((localIndexScan && !isDelete && !isDescRowKeyOrderUpgrade) || (j == null && p != null)) {
if (dataColumns != null) {
tupleProjector = IndexUtil.getTupleProjector(scan, dataColumns);
viewConstants = IndexUtil.deserializeViewConstantsFromScan(scan);
}
ImmutableBytesWritable tempPtr = new ImmutableBytesWritable();
theScanner =
getWrappedScanner(c, theScanner, offset, scan, dataColumns, tupleProjector,
region, indexMaintainers == null ? null : indexMaintainers.get(0), viewConstants, p, tempPtr);
}
if (j != null) {
theScanner = new HashJoinRegionScanner(theScanner, p, j, ScanUtil.getTenantId(scan), env);
}
int batchSize = 0;
long batchSizeBytes = 0L;
List<Mutation> mutations = Collections.emptyList();
boolean needToWrite = false;
Configuration conf = c.getEnvironment().getConfiguration();
long flushSize = region.getTableDesc().getMemStoreFlushSize();
if (flushSize <= 0) {
flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE,
HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE);
}
/**
* Slow down the writes if the memstore size more than
* (hbase.hregion.memstore.block.multiplier - 1) times hbase.hregion.memstore.flush.size
* bytes. This avoids flush storm to hdfs for cases like index building where reads and
* write happen to all the table regions in the server.
*/
final long blockingMemStoreSize = flushSize * (
conf.getLong(HConstants.HREGION_MEMSTORE_BLOCK_MULTIPLIER,
HConstants.DEFAULT_HREGION_MEMSTORE_BLOCK_MULTIPLIER)-1) ;
boolean buildLocalIndex = indexMaintainers != null && dataColumns==null && !localIndexScan;
if (isDescRowKeyOrderUpgrade || isDelete || isUpsert || (deleteCQ != null && deleteCF != null) || emptyCF != null || buildLocalIndex) {
needToWrite = true;
// TODO: size better
mutations = Lists.newArrayListWithExpectedSize(1024);
batchSize = env.getConfiguration().getInt(MUTATE_BATCH_SIZE_ATTRIB, QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE);
batchSizeBytes = env.getConfiguration().getLong(MUTATE_BATCH_SIZE_BYTES_ATTRIB,
QueryServicesOptions.DEFAULT_MUTATE_BATCH_SIZE_BYTES);
}
Aggregators aggregators = ServerAggregators.deserialize(
scan.getAttribute(BaseScannerRegionObserver.AGGREGATORS), env.getConfiguration());
Aggregator[] rowAggregators = aggregators.getAggregators();
boolean hasMore;
boolean hasAny = false;
MultiKeyValueTuple result = new MultiKeyValueTuple();
if (logger.isDebugEnabled()) {
logger.debug(LogUtil.addCustomAnnotations("Starting ungrouped coprocessor scan " + scan + " "+region.getRegionInfo(), ScanUtil.getCustomAnnotations(scan)));
}
long rowCount = 0;
final RegionScanner innerScanner = theScanner;
byte[] indexMaintainersPtr = scan.getAttribute(PhoenixIndexCodec.INDEX_MD);
boolean acquiredLock = false;
try {
if(needToWrite) {
synchronized (lock) {
scansReferenceCount++;
}
}
region.startRegionOperation();
acquiredLock = true;
synchronized (innerScanner) {
do {
List<Cell> results = new ArrayList<Cell>();
// Results are potentially returned even when the return value of s.next is false
// since this is an indication of whether or not there are more values after the
// ones returned
hasMore = innerScanner.nextRaw(results);
if (!results.isEmpty()) {
rowCount++;
result.setKeyValues(results);
if (isDescRowKeyOrderUpgrade) {
Arrays.fill(values, null);
Cell firstKV = results.get(0);
RowKeySchema schema = projectedTable.getRowKeySchema();
int maxOffset = schema.iterator(firstKV.getRowArray(), firstKV.getRowOffset() + offset, firstKV.getRowLength(), ptr);
for (int i = 0; i < schema.getFieldCount(); i++) {
Boolean hasValue = schema.next(ptr, i, maxOffset);
if (hasValue == null) {
break;
}
Field field = schema.getField(i);
if (field.getSortOrder() == SortOrder.DESC) {
// Special case for re-writing DESC ARRAY, as the actual byte value needs to change in this case
if (field.getDataType().isArrayType()) {
field.getDataType().coerceBytes(ptr, null, field.getDataType(),
field.getMaxLength(), field.getScale(), field.getSortOrder(),
field.getMaxLength(), field.getScale(), field.getSortOrder(), true); // force to use correct separator byte
}
// Special case for re-writing DESC CHAR or DESC BINARY, to force the re-writing of trailing space characters
else if (field.getDataType() == PChar.INSTANCE || field.getDataType() == PBinary.INSTANCE) {
int len = ptr.getLength();
while (len > 0 && ptr.get()[ptr.getOffset() + len - 1] == StringUtil.SPACE_UTF8) {
len--;
}
ptr.set(ptr.get(), ptr.getOffset(), len);
// Special case for re-writing DESC FLOAT and DOUBLE, as they're not inverted like they should be (PHOENIX-2171)
} else if (field.getDataType() == PFloat.INSTANCE || field.getDataType() == PDouble.INSTANCE) {
byte[] invertedBytes = SortOrder.invert(ptr.get(), ptr.getOffset(), ptr.getLength());
ptr.set(invertedBytes);
}
} else if (field.getDataType() == PBinary.INSTANCE) {
// Remove trailing space characters so that the setValues call below will replace them
// with the correct zero byte character. Note this is somewhat dangerous as these
// could be legit, but I don't know what the alternative is.
int len = ptr.getLength();
while (len > 0 && ptr.get()[ptr.getOffset() + len - 1] == StringUtil.SPACE_UTF8) {
len--;
}
ptr.set(ptr.get(), ptr.getOffset(), len);
}
values[i] = ptr.copyBytes();
}
writeToTable.newKey(ptr, values);
if (Bytes.compareTo(
firstKV.getRowArray(), firstKV.getRowOffset() + offset, firstKV.getRowLength(),
ptr.get(),ptr.getOffset() + offset,ptr.getLength()) == 0) {
continue;
}
byte[] newRow = ByteUtil.copyKeyBytesIfNecessary(ptr);
if (offset > 0) { // for local indexes (prepend region start key)
byte[] newRowWithOffset = new byte[offset + newRow.length];
System.arraycopy(firstKV.getRowArray(), firstKV.getRowOffset(), newRowWithOffset, 0, offset);;
System.arraycopy(newRow, 0, newRowWithOffset, offset, newRow.length);
newRow = newRowWithOffset;
}
byte[] oldRow = Bytes.copy(firstKV.getRowArray(), firstKV.getRowOffset(), firstKV.getRowLength());
for (Cell cell : results) {
// Copy existing cell but with new row key
Cell newCell = new KeyValue(newRow, 0, newRow.length,
cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(),
cell.getTimestamp(), KeyValue.Type.codeToType(cell.getTypeByte()),
cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
switch (KeyValue.Type.codeToType(cell.getTypeByte())) {
case Put:
// If Put, point delete old Put
Delete del = new Delete(oldRow);
del.addDeleteMarker(new KeyValue(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
cell.getQualifierArray(), cell.getQualifierOffset(),
cell.getQualifierLength(), cell.getTimestamp(), KeyValue.Type.Delete,
ByteUtil.EMPTY_BYTE_ARRAY, 0, 0));
mutations.add(del);
Put put = new Put(newRow);
put.add(newCell);
mutations.add(put);
break;
case Delete:
case DeleteColumn:
case DeleteFamily:
case DeleteFamilyVersion:
Delete delete = new Delete(newRow);
delete.addDeleteMarker(newCell);
mutations.add(delete);
break;
}
}
} else if (buildLocalIndex) {
for (IndexMaintainer maintainer : indexMaintainers) {
if (!results.isEmpty()) {
result.getKey(ptr);
ValueGetter valueGetter =
maintainer.createGetterFromKeyValues(
ImmutableBytesPtr.copyBytesIfNecessary(ptr),
results);
Put put = maintainer.buildUpdateMutation(kvBuilder,
valueGetter, ptr, results.get(0).getTimestamp(),
env.getRegion().getRegionInfo().getStartKey(),
env.getRegion().getRegionInfo().getEndKey());
indexMutations.add(put);
}
}
result.setKeyValues(results);
} else if (isDelete) {
// FIXME: the version of the Delete constructor without the lock
// args was introduced in 0.94.4, thus if we try to use it here
// we can no longer use the 0.94.2 version of the client.
Cell firstKV = results.get(0);
Delete delete = new Delete(firstKV.getRowArray(),
firstKV.getRowOffset(), firstKV.getRowLength(),ts);
mutations.add(delete);
// force tephra to ignore this deletes
delete.setAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY, new byte[0]);
} else if (isUpsert) {
Arrays.fill(values, null);
int i = 0;
List<PColumn> projectedColumns = projectedTable.getColumns();
for (; i < projectedTable.getPKColumns().size(); i++) {
Expression expression = selectExpressions.get(i);
if (expression.evaluate(result, ptr)) {
values[i] = ptr.copyBytes();
// If SortOrder from expression in SELECT doesn't match the
// column being projected into then invert the bits.
if (expression.getSortOrder() !=
projectedColumns.get(i).getSortOrder()) {
SortOrder.invert(values[i], 0, values[i], 0,
values[i].length);
}
}
}
projectedTable.newKey(ptr, values);
PRow row = projectedTable.newRow(kvBuilder, ts, ptr, false);
for (; i < projectedColumns.size(); i++) {
Expression expression = selectExpressions.get(i);
if (expression.evaluate(result, ptr)) {
PColumn column = projectedColumns.get(i);
if (!column.getDataType().isSizeCompatible(ptr, null,
expression.getDataType(), expression.getSortOrder(),
expression.getMaxLength(), expression.getScale(),
column.getMaxLength(), column.getScale())) {
throw new DataExceedsCapacityException(
column.getDataType(), column.getMaxLength(),
column.getScale(), column.getName().getString(), ptr);
}
column.getDataType().coerceBytes(ptr, null,
expression.getDataType(), expression.getMaxLength(),
expression.getScale(), expression.getSortOrder(),
column.getMaxLength(), column.getScale(),
column.getSortOrder(), projectedTable.rowKeyOrderOptimizable());
byte[] bytes = ByteUtil.copyKeyBytesIfNecessary(ptr);
row.setValue(column, bytes);
}
}
for (Mutation mutation : row.toRowMutations()) {
mutations.add(mutation);
}
for (i = 0; i < selectExpressions.size(); i++) {
selectExpressions.get(i).reset();
}
} else if (deleteCF != null && deleteCQ != null) {
// No need to search for delete column, since we project only it
// if no empty key value is being set
if (emptyCF == null ||
result.getValue(deleteCF, deleteCQ) != null) {
Delete delete = new Delete(results.get(0).getRowArray(),
results.get(0).getRowOffset(),
results.get(0).getRowLength());
delete.deleteColumns(deleteCF, deleteCQ, ts);
// force tephra to ignore this deletes
delete.setAttribute(TxConstants.TX_ROLLBACK_ATTRIBUTE_KEY, new byte[0]);
mutations.add(delete);
}
}
if (emptyCF != null) {
/*
* If we've specified an emptyCF, then we need to insert an empty
* key value "retroactively" for any key value that is visible at
* the timestamp that the DDL was issued. Key values that are not
* visible at this timestamp will not ever be projected up to
* scans past this timestamp, so don't need to be considered.
* We insert one empty key value per row per timestamp.
*/
Set<Long> timeStamps =
Sets.newHashSetWithExpectedSize(results.size());
for (Cell kv : results) {
long kvts = kv.getTimestamp();
if (!timeStamps.contains(kvts)) {
Put put = new Put(kv.getRowArray(), kv.getRowOffset(),
kv.getRowLength());
put.add(emptyCF, QueryConstants.EMPTY_COLUMN_BYTES, kvts,
ByteUtil.EMPTY_BYTE_ARRAY);
mutations.add(put);
}
}
// Commit in batches based on UPSERT_BATCH_SIZE_BYTES_ATTRIB in config
List<List<Mutation>> batchMutationList =
MutationState.getMutationBatchList(batchSize, batchSizeBytes, mutations);
for (List<Mutation> batchMutations : batchMutationList) {
commitBatch(region, batchMutations, indexUUID, blockingMemStoreSize, indexMaintainersPtr,
txState);
batchMutations.clear();
}
mutations.clear();
// Commit in batches based on UPSERT_BATCH_SIZE_BYTES_ATTRIB in config
List<List<Mutation>> batchIndexMutationList =
MutationState.getMutationBatchList(batchSize, batchSizeBytes, indexMutations);
for (List<Mutation> batchIndexMutations : batchIndexMutationList) {
commitBatch(region, batchIndexMutations, null, blockingMemStoreSize, null, txState);
batchIndexMutations.clear();
}
indexMutations.clear();
}
aggregators.aggregate(rowAggregators, result);
hasAny = true;
}
} while (hasMore);
if (!mutations.isEmpty()) {
commitBatch(region, mutations, indexUUID, blockingMemStoreSize, indexMaintainersPtr, txState);
}
if (!indexMutations.isEmpty()) {
commitBatch(region, indexMutations, null, blockingMemStoreSize, indexMaintainersPtr, txState);
indexMutations.clear();
}
}
} finally {
if(needToWrite) {
synchronized (lock) {
scansReferenceCount--;
}
}
try {
innerScanner.close();
} finally {
if (acquiredLock) region.closeRegionOperation();
}
}
if (logger.isDebugEnabled()) {
logger.debug(LogUtil.addCustomAnnotations("Finished scanning " + rowCount + " rows for ungrouped coprocessor scan " + scan, ScanUtil.getCustomAnnotations(scan)));
}
final boolean hadAny = hasAny;
KeyValue keyValue = null;
if (hadAny) {
byte[] value = aggregators.toBytes(rowAggregators);
keyValue = KeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY, SINGLE_COLUMN_FAMILY, SINGLE_COLUMN, AGG_TIMESTAMP, value, 0, value.length);
}
final KeyValue aggKeyValue = keyValue;
RegionScanner scanner = new BaseRegionScanner(innerScanner) {
private boolean done = !hadAny;
@Override
public boolean isFilterDone() {
return done;
}
@Override
public boolean next(List<Cell> results) throws IOException {
if (done) return false;
done = true;
results.add(aggKeyValue);
return false;
}
@Override
public long getMaxResultSize() {
return scan.getMaxResultSize();
}
};
return scanner;
}
#location 200
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public int newKey(ImmutableBytesWritable key, byte[][] values) {
int nValues = values.length;
while (nValues > 0 && (values[nValues-1] == null || values[nValues-1].length == 0)) {
nValues--;
}
int i = 0;
TrustedByteArrayOutputStream os = new TrustedByteArrayOutputStream(SchemaUtil.estimateKeyLength(this));
try {
Integer bucketNum = this.getBucketNum();
if (bucketNum != null) {
// Write place holder for salt byte
i++;
os.write(QueryConstants.SEPARATOR_BYTE_ARRAY);
}
List<PColumn> columns = getPKColumns();
int nColumns = columns.size();
PDataType type = null;
while (i < nValues && i < nColumns) {
// Separate variable length column values in key with zero byte
if (type != null && !type.isFixedWidth()) {
os.write(SEPARATOR_BYTE);
}
PColumn column = columns.get(i);
type = column.getDataType();
// This will throw if the value is null and the type doesn't allow null
byte[] byteValue = values[i++];
if (byteValue == null) {
byteValue = ByteUtil.EMPTY_BYTE_ARRAY;
}
// An empty byte array return value means null. Do this,
// since a type may have muliple representations of null.
// For example, VARCHAR treats both null and an empty string
// as null. This way we don't need to leak that part of the
// implementation outside of PDataType by checking the value
// here.
if (byteValue.length == 0 && !column.isNullable()) {
throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not be null");
}
Integer maxLength = column.getMaxLength();
if (maxLength != null && type.isFixedWidth() && byteValue.length <= maxLength) {
byteValue = StringUtil.padChar(byteValue, maxLength);
} else if (maxLength != null && byteValue.length > maxLength) {
throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not exceed " + maxLength + " bytes (" + SchemaUtil.toString(type, byteValue) + ")");
}
os.write(byteValue, 0, byteValue.length);
}
// If some non null pk values aren't set, then throw
if (i < nColumns) {
PColumn column = columns.get(i);
type = column.getDataType();
if (type.isFixedWidth() || !column.isNullable()) {
throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not be null");
}
}
if (nValues == 0) {
throw new ConstraintViolationException("Primary key may not be null ("+ name.getString() + ")");
}
byte[] buf = os.getBuffer();
int size = os.size();
if (bucketNum != null) {
buf[0] = SaltingUtil.getSaltingByte(buf, 1, size-1, bucketNum);
}
key.set(buf,0,size);
return i;
} finally {
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e); // Impossible
}
}
}
|
#vulnerable code
@Override
public int newKey(ImmutableBytesWritable key, byte[][] values) {
int nValues = values.length;
while (nValues > 0 && (values[nValues-1] == null || values[nValues-1].length == 0)) {
nValues--;
}
int i = 0;
TrustedByteArrayOutputStream os = new TrustedByteArrayOutputStream(SchemaUtil.estimateKeyLength(this));
try {
Integer bucketNum = this.getBucketNum();
if (bucketNum != null) {
// Write place holder for salt byte
i++;
os.write(QueryConstants.SEPARATOR_BYTE_ARRAY);
}
List<PColumn> columns = getPKColumns();
int nColumns = columns.size();
PDataType type = null;
while (i < nValues && i < nColumns) {
// Separate variable length column values in key with zero byte
if (type != null && !type.isFixedWidth()) {
os.write(SEPARATOR_BYTE);
}
PColumn column = columns.get(i);
type = column.getDataType();
// This will throw if the value is null and the type doesn't allow null
byte[] byteValue = values[i++];
if (byteValue == null) {
byteValue = ByteUtil.EMPTY_BYTE_ARRAY;
}
// An empty byte array return value means null. Do this,
// since a type may have muliple representations of null.
// For example, VARCHAR treats both null and an empty string
// as null. This way we don't need to leak that part of the
// implementation outside of PDataType by checking the value
// here.
if (byteValue.length == 0 && !column.isNullable()) {
throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not be null");
}
Integer maxLength = column.getMaxLength();
if (maxLength != null && type.isFixedWidth() && byteValue.length <= maxLength) {
byteValue = StringUtil.padChar(byteValue, maxLength);
} else if (maxLength != null && byteValue.length > maxLength) {
throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not exceed " + maxLength + " bytes (" + SchemaUtil.toString(type, byteValue) + ")");
}
os.write(byteValue, 0, byteValue.length);
}
// If some non null pk values aren't set, then throw
if (i < nColumns) {
PColumn column = columns.get(i);
type = column.getDataType();
if (type.isFixedWidth() || !column.isNullable()) {
throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not be null");
}
}
byte[] buf = os.getBuffer();
int size = os.size();
if (bucketNum != null) {
buf[0] = SaltingUtil.getSaltingByte(buf, 1, size-1, bucketNum);
}
key.set(buf,0,size);
return i;
} finally {
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e); // Impossible
}
}
}
#location 59
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public byte[] getViewIndexIdFromIndexRowKey(ImmutableBytesWritable indexRowKeyPtr) {
assert (isLocalIndex);
ImmutableBytesPtr ptr =
new ImmutableBytesPtr(indexRowKeyPtr.get(),( indexRowKeyPtr.getOffset()
+ (nIndexSaltBuckets > 0 ? 1 : 0)), viewIndexId.length);
return ptr.copyBytesIfNecessary();
}
|
#vulnerable code
public byte[] getViewIndexIdFromIndexRowKey(ImmutableBytesWritable indexRowKeyPtr) {
assert(isLocalIndex);
RowKeySchema indexRowKeySchema = getIndexRowKeySchema();
// TODO add logic to skip region start key as well because we cannot find the region startkey in indexhalfstorefilereader.
ImmutableBytesWritable ptr = new ImmutableBytesWritable();
TrustedByteArrayOutputStream stream =
new TrustedByteArrayOutputStream(estimatedIndexRowKeyBytes);
DataOutput output = new DataOutputStream(stream);
try {
int indexPosOffset = (!isLocalIndex && nIndexSaltBuckets > 0 ? 1 : 0) + (isMultiTenant ? 1 : 0) + (viewIndexId == null ? 0 : 1);
Boolean hasValue =
indexRowKeySchema.iterator(indexRowKeyPtr, ptr, indexPosOffset);
if (Boolean.TRUE.equals(hasValue)) {
output.write(ptr.get(), ptr.getOffset(), ptr.getLength());
}
int length = stream.size();
byte[] dataRowKey = stream.getBuffer();
return dataRowKey.length == length ? dataRowKey : Arrays.copyOf(dataRowKey, length);
} catch (IOException e) {
throw new RuntimeException(e); // Impossible
} finally {
try {
stream.close();
} catch (IOException e) {
throw new RuntimeException(e); // Impossible
}
}
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean seekOrReseek(Cell cell, boolean isSeek) throws IOException{
Cell keyToSeek = cell;
KeyValue splitKeyValue = new KeyValue.KeyOnlyKeyValue(reader.getSplitkey());
if (reader.isTop()) {
if(this.comparator.compare(cell, splitKeyValue, true) < 0){
if(!isSeek && realSeekDone()) {
return true;
}
return seekOrReseekToProperKey(isSeek, keyToSeek);
}
keyToSeek = getKeyPresentInHFiles(cell);
return seekOrReseekToProperKey(isSeek, keyToSeek);
} else {
if (this.comparator.compare(cell, splitKeyValue, true) >= 0) {
close();
return false;
}
if(!isSeek && reader.getRegionInfo().getStartKey().length == 0 && reader.getSplitRow().length > reader.getRegionStartKeyInHFile().length) {
keyToSeek = getKeyPresentInHFiles(cell);
}
}
return seekOrReseekToProperKey(isSeek, keyToSeek);
}
|
#vulnerable code
public boolean seekOrReseek(Cell cell, boolean isSeek) throws IOException{
KeyValue kv = PhoenixKeyValueUtil.maybeCopyCell(cell);
KeyValue keyToSeek = kv;
KeyValue splitKeyValue = KeyValueUtil.createKeyValueFromKey(reader.getSplitkey());
if (reader.isTop()) {
if(getComparator().compare(kv, splitKeyValue) < 0){
if(!isSeek && realSeekDone()) {
return true;
}
return seekOrReseekToProperKey(isSeek, keyToSeek);
}
keyToSeek = getKeyPresentInHFiles(kv.getRowArray());
return seekOrReseekToProperKey(isSeek, keyToSeek);
} else {
if (getComparator().compare(kv, splitKeyValue) >= 0) {
close();
return false;
}
if(!isSeek && reader.getRegionInfo().getStartKey().length == 0 && reader.getSplitRow().length > reader.getRegionStartKeyInHFile().length) {
keyToSeek = getKeyPresentInHFiles(kv.getRowArray());
}
}
return seekOrReseekToProperKey(isSeek, keyToSeek);
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void lookup()
{
myMethods = lookupMethods();
}
|
#vulnerable code
@Override
public void lookup()
{
ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup();
ClassFile otherClass = group.findClass(method.getClassEntry().getName());
if (otherClass == null)
return; // not our class
// when I recompile classes I can see the class of invokevirtuals methods change, get all methods
//List<net.runelite.deob.Method> list = new ArrayList<>();
//findMethodFromClass(new HashSet<>(), list, otherClass);
net.runelite.deob.Method m = otherClass.findMethodDeep(method.getNameAndType());
if (m == null)
{
return;
}
myMethods = Renamer.getVirutalMethods(m);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run(ClassGroup one, ClassGroup two)
{
eone = new Execution(one);
eone.populateInitialMethods();
List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
eone.run();
etwo = new Execution(two);
etwo.populateInitialMethods();
List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
etwo.run();
assert initial1.size() == initial2.size();
for (int i = 0; i < initial1.size(); ++i)
{
Method m1 = initial1.get(i), m2 = initial2.get(i);
assert m1.getName().equals(m2.getName());
objMap.put(m1, m2);
}
// process(
// initial1.get(0).getMethod(),
// initial2.get(0).getMethod()
// );
// processed.add(initial1.get(0).getMethod());
// process(
// one.findClass("class143").findMethod("run"),
// two.findClass("class143").findMethod("run")
// );
// processed.add(one.findClass("client").findMethod("init"));
for (;;)
{
Optional next = objMap.keySet().stream()
.filter(m -> !processed.contains(m))
.findAny();
if (!next.isPresent())
break;
Method m = (Method) next.get();
Method m2 = (Method) objMap.get(m);
System.out.println("Scanning " + m.getName() + " -> " + m2.getName());
process(m, m2);
processed.add(m);
}
for (Entry<Object, Object> e : objMap.entrySet())
{
Method m1 = (Method) e.getKey();
Method m2 = (Method) e.getValue();
System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
}
System.out.println("done count " + objMap.size());
}
|
#vulnerable code
public void run(ClassGroup one, ClassGroup two)
{
eone = new Execution(one);
eone.populateInitialMethods();
List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
eone.run();
etwo = new Execution(two);
etwo.populateInitialMethods();
List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
etwo.run();
assert initial1.size() == initial2.size();
for (int i = 0; i < initial1.size(); ++i)
{
Method m1 = initial1.get(i), m2 = initial2.get(i);
objMap.put(m1, m2);
}
// process(
// initial1.get(0).getMethod(),
// initial2.get(0).getMethod()
// );
// processed.add(initial1.get(0).getMethod());
process(
one.findClass("class143").findMethod("run"),
two.findClass("class143").findMethod("run")
);
// processed.add(one.findClass("client").findMethod("init"));
// for (;;)
// {
// Optional next = objMap.keySet().stream()
// .filter(m -> !processed.contains(m))
// .findAny();
// if (!next.isPresent())
// break;
//
// Method m = (Method) next.get();
// Method m2 = (Method) objMap.get(m);
//
// System.out.println("Scanning " + m.getName() + " -> " + m2.getName());
// process(m, m2);
// processed.add(m);
// }
for (Entry<Object, Object> e : objMap.entrySet())
{
Method m1 = (Method) e.getKey();
Method m2 = (Method) e.getValue();
System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
}
System.out.println("done");
}
#location 28
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void renameField(net.runelite.deob.Field f, Field newField)
{
net.runelite.deob.Field f2 = getMyField();
if (f2 == f)
field = newField;
}
|
#vulnerable code
@Override
public void renameField(net.runelite.deob.Field f, Field newField)
{
Class clazz = field.getClassEntry();
NameAndType nat = field.getNameAndType();
ClassFile cf = this.getInstructions().getCode().getAttributes().getClassFile().getGroup().findClass(clazz.getName());
if (cf == null)
return;
net.runelite.deob.Field f2 = cf.findFieldDeep(nat);
assert f2 != null;
if (f2 == f)
field = newField;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store(folder.getRoot());
DataFile df = new DataFile(store, 42, file);
int sector = df.write(3, ByteBuffer.wrap("test".getBytes()));
ByteBuffer buf = df.read(3, sector, 4);
String str = new String(buf.array());
Assert.assertEquals("test", str);
file.delete();
}
|
#vulnerable code
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store();
DataFile df = new DataFile(store, 42, file);
int sector = df.write(3, ByteBuffer.wrap("test".getBytes()));
ByteBuffer buf = df.read(3, sector, 4);
String str = new String(buf.array());
Assert.assertEquals("test", str);
file.delete();
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void buildInstructionGraph()
{
net.runelite.deob.Field f = getMyField();
if (f != null)
f.addReference(this);
}
|
#vulnerable code
@Override
public void buildInstructionGraph()
{
Class clazz = field.getClassEntry();
NameAndType nat = field.getNameAndType();
ClassFile cf = this.getInstructions().getCode().getAttributes().getClassFile().getGroup().findClass(clazz.getName());
if (cf == null)
return;
net.runelite.deob.Field f = cf.findFieldDeep(nat);
assert f != null;
f.addReference(this);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run(ClassGroup one, ClassGroup two)
{
eone = new Execution(one);
eone.populateInitialMethods();
List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
eone.run();
etwo = new Execution(two);
etwo.populateInitialMethods();
List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
etwo.run();
assert initial1.size() == initial2.size();
for (int i = 0; i < initial1.size(); ++i)
{
Method m1 = initial1.get(i), m2 = initial2.get(i);
objMap.put(m1, m2);
}
// process(
// initial1.get(0).getMethod(),
// initial2.get(0).getMethod()
// );
// processed.add(initial1.get(0).getMethod());
process(
one.findClass("class143").findMethod("run"),
two.findClass("class143").findMethod("run")
);
// processed.add(one.findClass("client").findMethod("init"));
// for (;;)
// {
// Optional next = objMap.keySet().stream()
// .filter(m -> !processed.contains(m))
// .findAny();
// if (!next.isPresent())
// break;
//
// Method m = (Method) next.get();
// Method m2 = (Method) objMap.get(m);
//
// System.out.println("Scanning " + m.getName() + " -> " + m2.getName());
// process(m, m2);
// processed.add(m);
// }
for (Entry<Object, Object> e : objMap.entrySet())
{
Method m1 = (Method) e.getKey();
Method m2 = (Method) e.getValue();
System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
}
System.out.println("done");
}
|
#vulnerable code
public void run(ClassGroup one, ClassGroup two)
{
eone = new Execution(one);
eone.populateInitialMethods();
eone.run();
etwo = new Execution(two);
etwo.populateInitialMethods();
etwo.run();
process(
one.findClass("client").findMethod("init"),
two.findClass("client").findMethod("init")
);
System.out.println("done");
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void renameField(net.runelite.deob.Field f, Field newField)
{
net.runelite.deob.Field f2 = getMyField();
if (f2 == f)
{
field = newField;
}
}
|
#vulnerable code
@Override
public void renameField(net.runelite.deob.Field f, Field newField)
{
Class clazz = field.getClassEntry();
NameAndType nat = field.getNameAndType();
ClassFile cf = this.getInstructions().getCode().getAttributes().getClassFile().getGroup().findClass(clazz.getName());
if (cf == null)
return;
net.runelite.deob.Field f2 = cf.findFieldDeep(nat);
assert f2 != null;
if (f2 == f)
{
field = newField;
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void test2() throws IOException
{
byte[] b = new byte[1024];
for (int i = 0; i < 1024; ++i)
b[i] = (byte) i;
File file = folder.newFile();
Store store = new Store(folder.getRoot());
DataFile df = new DataFile(store, file);
DataFileWriteResult res = df.write(42, 0x1FFFF, ByteBuffer.wrap(b), 0, 0);
DataFileReadResult res2 = df.read(42, 0x1FFFF, res.sector, res.compressedLength);
byte[] buf = res2.data;
Assert.assertArrayEquals(b, buf);
file.delete();
}
|
#vulnerable code
@Test
public void test2() throws IOException
{
byte[] b = new byte[1024];
for (int i = 0; i < 1024; ++i) b[i] = (byte) i;
File file = folder.newFile();
Store store = new Store(folder.getRoot());
DataFile df = new DataFile(store, file);
int sector = df.write(42, 0x1FFFF, ByteBuffer.wrap(b));
byte[] buf = df.read(42, 0x1FFFF, sector, b.length);
Assert.assertArrayEquals(b, buf);
file.delete();
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public NameMappings run(ClassGroup one, ClassGroup two)
{
Execution eone = new Execution(one);
eone.setBuildGraph(true);
eone.populateInitialMethods();
eone.run();
Execution etwo = new Execution(two);
etwo.setBuildGraph(true);
etwo.populateInitialMethods();
etwo.run();
g1 = eone.getGraph();
g2 = etwo.getGraph();
System.out.println(eone.getGraph());
System.out.println(etwo.getGraph());
for (int i = 0; i < 250; ++i)
{
ClassFile c1 = one.findClass("class" + i);
ClassFile c2 = two.findClass("class" + i);
if (c1 == null || c2 == null)
continue;
//Map m1 = this.find(c1);
//Map m2 = this.find(c2);
// mapClassMethods(m1, m2);
mapDeobfuscatedMethods(c1, c2);
}
ClassFile cf1 = one.findClass("client"), cf2 = two.findClass("client");
mapDeobfuscatedMethods(cf1, cf2);
// List<Field> fl1 = getClientFields(one, eone);
// List<Field> fl2 = getClientFields(two, etwo);
//
// for (int i = 0; i < Math.min(fl1.size(), fl2.size()); ++i)
// {
// Field f1 = fl1.get(i), f2 = fl2.get(i);
//
// Vertex v1 = g1.getVertexFor(f1);
// Vertex v2 = g2.getVertexFor(f2);
//
// v1.is(v2);
// v2.is(v1);
//
// System.out.println(fname(f1) + " is " + fname(f2));
// }
System.out.println("g1 verticies " + g1.getVerticies().size() + " reachable " + g1.reachableVerticiesFromSolvedVerticies().size());
Set<Vertex> reachable = g1.reachableVerticiesFromSolvedVerticies();
for (Vertex v : g1.getVerticies())
if (!reachable.contains(v))
{
System.out.println("unreachable " + v);
}
for (;;)
{
int before = g1.solved(null);
System.out.println("Before " + before);
solve();
g1.getVerticies().forEach(v -> v.finish());
//g2
int after = g1.solved(null);
System.out.println("After " + after);
if (before == after)
break;
}
g1.check();
g2.check();
System.out.println("methods " +g1.solved(VertexType.METHOD));
System.out.println("f " +g1.solved(VertexType.FIELD));
Vertex stored = null;
for (Vertex v : g1.getVerticies())
{
if (v.getOther() == null)
continue;
if (!v.toString().equals("Vertex{object=class0.<init>()V}"))
continue;
assert stored == null;
stored = v;
for (Edge e : v.getEdges())
{
if (e.getTo().getOther() == null)
{
System.out.println("Edge " + e + " on vertex " + v + " is unsolved");
}
}
}
// NameMappings col = buildCollisionMap(one, two);
// rename(col, two);
//
// NameMappings mappings = buildMappings(one, two); // two -> one
//
// show(mappings);
System.out.println("Solved methods "+ g1.solved(VertexType.METHOD) + ", solved fields " + g1.solved(VertexType.FIELD) + ", total " + g1.getVerticies().size());
//rename(mappings, two);
try
{
JarUtil.saveJar(two, new File("/Users/adam/w/rs/07/adamout.jar"));
}
catch (IOException ex)
{
Logger.getLogger(Rename2.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
|
#vulnerable code
public NameMappings run(ClassGroup one, ClassGroup two)
{
Execution eone = new Execution(one);
eone.setBuildGraph(true);
eone.populateInitialMethods();
eone.run();
Execution etwo = new Execution(two);
etwo.setBuildGraph(true);
etwo.populateInitialMethods();
etwo.run();
g1 = eone.getGraph();
g2 = etwo.getGraph();
System.out.println(eone.getGraph());
System.out.println(etwo.getGraph());
for (int i = 0; i < 250; ++i)
//for (int i = 0; i < Math.min(one.getClasses().size(), two.getClasses().size()); ++i)
{
ClassFile c1 = one.findClass("class" + i);
ClassFile c2 = two.findClass("class" + i);
if (c1 == null || c2 == null)
continue;
//Map m1 = this.find(c1);
//Map m2 = this.find(c2);
// mapClassMethods(m1, m2);
mapDeobfuscatedMethods(c1, c2);
}
ClassFile cf1 = one.findClass("client"), cf2 = two.findClass("client");
mapDeobfuscatedMethods(cf1, cf2);
//List<Field> fl1 = getClientFields(one, eone);
//List<Field> fl2 = getClientFields(two, etwo);
// for (int i = 0; i < Math.min(fl1.size(), fl2.size()); ++i)
// {
// Field f1 = fl1.get(i), f2 = fl2.get(i);
//
// Vertex v1 = g1.getVertexFor(f1);
// Vertex v2 = g2.getVertexFor(f2);
//
// v1.is(v2);
// v2.is(v1);
//
// System.out.println(fname(f1) + " is " + fname(f2));
// }
System.out.println("g1 verticies " + g1.getVerticies().size() + " reachable " + g1.reachableVerticiesFromSolvedVerticies().size());
Set<Vertex> reachable = g1.reachableVerticiesFromSolvedVerticies();
for (Vertex v : g1.getVerticies())
if (!reachable.contains(v))
{
System.out.println("unreachable " + v);
}
for (;;)
{
int before = g1.solved(null);
System.out.println("Before " + before);
solve();
g1.getVerticies().forEach(v -> v.finish());
//g2
int after = g1.solved(null);
System.out.println("After " + after);
if (before == after)
break;
}
g1.check();
g2.check();
System.out.println("methods " +g1.solved(VertexType.METHOD));
System.out.println("f " +g1.solved(VertexType.FIELD));
Vertex stored = null;
for (Vertex v : g1.getVerticies())
{
if (v.getOther() == null)
continue;
if (!v.toString().equals("Vertex{object=class0.<init>()V}"))
continue;
assert stored == null;
stored = v;
for (Edge e : v.getEdges())
{
if (e.getTo().getOther() == null)
{
System.out.println("Edge " + e + " on vertex " + v + " is unsolved");
}
}
}
// NameMappings col = buildCollisionMap(one, two);
// rename(col, two);
//
// NameMappings mappings = buildMappings(one, two); // two -> one
//
// show(mappings);
System.out.println("Solved methods "+ g1.solved(VertexType.METHOD) + ", total " + g1.getVerticies().size());
//rename(mappings, two);
try
{
JarUtil.saveJar(two, new File("/Users/adam/w/rs/07/adamout.jar"));
}
catch (IOException ex)
{
Logger.getLogger(Rename2.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
#location 37
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<net.runelite.deob.Method> getMethods()
{
return myMethods != null ? myMethods : Arrays.asList();
}
|
#vulnerable code
@Override
public List<net.runelite.deob.Method> getMethods()
{
ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup();
ClassFile otherClass = group.findClass(method.getClassEntry().getName());
if (otherClass == null)
return new ArrayList<>(); // not our class
// look up this method in this class and anything that inherits from it
List<net.runelite.deob.Method> list = new ArrayList<>();
findMethodFromClass(list, otherClass);
return list;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<net.runelite.deob.Method> getMethods()
{
return myMethods != null ? myMethods : Arrays.asList();
}
|
#vulnerable code
@Override
public List<net.runelite.deob.Method> getMethods()
{
ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup();
ClassFile otherClass = group.findClass(method.getClassEntry().getName());
if (otherClass == null)
return new ArrayList<>(); // not our class
// look up this method in this class and anything that inherits from it
List<net.runelite.deob.Method> list = new ArrayList<>();
findMethodFromClass(list, otherClass);
return list;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store(folder.getRoot());
IndexFile index = new IndexFile(store, 5, file);
IndexEntry entry = new IndexEntry(index, 7, 8, 9);
index.write(entry);
IndexEntry entry2 = index.read(7);
Assert.assertEquals(entry, entry2);
}
|
#vulnerable code
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store();
IndexFile index = new IndexFile(store, 5, file);
IndexEntry entry = new IndexEntry(index, 7, 8, 9);
index.write(entry);
IndexEntry entry2 = index.read(7);
Assert.assertEquals(entry, entry2);
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void lookup()
{
myMethod = lookupMethod();
}
|
#vulnerable code
@Override
public void lookup()
{
ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup();
ClassFile otherClass = group.findClass(method.getClassEntry().getName());
if (otherClass == null)
return; // not our class
net.runelite.deob.Method other = otherClass.findMethodDeepStatic(method.getNameAndType());
assert other != null;
List<net.runelite.deob.Method> list = new ArrayList<>();
list.add(other);
myMethods = list;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run(ClassGroup one, ClassGroup two)
{
groupOne = one;
groupTwo = two;
Execution eone = new Execution(one);
eone.setBuildGraph(true);
eone.setFollowInvokes(false);
eone.populateInitialMethods();
List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
eone.run();
Execution etwo = new Execution(two);
etwo.setBuildGraph(true);
etwo.setFollowInvokes(false);
etwo.populateInitialMethods();
List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
etwo.run();
assert initial1.size() == initial2.size();
for (int i = 0; i < initial1.size(); ++i)
{
Method m1 = initial1.get(i), m2 = initial2.get(i);
assert m1.getName().equals(m2.getName());
objMap.put(m1, m2);
}
// process(
// one.findClass("class143").findMethod("method3014"),
// two.findClass("class143").findMethod("method2966")
// );
for (;;)
{
Optional next = objMap.keySet().stream()
.filter(m -> !processed.contains(m))
.findAny();
if (!next.isPresent())
break;
Method m = (Method) next.get();
Method m2 = (Method) objMap.get(m);
if (m.getCode() == null || m2.getCode() == null)
{
processed.add(m);
continue;
}
System.out.println("Scanning " + m.getMethods().getClassFile().getName() + "." + m.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
process(m, m2);
processed.add(m);
}
for (Entry<Object, Object> e : objMap.entrySet())
{
Method m1 = (Method) e.getKey();
Method m2 = (Method) e.getValue();
System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
}
System.out.println("done count " + objMap.size());
}
|
#vulnerable code
public void run(ClassGroup one, ClassGroup two)
{
groupOne = one;
groupTwo = two;
// Execution eone = new Execution(one);
// eone.setBuildGraph(true);
// eone.setFollowInvokes(false);
// eone.populateInitialMethods();
// List<Method> initial1 = eone.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
// eone.run();
//
// Execution etwo = new Execution(two);
// etwo.setBuildGraph(true);
// etwo.setFollowInvokes(false);
// etwo.populateInitialMethods();
// List<Method> initial2 = etwo.getInitialMethods().stream().sorted((m1, m2) -> m1.getName().compareTo(m2.getName())).collect(Collectors.toList());
// etwo.run();
//
// assert initial1.size() == initial2.size();
//
// for (int i = 0; i < initial1.size(); ++i)
// {
// Method m1 = initial1.get(i), m2 = initial2.get(i);
//
// assert m1.getName().equals(m2.getName());
//
// objMap.put(m1, m2);
// }
process(
one.findClass("class143").findMethod("method3014"),
two.findClass("class143").findMethod("method2966")
);
for (;;)
{
Optional next = objMap.keySet().stream()
.filter(m -> !processed.contains(m))
.findAny();
if (!next.isPresent())
break;
Method m = (Method) next.get();
Method m2 = (Method) objMap.get(m);
if (m.getCode() == null || m2.getCode() == null)
{
processed.add(m);
continue;
}
System.out.println("Scanning " + m.getMethods().getClassFile().getName() + "." + m.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
process(m, m2);
processed.add(m);
}
for (Entry<Object, Object> e : objMap.entrySet())
{
Method m1 = (Method) e.getKey();
Method m2 = (Method) e.getValue();
System.out.println("FINAL " + m1.getMethods().getClassFile().getName() + "." + m1.getName() + " -> " + m2.getMethods().getClassFile().getName() + "." + m2.getName());
}
System.out.println("done count " + objMap.size());
}
#location 32
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store(folder.getRoot());
DataFile df = new DataFile(store, file);
DataFileWriteResult res = df.write(42, 3, ByteBuffer.wrap("test".getBytes()), 0, 0);
DataFileReadResult res2 = df.read(42, 3, res.sector, res.compressedLength);
byte[] buf = res2.data;
String str = new String(buf);
Assert.assertEquals("test", str);
file.delete();
}
|
#vulnerable code
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store(folder.getRoot());
DataFile df = new DataFile(store, file);
int sector = df.write(42, 3, ByteBuffer.wrap("test".getBytes()));
byte[] buf = df.read(42, 3, sector, 4);
String str = new String(buf);
Assert.assertEquals("test", str);
file.delete();
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void lookup()
{
myMethods = lookupMethods();
}
|
#vulnerable code
@Override
public void lookup()
{
ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup();
ClassFile otherClass = group.findClass(method.getClassEntry().getName());
if (otherClass == null)
return; // not our class
// look up this method in this class and anything that inherits from it
//List<net.runelite.deob.Method> list = new ArrayList<>();
//findMethodFromClass(list, otherClass);
myMethods = Renamer.getVirutalMethods(otherClass.findMethod(method.getNameAndType()));
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<net.runelite.deob.Method> getMethods()
{
return myMethods != null ? myMethods : Arrays.asList();
}
|
#vulnerable code
@Override
public List<net.runelite.deob.Method> getMethods()
{
ClassGroup group = this.getInstructions().getCode().getAttributes().getClassFile().getGroup();
ClassFile otherClass = group.findClass(method.getClassEntry().getName());
if (otherClass == null)
return new ArrayList<>(); // not our class
net.runelite.deob.Method other = otherClass.findMethodDeepStatic(method.getNameAndType());
assert other != null;
List<net.runelite.deob.Method> list = new ArrayList<>();
list.add(other);
return list;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void run()
{
for (ClassFile cf : deobfuscated.getClasses())
{
Annotations an = cf.getAttributes().getAnnotations();
if (an == null)
continue;
String obfuscatedName = cf.getName();
Annotation obfuscatedNameAnnotation = an.find(OBFUSCATED_NAME);
if (obfuscatedNameAnnotation != null)
obfuscatedName = obfuscatedNameAnnotation.getElement().getString();
ClassFile other = vanilla.findClass(obfuscatedName);
assert other != null;
java.lang.Class implementingClass = injectInterface(cf, other);
if (implementingClass == null)
continue;
for (Field f : cf.getFields().getFields())
{
an = f.getAttributes().getAnnotations();
if (an.find(EXPORT) == null)
continue; // not an exported field
String exportedName = an.find(EXPORT).getElement().getString();
obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString();
Annotation getterAnnotation = an.find(OBFUSCATED_GETTER);
Number getter = null;
if (getterAnnotation != null)
getter = (Number) getterAnnotation.getElement().getValue().getObject();
// the ob jar is the same as the vanilla so this field must exist in this class.
Type obType = toObType(f.getType());
Field otherf = other.findField(new NameAndType(obfuscatedName, obType));
assert otherf != null;
assert f.isStatic() == otherf.isStatic();
ClassFile targetClass = f.isStatic() ? vanilla.findClass("client") : other; // target class for getter
java.lang.Class targetApiClass = f.isStatic() ? clientClass : implementingClass; // target api class for getter
java.lang.reflect.Method apiMethod = findImportMethodOnApi(targetApiClass, exportedName);
if (apiMethod == null)
{
System.out.println("no api method");
continue;
}
injectGetter(targetClass, apiMethod, otherf, getter);
}
for (Method m : cf.getMethods().getMethods())
{
an = m.getAttributes().getAnnotations();
if (an == null || an.find(EXPORT) == null)
continue; // not an exported method
// XXX static methods can be in any class not just 'other' so the below finding won't work.
// XXX static methods can also be totally inlined by the obfuscator and thus removed by the dead code remover,
// so exporting them maybe wouldn't work anyway?
assert !m.isStatic();
String exportedName = an.find(EXPORT).getElement().getString();
obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString();
Method otherm;
Annotation obfuscatedSignature = an.find(OBFUSCATED_SIGNATURE);
String garbage = null;
if (obfuscatedSignature != null)
{
String signatureString = obfuscatedSignature.getElements().get(0).getString();
garbage = obfuscatedSignature.getElements().get(1).getString();
Signature signature = new Signature(signatureString); // parse signature
// The obfuscated signature annotation is generated post rename unique, so class
// names in the signature match our class names and not theirs, so we toObSignature() it
otherm = other.findMethod(new NameAndType(obfuscatedName, toObSignature(signature)));
}
else
{
// No obfuscated signature annotation, so the annotation wasn't changed during deobfuscation.
// We should be able to just find it normally.
otherm = other.findMethod(new NameAndType(obfuscatedName, toObSignature(m.getDescriptor())));
}
assert otherm != null;
java.lang.reflect.Method apiMethod = findImportMethodOnApi(implementingClass, exportedName); // api method to invoke 'otherm'
if (apiMethod == null)
{
System.out.println("no api method");
continue;
}
injectInvoker(other, apiMethod, m, otherm, garbage);
}
}
}
|
#vulnerable code
public void run()
{
for (ClassFile cf : deobfuscated.getClasses())
{
Annotations an = cf.getAttributes().getAnnotations();
String obfuscatedName = cf.getName();
Annotation obfuscatedNameAnnotation = an.find(OBFUSCATED_NAME);
if (obfuscatedNameAnnotation != null)
obfuscatedName = obfuscatedNameAnnotation.getElement().getString();
ClassFile other = vanilla.findClass(obfuscatedName);
assert other != null;
java.lang.Class implementingClass = injectInterface(cf, other);
if (implementingClass == null)
continue;
for (Field f : cf.getFields().getFields())
{
an = f.getAttributes().getAnnotations();
if (an.find(EXPORT) == null)
continue; // not an exported field
String exportedName = an.find(EXPORT).getElement().getString();
obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString();
Annotation getterAnnotation = an.find(OBFUSCATED_GETTER);
Number getter = null;
if (getterAnnotation != null)
getter = (Number) getterAnnotation.getElement().getValue().getObject();
// the ob jar is the same as the vanilla so this field must exist in this class.
Type obType = toObType(f.getType());
Field otherf = other.findField(new NameAndType(obfuscatedName, obType));
if (otherf == null)
otherf = other.findField(new NameAndType(obfuscatedName, obType));
assert otherf != null;
assert f.isStatic() == otherf.isStatic();
//
ClassFile targetClass = f.isStatic() ? vanilla.findClass("client") : other; // target class for getter
java.lang.Class targetApiClass = f.isStatic() ? clientClass : implementingClass; // target api class for getter
java.lang.reflect.Method apiMethod = findImportMethodOnApi(targetApiClass, exportedName);
if (apiMethod == null)
{
System.out.println("no api method");
continue;
}
injectGetter(targetClass, apiMethod, otherf, getter);
}
for (Method m : cf.getMethods().getMethods())
{
an = m.getAttributes().getAnnotations();
if (an == null || an.find(EXPORT) == null)
continue; // not an exported method
String exportedName = an.find(EXPORT).getElement().getString();
obfuscatedName = an.find(OBFUSCATED_NAME).getElement().getString();
// XXX static methods don't have to be in the same class, so we should have @ObfuscatedClass or something
Method otherm = other.findMethod(new NameAndType(obfuscatedName, toObSignature(m.getDescriptor())));
assert otherm != null;
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private ParallelExecutorMapping mapStaticMethods(ClassGroup one, ClassGroup two)
{
StaticMethodSignatureMapper smsm = new StaticMethodSignatureMapper();
smsm.map(one, two);
List<ParallelExecutorMapping> pmes = new ArrayList<>();
for (Method m : smsm.getMap().keySet())
{
Collection<Method> methods = smsm.getMap().get(m);
ExecutionMapper em = new ExecutionMapper(m, methods);
ParallelExecutorMapping mapping = em.run();
if (mapping == null)
continue;
mapping.map(mapping.m1, mapping.m2);
pmes.add(mapping);
}
ParallelExecutorMapping finalm = new ParallelExecutorMapping(one, two);
for (ParallelExecutorMapping pme : pmes)
finalm.merge(pme);
return finalm;
}
|
#vulnerable code
private ParallelExecutorMapping mapStaticMethods(ClassGroup one, ClassGroup two)
{
StaticMethodSignatureMapper smsm = new StaticMethodSignatureMapper();
smsm.map(one, two);
List<ParallelExecutorMapping> pmes = new ArrayList<>();
for (Method m : smsm.getMap().keySet())
{
Collection<Method> methods = smsm.getMap().get(m);
ExecutionMapper em = new ExecutionMapper(m, methods);
ParallelExecutorMapping mapping = em.run();
mapping.map(mapping.m1, mapping.m2);
pmes.add(mapping);
}
ParallelExecutorMapping finalm = new ParallelExecutorMapping(one, two);
for (ParallelExecutorMapping pme : pmes)
finalm.merge(pme);
return finalm;
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run(ClassGroup group)
{
this.group = group;
group.buildClassGraph();
execution = new Execution(group);
execution.populateInitialMethods();
Encryption encr = new Encryption();
execution.setEncryption(encr);
execution.run();
encr.doChange();
// findUses();
//
// Field f = group.findClass("class41").findField("field1170");
// calculate(f);
}
|
#vulnerable code
@Override
public void run(ClassGroup group)
{
this.group = group;
group.buildClassGraph();
execution = new Execution(group);
execution.populateInitialMethods();
execution.run();
findUses();
Field f = group.findClass("class41").findField("field1170");
calculate(f);
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) {
Socket socket = null;
InputStream inputStream = null;
OutputStream outputStream = null;
StringBuffer response = null;
byte[] buffer = new byte[2048];
int length = 0;
SocksProxy proxy1 = new Socks5(new InetSocketAddress("localhost", 1080));
proxy1.setCredentials(new UsernamePasswordCredentials("socks", "1234"));
SocksProxy proxy2 = new Socks5(new InetSocketAddress("localhost", 1081));
proxy2.setCredentials(new UsernamePasswordCredentials("socks", "1234"));
SocksProxy proxy3 = new Socks5(new InetSocketAddress("localhost", 1082));
proxy3.setCredentials(new UsernamePasswordCredentials("socks", "1234"));
proxy1.setChainProxy(proxy2.setChainProxy(proxy3));
System.out.println("USE proxy:"+proxy1);
try {
socket = new SocksSocket(proxy1);
socket.connect(new InetSocketAddress("whois.internic.net", 43));
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("domain google.com\r\n");
printWriter.flush();
length = 0;
response = new StringBuffer();
while ((length = inputStream.read(buffer)) > 0) {
response.append(new String(buffer, 0, length));
}
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
ResourceUtil.close(inputStream, outputStream, socket);
}
}
|
#vulnerable code
public static void main(String[] args) {
SocksProxy proxy1 = new Socks5(new InetSocketAddress("localhost", 1080));
proxy1.setCredentials(new UsernamePasswordCredentials("socks", "1234"));
SocksProxy proxy2 = new Socks5(new InetSocketAddress("localhost", 1081));
proxy2.setCredentials(new UsernamePasswordCredentials("socks", "1234"));
SocksProxy proxy3 = new Socks5(new InetSocketAddress("localhost", 1082));
proxy3.setCredentials(new UsernamePasswordCredentials("socks", "1234"));
proxy1.setChainProxy(proxy2.setChainProxy(proxy3.setChainProxy(proxy1.copy().setChainProxy(
proxy2.copy()))));
try {
@SuppressWarnings("resource")
Socket socket = new SocksSocket(proxy1);
socket.connect(new InetSocketAddress("whois.internic.net", 43));
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("domain google.com\r\n");
printWriter.flush();
byte[] whoisrecords = new byte[2048];
java.util.List<Byte> bytelist = new ArrayList<>(1024 * 6);
int size = 0;
while ((size = inputStream.read(whoisrecords)) > 0) {
for (int i = 0; i < size; i++) {
bytelist.add(whoisrecords[i]);
}
}
System.out.println("size:" + bytelist.size());
byte[] resultbyte = new byte[bytelist.size()];
for (int i = 0; i < resultbyte.length; i++) {
resultbyte[i] = bytelist.get(i);
}
String string = new String(resultbyte);
System.out.println(string);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocksException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run() {
logger.info("Start proxy server at port:{}", bindPort);
while (!stop) {
try {
Socket socket = serverSocket.accept();
socket = processSocketBeforeUse(socket);
socket.setSoTimeout(timeout);
Session session = sessionManager.newSession(socket);
logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress());
try {
sessionFilterChain.doFilterChain(session);
} catch (InterruptedException e) {
session.close();
logger.info(e.getMessage());
continue;
}
SocksHandler socksHandler = createSocksHandler();
/* initialize socks handler */
socksHandler.setSession(session);
initializeSocksHandler(socksHandler);
executorService.execute(socksHandler);
} catch (IOException e) {
// Catches the exception that cause by shutdown method.
if (e.getMessage().equals("Socket closed") && stop) {
logger.debug("Server shutdown");
return;
}
logger.debug(e.getMessage(), e);
}
}
}
|
#vulnerable code
@Override
public void run() {
logger.info("Start proxy server at port:{}", bindPort);
while (!stop) {
try {
Socket socket = serverSocket.accept();
socket = processSocketBeforeUse(socket);
socket.setSoTimeout(timeout);
Session session = new SocksSession(getNextSessionId(), socket, sessions);
sessions.put(session.getId(), session);
logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress());
try {
sessionFilterChain.doFilterChain(session);
} catch (InterruptedException e) {
session.close();
logger.info(e.getMessage());
continue;
}
SocksHandler socksHandler = createSocksHandler();
/* initialize socks handler */
socksHandler.setSession(session);
initializeSocksHandler(socksHandler);
executorService.execute(socksHandler);
} catch (IOException e) {
// Catches the exception that cause by shutdown method.
if (e.getMessage().equals("Socket closed") && stop) {
logger.debug("Server shutdown");
return;
}
logger.debug(e.getMessage(), e);
}
}
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws Exception {
SSLConfiguration configuration = SSLConfiguration.loadClassPath("client-ssl.properties");
SocksProxy proxy = new SSLSocks5(new InetSocketAddress("localhost", 1080), configuration);
List<SocksMethod> methods = new ArrayList<SocksMethod>();
methods.add(new NoAuthencationRequiredMethod());
proxy.setAcceptableMethods(methods);
SocksSocket socket = new SocksSocket(proxy);
socket.connect("whois.internic.net", 43);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("domain google.com\r\n");
printWriter.flush();
byte[] whoisrecords = new byte[2048];
List<Byte> bytelist = new ArrayList<>(1024 * 6);
int size = 0;
while ((size = inputStream.read(whoisrecords)) > 0) {
for (int i = 0; i < size; i++) {
bytelist.add(whoisrecords[i]);
}
}
byte[] resultbyte = new byte[bytelist.size()];
for (int i = 0; i < resultbyte.length; i++) {
resultbyte[i] = bytelist.get(i);
}
String string = new String(resultbyte);
System.out.println(string);
inputStream.close();
outputStream.close();
socket.close();
}
|
#vulnerable code
public static void main(String[] args) throws Exception {
SocksClientSSLUtil sslUtil = SocksClientSSLUtil.loadClassPath("client-ssl.properties");
SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080));
List<SocksMethod> methods = new ArrayList<SocksMethod>();
methods.add(new NoAuthencationRequiredMethod());
proxy.setAcceptableMethods(methods);
SocksSocket socket = sslUtil.create(proxy);
socket.connect("whois.internic.net", 43);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("domain google.com\r\n");
printWriter.flush();
byte[] whoisrecords = new byte[2048];
java.util.List<Byte> bytelist = new ArrayList<>(1024 * 6);
int size = 0;
while ((size = inputStream.read(whoisrecords)) > 0) {
for (int i = 0; i < size; i++) {
bytelist.add(whoisrecords[i]);
}
}
byte[] resultbyte = new byte[bytelist.size()];
for (int i = 0; i < resultbyte.length; i++) {
resultbyte[i] = bytelist.get(i);
}
String string = new String(resultbyte);
System.out.println(string);
inputStream.close();
outputStream.close();
socket.close();
}
#location 35
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run() {
logger.info("Start proxy server at port:{}", bindPort);
while (!stop) {
try {
Socket socket = serverSocket.accept();
socket = processSocketBeforeUse(socket);
socket.setSoTimeout(timeout);
Session session = sessionManager.newSession(socket);
logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress());
try {
sessionFilterChain.doFilterChain(session);
} catch (InterruptedException e) {
session.close();
logger.info(e.getMessage());
continue;
}
SocksHandler socksHandler = createSocksHandler();
/* initialize socks handler */
socksHandler.setSession(session);
initializeSocksHandler(socksHandler);
executorService.execute(socksHandler);
} catch (IOException e) {
// Catches the exception that cause by shutdown method.
if (e.getMessage().equals("Socket closed") && stop) {
logger.debug("Server shutdown");
return;
}
logger.debug(e.getMessage(), e);
}
}
}
|
#vulnerable code
@Override
public void run() {
logger.info("Start proxy server at port:{}", bindPort);
while (!stop) {
try {
Socket socket = serverSocket.accept();
socket = processSocketBeforeUse(socket);
socket.setSoTimeout(timeout);
Session session = new SocksSession(getNextSessionId(), socket, sessions);
sessions.put(session.getId(), session);
logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress());
try {
sessionFilterChain.doFilterChain(session);
} catch (InterruptedException e) {
session.close();
logger.info(e.getMessage());
continue;
}
SocksHandler socksHandler = createSocksHandler();
/* initialize socks handler */
socksHandler.setSession(session);
initializeSocksHandler(socksHandler);
executorService.execute(socksHandler);
} catch (IOException e) {
// Catches the exception that cause by shutdown method.
if (e.getMessage().equals("Socket closed") && stop) {
logger.debug("Server shutdown");
return;
}
logger.debug(e.getMessage(), e);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
Timer.open();
SSLConfiguration configuration = SSLConfiguration.loadClassPath("server-ssl.properties");
SocksProxyServer proxyServer = SocksServerBuilder.buildAnonymousSSLSocks5Server(1081, configuration);
try {
proxyServer.start();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
Timer.open();
SSLConfiguration configuration = SSLConfiguration.loadClassPath("server-ssl.properties");
SocksProxyServer proxyServer = new SSLSocksProxyServer(Socks5Handler.class, configuration);
proxyServer.setBindPort(1081);
proxyServer.setSupportMethods(new NoAuthenticationRequiredMethod());
try {
proxyServer.start();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public byte[] getBytes() {
byte[] bytes = null;
switch (addressType) {
case AddressType.IPV4:
bytes = new byte[10];
byte[] ipv4Bytes = inetAddress.getAddress();// todo
System.arraycopy(ipv4Bytes, 0, bytes, 4, ipv4Bytes.length);
bytes[8] = SocksUtil.getFirstByteFromInt(port);
bytes[9] = SocksUtil.getSecondByteFromInt(port);
break;
case AddressType.IPV6:
bytes = new byte[22];
byte[] ipv6Bytes = inetAddress.getAddress();// todo
System.arraycopy(ipv6Bytes, 0, bytes, 4, ipv6Bytes.length);
bytes[20] = SocksUtil.getFirstByteFromInt(port);
bytes[21] = SocksUtil.getSecondByteFromInt(port);
break;
case AddressType.DOMAIN_NAME:
final int hostLength = host.getBytes().length;
bytes = new byte[7 + hostLength];
bytes[4] = (byte) hostLength;
for (int i = 0; i < hostLength; i++) {
bytes[5 + i] = host.getBytes()[i];
}
bytes[5 + hostLength] = SocksUtil.getFirstByteFromInt(port);
bytes[6 + hostLength] = SocksUtil.getSecondByteFromInt(port);
break;
default:
break;
}
if (bytes != null) {
bytes[0] = (byte) version;
bytes[1] = (byte) command.getValue();
bytes[2] = RESERVED;
bytes[3] = (byte) addressType;
}
return bytes;
}
|
#vulnerable code
@Override
public byte[] getBytes() {
byte[] bytes = null;
switch (addressType) {
case AddressType.IPV4:
bytes = new byte[10];
byte[] ipv4Bytes = inetAddress.getAddress();// todo
System.arraycopy(ipv4Bytes, 0, bytes, 4, ipv4Bytes.length);
bytes[8] = SocksUtil.getFirstByteFromInt(port);
bytes[9] = SocksUtil.getSecondByteFromInt(port);
break;
case AddressType.IPV6:
bytes = new byte[22];
byte[] ipv6Bytes = inetAddress.getAddress();// todo
System.arraycopy(ipv6Bytes, 0, bytes, 4, ipv6Bytes.length);
bytes[20] = SocksUtil.getFirstByteFromInt(port);
bytes[21] = SocksUtil.getSecondByteFromInt(port);
break;
case AddressType.DOMAIN_NAME:
final int hostLength = host.getBytes().length;
bytes = new byte[7 + hostLength];
bytes[4] = (byte) hostLength;
for (int i = 0; i < hostLength; i++) {
bytes[5 + i] = host.getBytes()[i];
}
bytes[5 + hostLength] = SocksUtil.getFirstByteFromInt(port);
bytes[6 + hostLength] = SocksUtil.getSecondByteFromInt(port);
break;
default:
break;
}
bytes[0] = (byte) version;
bytes[1] = (byte) command.getValue();
bytes[2] = RESERVED;
bytes[3] = (byte) addressType;
return bytes;
}
#location 36
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run() {
logger.info("Start proxy server at port:{}", bindPort);
while (!stop) {
try {
Socket socket = serverSocket.accept();
socket = processSocketBeforeUse(socket);
socket.setSoTimeout(timeout);
Session session = sessionManager.newSession(socket);
logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress());
try {
sessionFilterChain.doFilterChain(session);
} catch (InterruptedException e) {
session.close();
logger.info(e.getMessage());
continue;
}
SocksHandler socksHandler = createSocksHandler();
/* initialize socks handler */
socksHandler.setSession(session);
initializeSocksHandler(socksHandler);
executorService.execute(socksHandler);
} catch (IOException e) {
// Catches the exception that cause by shutdown method.
if (e.getMessage().equals("Socket closed") && stop) {
logger.debug("Server shutdown");
return;
}
logger.debug(e.getMessage(), e);
}
}
}
|
#vulnerable code
@Override
public void run() {
logger.info("Start proxy server at port:{}", bindPort);
while (!stop) {
try {
Socket socket = serverSocket.accept();
socket = processSocketBeforeUse(socket);
socket.setSoTimeout(timeout);
Session session = new SocksSession(getNextSessionId(), socket, sessions);
sessions.put(session.getId(), session);
logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress());
try {
sessionFilterChain.doFilterChain(session);
} catch (InterruptedException e) {
session.close();
logger.info(e.getMessage());
continue;
}
SocksHandler socksHandler = createSocksHandler();
/* initialize socks handler */
socksHandler.setSession(session);
initializeSocksHandler(socksHandler);
executorService.execute(socksHandler);
} catch (IOException e) {
// Catches the exception that cause by shutdown method.
if (e.getMessage().equals("Socket closed") && stop) {
logger.debug("Server shutdown");
return;
}
logger.debug(e.getMessage(), e);
}
}
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(@Nullable String[] args) throws IOException, InterruptedException {
Timer.open();
Socks5Server socks5Server = new Socks5Server();
socks5Server.start(args);
}
|
#vulnerable code
public static void main(@Nullable String[] args) throws IOException, InterruptedException {
Timer.open();
Socks5Server socks5Server = new Socks5Server();
socks5Server.start(args);
BasicSocksProxyServer server = (BasicSocksProxyServer) socks5Server.server;
NetworkMonitor monitor = server.getNetworkMonitor();
while (true) {
logger.info(monitor.toString());
Thread.sleep(5000);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) {
InputStream inputStream = null;
OutputStream outputStream = null;
Socket socket = null;
StringBuffer response = null;
int length = 0;
byte[] buffer = new byte[2048];
try {
SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080));
socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net", 43));
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("domain google.com\r\n"); // query google.com WHOIS.
printWriter.flush();
response = new StringBuffer();
while ((length = inputStream.read(buffer)) > 0) {
response.append(new String(buffer, 0, length));
}
System.out.println(response.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
ResourceUtil.close(inputStream, outputStream, socket);
}
}
|
#vulnerable code
public static void main(String[] args) {
SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080));
try {
@SuppressWarnings("resource")
Socket socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net", 43));
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("domain google.com\r\n");
printWriter.flush();
byte[] whoisrecords = new byte[2048];
java.util.List<Byte> bytelist = new ArrayList<>(1024 * 6);
int size = 0;
while ((size = inputStream.read(whoisrecords)) > 0) {
for (int i = 0; i < size; i++) {
bytelist.add(whoisrecords[i]);
}
}
System.out.println("size:" + bytelist.size());
byte[] resultbyte = new byte[bytelist.size()];
for (int i = 0; i < resultbyte.length; i++) {
resultbyte[i] = bytelist.get(i);
}
String string = new String(resultbyte);
System.out.println(string);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocksException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testGetterSetterAnnotated() throws Exception {
GetterSetterAnnotated o = new GetterSetterAnnotated();
o.setId("blah");
JacksonDBCollection<GetterSetterAnnotated, String> coll = createCollFor(o, String.class);
coll.insert(o);
GetterSetterAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo("blah"));
}
|
#vulnerable code
@Test
public void testGetterSetterAnnotated() throws Exception {
GetterSetterAnnotated o = new GetterSetterAnnotated();
o.setId("blah");
JacksonDBCollection<GetterSetterAnnotated, String> coll = createCollFor(o, String.class);
WriteResult<GetterSetterAnnotated, String> writeResult = coll.insert(o);
assertThat(writeResult.getSavedId(), equalTo("blah"));
assertThat(writeResult.getDbObject().get("id"), nullValue());
GetterSetterAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo("blah"));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void simpleDbRefShouldBeSavedAsDbRef() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class);
refColl.insert(new Referenced("hello", 10));
coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName())));
String id = coll.findOne()._id;
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
|
#vulnerable code
@Test
public void simpleDbRefShouldBeSavedAsDbRef() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class);
refColl.insert(new Referenced("hello", 10));
String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName()))).getSavedId();
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void dbRefWithObjectIdShouldBeSavedAsDbRef() {
JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class);
JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class);
byte[] refId = new org.bson.types.ObjectId().toByteArray();
refColl.insert(new ObjectIdReferenced(refId, 10));
coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName())));
String id = coll.findOne()._id;
ObjectIdOwner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo(refId));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
ObjectIdReferenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId));
assertThat(ref.i, equalTo(10));
}
|
#vulnerable code
@Test
public void dbRefWithObjectIdShouldBeSavedAsDbRef() {
JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class);
JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class);
byte[] refId = refColl.insert(new ObjectIdReferenced(10)).getSavedId();
String id = coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName()))).getSavedId();
ObjectIdOwner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo(refId));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
ObjectIdReferenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId));
assertThat(ref.i, equalTo(10));
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public WriteResult<T, K> update(T query, T object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException {
return update(convertToBasicDbObject(query), convertToBasicDbObject(object), upsert, multi, concern);
}
|
#vulnerable code
public WriteResult<T, K> update(T query, T object, boolean upsert, boolean multi, WriteConcern concern) throws MongoException {
return update(convertToDbObject(query), convertToDbObject(object), upsert, multi, concern);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testJpaIdFieldAnnotated() throws Exception {
JpaIdFieldAnnotated o = new JpaIdFieldAnnotated();
o.id = "blah";
JacksonDBCollection<JpaIdFieldAnnotated, String> coll = createCollFor(o, String.class);
coll.insert(o);
JpaIdFieldAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.id, equalTo("blah"));
}
|
#vulnerable code
@Test
public void testJpaIdFieldAnnotated() throws Exception {
JpaIdFieldAnnotated o = new JpaIdFieldAnnotated();
o.id = "blah";
JacksonDBCollection<JpaIdFieldAnnotated, String> coll = createCollFor(o, String.class);
WriteResult<JpaIdFieldAnnotated, String> writeResult = coll.insert(o);
assertThat(writeResult.getSavedId(), equalTo("blah"));
assertThat(writeResult.getDbObject().get("id"), nullValue());
JpaIdFieldAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.id, equalTo("blah"));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void dbRefWithObjectIdShouldBeSavedAsDbRef() {
JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class);
JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class);
byte[] refId = new org.bson.types.ObjectId().toByteArray();
refColl.insert(new ObjectIdReferenced(refId, 10));
coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName())));
String id = coll.findOne()._id;
ObjectIdOwner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo(refId));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
ObjectIdReferenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId));
assertThat(ref.i, equalTo(10));
}
|
#vulnerable code
@Test
public void dbRefWithObjectIdShouldBeSavedAsDbRef() {
JacksonDBCollection<ObjectIdOwner, String> coll = getCollection(ObjectIdOwner.class, String.class);
JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class);
byte[] refId = refColl.insert(new ObjectIdReferenced(10)).getSavedId();
String id = coll.insert(new ObjectIdOwner(new DBRef<ObjectIdReferenced, byte[]>(refId, refColl.getName()))).getSavedId();
ObjectIdOwner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo(refId));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
ObjectIdReferenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId));
assertThat(ref.i, equalTo(10));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testIdFieldAnnotated() throws Exception {
IdFieldAnnotated o = new IdFieldAnnotated();
o.id = "blah";
JacksonDBCollection<IdFieldAnnotated, String> coll = createCollFor(o, String.class);
coll.insert(o);
IdFieldAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.id, equalTo("blah"));
}
|
#vulnerable code
@Test
public void testIdFieldAnnotated() throws Exception {
IdFieldAnnotated o = new IdFieldAnnotated();
o.id = "blah";
JacksonDBCollection<IdFieldAnnotated, String> coll = createCollFor(o, String.class);
WriteResult<IdFieldAnnotated, String> writeResult = coll.insert(o);
assertThat(writeResult.getSavedId(), equalTo("blah"));
assertThat(writeResult.getDbObject().get("id"), nullValue());
IdFieldAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.id, equalTo("blah"));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testObjectIdAnnotationOnStringGenerated() {
StringId object = new StringId();
JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class);
coll.insert(object);
String id = coll.findOne()._id;
// Check that it's a valid object id
assertTrue(org.bson.types.ObjectId.isValid(id));
StringId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
assertThat(coll.getDbCollection().findOne().get("_id").toString(), equalTo(id));
}
|
#vulnerable code
@Test
public void testObjectIdAnnotationOnStringGenerated() {
StringId object = new StringId();
JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class);
String id = coll.insert(object).getSavedId();
// Check that it's a valid object id
assertTrue(org.bson.types.ObjectId.isValid(id));
StringId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCreatorGetterAnnotated() throws Exception {
CreatorGetterAnnotated o = new CreatorGetterAnnotated("blah");
JacksonDBCollection<CreatorGetterAnnotated, String> coll = createCollFor(o, String.class);
coll.insert(o);
CreatorGetterAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo("blah"));
}
|
#vulnerable code
@Test
public void testCreatorGetterAnnotated() throws Exception {
CreatorGetterAnnotated o = new CreatorGetterAnnotated("blah");
JacksonDBCollection<CreatorGetterAnnotated, String> coll = createCollFor(o, String.class);
WriteResult<CreatorGetterAnnotated, String> writeResult = coll.insert(o);
assertThat(writeResult.getSavedId(), equalTo("blah"));
assertThat(writeResult.getDbObject().get("id"), nullValue());
CreatorGetterAnnotated result = coll.findOneById("blah");
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo("blah"));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testObjectIdGenerated() {
ObjectIdId object = new ObjectIdId();
JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class,
org.bson.types.ObjectId.class);
coll.insert(object);
org.bson.types.ObjectId id = coll.findOne()._id;
ObjectIdId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
assertThat((org.bson.types.ObjectId) coll.getDbCollection().findOne().get("_id"), equalTo(id));
}
|
#vulnerable code
@Test
public void testObjectIdGenerated() {
ObjectIdId object = new ObjectIdId();
JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class,
org.bson.types.ObjectId.class);
org.bson.types.ObjectId id = coll.insert(object).getSavedId();
ObjectIdId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testUsingMongoCollectionAnnotation() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced");
refColl.insert(new Referenced("hello", 10));
coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class)));
String id = coll.findOne()._id;
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo("referenced"));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
|
#vulnerable code
@Test
public void testUsingMongoCollectionAnnotation() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced");
refColl.insert(new Referenced("hello", 10));
String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class))).getSavedId();
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo("referenced"));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public UpdateResult save(T object, WriteConcern concern) throws MongoWriteException, MongoWriteConcernException, MongoException {
Object _id;
@SuppressWarnings("unchecked")
final Codec<T> codec = getMongoCollection().getCodecRegistry().get((Class<T>) object.getClass());
if (codec instanceof CollectibleCodec) {
_id = JacksonCodec.extractValueEx(((CollectibleCodec<T>) codec).getDocumentId(object));
} else {
Document dbObject = convertToDocument(object);
_id = dbObject.get("_id");
}
if(_id == null) {
if (concern == null) {
this.insert(object);
} else {
this.insert(object, concern);
}
if (codec instanceof CollectibleCodec) {
return UpdateResult.acknowledged(0, 1L, ((CollectibleCodec<T>)codec).getDocumentId(object));
} else {
return UpdateResult.acknowledged(0, 1L, null);
}
} else {
return this.replaceOne(new Document("_id", _id), object, true, concern);
}
}
|
#vulnerable code
public UpdateResult save(T object, WriteConcern concern) throws MongoWriteException, MongoWriteConcernException, MongoException {
Document dbObject = convertToDocument(object);
Object _id = dbObject.get("_id");
if(_id == null) {
this.insert(object, concern);
return UpdateResult.acknowledged(0, 1L, new BsonObjectId((ObjectId) convertToDocument(object).get("_id")));
} else {
return this.replaceOne(new Document("_id", _id), object, true, concern);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testObjectIdFieldAnnotated() throws Exception {
ObjectIdFieldAnnotated o = new ObjectIdFieldAnnotated();
o.id = new org.bson.types.ObjectId().toString();
JacksonDBCollection<ObjectIdFieldAnnotated, String> coll = createCollFor(o, String.class);
coll.insert(o);
ObjectIdFieldAnnotated result = coll.findOneById(o.id);
assertThat(result, notNullValue());
assertThat(result.id, equalTo(o.id));
}
|
#vulnerable code
@Test
public void testObjectIdFieldAnnotated() throws Exception {
ObjectIdFieldAnnotated o = new ObjectIdFieldAnnotated();
JacksonDBCollection<ObjectIdFieldAnnotated, String> coll = createCollFor(o, String.class);
WriteResult<ObjectIdFieldAnnotated, String> writeResult = coll.insert(o);
assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class));
assertThat(writeResult.getSavedId(), instanceOf(String.class));
assertThat(writeResult.getDbObject().get("id"), nullValue());
ObjectIdFieldAnnotated result = coll.findOneById(writeResult.getSavedId());
assertThat(result, notNullValue());
assertThat(result.id, equalTo(writeResult.getSavedId()));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testObjectIdSaved() {
ObjectIdId object = new ObjectIdId();
org.bson.types.ObjectId id = new org.bson.types.ObjectId();
object._id = id;
JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class,
org.bson.types.ObjectId.class);
coll.insert(object);
ObjectIdId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
assertThat((org.bson.types.ObjectId) coll.getDbCollection().findOne().get("_id"), equalTo(id));
}
|
#vulnerable code
@Test
public void testObjectIdSaved() {
ObjectIdId object = new ObjectIdId();
org.bson.types.ObjectId id = new org.bson.types.ObjectId();
object._id = id;
JacksonDBCollection<ObjectIdId, org.bson.types.ObjectId> coll = getCollection(ObjectIdId.class,
org.bson.types.ObjectId.class);
coll.insert(object);
ObjectIdId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testUsingMongoCollectionAnnotation() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced");
refColl.insert(new Referenced("hello", 10));
coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class)));
String id = coll.findOne()._id;
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo("referenced"));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
|
#vulnerable code
@Test
public void testUsingMongoCollectionAnnotation() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class, "referenced");
refColl.insert(new Referenced("hello", 10));
String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", Referenced.class))).getSavedId();
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo("referenced"));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testFindOneByIdWithObjectId() {
JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class);
StringId object = new StringId();
coll.insert(object);
assertThat(coll.getDbCollection().findOne().get("_id"), instanceOf(org.bson.types.ObjectId.class));
String id = coll.findOne()._id;
assertThat(id, instanceOf(String.class));
StringId result = coll.findOneById(id);
assertThat(result._id, Matchers.equalTo(id));
}
|
#vulnerable code
@Test
public void testFindOneByIdWithObjectId() {
JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class);
StringId object = new StringId();
net.vz.mongodb.jackson.WriteResult<StringId, String> writeResult = coll.insert(object);
assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class));
String id = writeResult.getSavedId();
assertThat(id, instanceOf(String.class));
StringId result = coll.findOneById(id);
assertThat(result._id, Matchers.equalTo(id));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCreatorGetterObjectIdAnnotated() throws Exception {
CreatorGetterObjectIdAnnotated o = new CreatorGetterObjectIdAnnotated(new org.bson.types.ObjectId().toString());
JacksonDBCollection<CreatorGetterObjectIdAnnotated, String> coll = createCollFor(o, String.class);
coll.insert(o);
CreatorGetterObjectIdAnnotated result = coll.findOneById(o.id);
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo(o.id));
}
|
#vulnerable code
@Test
public void testCreatorGetterObjectIdAnnotated() throws Exception {
CreatorGetterObjectIdAnnotated o = new CreatorGetterObjectIdAnnotated(null);
JacksonDBCollection<CreatorGetterObjectIdAnnotated, String> coll = createCollFor(o, String.class);
WriteResult<CreatorGetterObjectIdAnnotated, String> writeResult = coll.insert(o);
assertThat(writeResult.getSavedId(), notNullValue());
assertThat(writeResult.getSavedId(), instanceOf(String.class));
assertThat(writeResult.getDbObject().get("id"), nullValue());
assertThat(writeResult.getSavedId(), equalTo(writeResult.getDbObject().get("_id").toString()));
CreatorGetterObjectIdAnnotated result = coll.findOneById(writeResult.getSavedId());
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo(writeResult.getSavedId()));
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() {
JacksonDBCollection<ObjectIdCollectionOwner, String> coll = getCollection(ObjectIdCollectionOwner.class, String.class);
JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced");
byte[] refId1 = new org.bson.types.ObjectId().toByteArray();
refColl.insert(new ObjectIdReferenced(refId1, 10));
byte[] refId2 = new org.bson.types.ObjectId().toByteArray();
refColl.insert(new ObjectIdReferenced(refId2, 20));
ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner();
owner.list = Arrays.asList(new DBRef<ObjectIdReferenced, byte[]>(refId1, refColl.getName()), new DBRef<ObjectIdReferenced, byte[]>(refId2, refColl.getName()));
owner._id = "foo";
coll.insert(owner);
ObjectIdCollectionOwner saved = coll.findOneById("foo");
assertThat(saved.list, notNullValue());
assertThat(saved.list, hasSize(2));
assertThat(saved.list.get(0).getId(), equalTo(refId1));
assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName()));
assertThat(saved.list.get(1).getId(), equalTo(refId2));
assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName()));
// Try loading them
ObjectIdReferenced ref = saved.list.get(0).fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId1));
assertThat(ref.i, equalTo(10));
ref = saved.list.get(1).fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId2));
assertThat(ref.i, equalTo(20));
}
|
#vulnerable code
@Test
public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() {
JacksonDBCollection<ObjectIdCollectionOwner, String> coll = getCollection(ObjectIdCollectionOwner.class, String.class);
JacksonDBCollection<ObjectIdReferenced, byte[]> refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced");
byte[] refId1 = refColl.insert(new ObjectIdReferenced(10)).getSavedId();
byte[] refId2 = refColl.insert(new ObjectIdReferenced(20)).getSavedId();
ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner();
owner.list = Arrays.asList(new DBRef<ObjectIdReferenced, byte[]>(refId1, refColl.getName()), new DBRef<ObjectIdReferenced, byte[]>(refId2, refColl.getName()));
owner._id = "foo";
coll.insert(owner);
ObjectIdCollectionOwner saved = coll.findOneById("foo");
assertThat(saved.list, notNullValue());
assertThat(saved.list, hasSize(2));
assertThat(saved.list.get(0).getId(), equalTo(refId1));
assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName()));
assertThat(saved.list.get(1).getId(), equalTo(refId2));
assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName()));
// Try loading them
ObjectIdReferenced ref = saved.list.get(0).fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId1));
assertThat(ref.i, equalTo(10));
ref = saved.list.get(1).fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo(refId2));
assertThat(ref.i, equalTo(20));
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testObjectIdAnnotationOnStringSaved() {
StringId object = new StringId();
String id = new org.bson.types.ObjectId().toString();
object._id = id;
JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class);
coll.insert(object);
StringId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
assertThat(coll.getDbCollection().findOne().get("_id").toString(), equalTo(id));
}
|
#vulnerable code
@Test
public void testObjectIdAnnotationOnStringSaved() {
StringId object = new StringId();
String id = new org.bson.types.ObjectId().toString();
object._id = id;
JacksonDBCollection<StringId, String> coll = getCollection(StringId.class, String.class);
coll.insert(object);
StringId result = coll.findOneById(id);
assertThat(result._id, equalTo(id));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void simpleDbRefShouldBeSavedAsDbRef() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class);
refColl.insert(new Referenced("hello", 10));
coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName())));
String id = coll.findOne()._id;
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
|
#vulnerable code
@Test
public void simpleDbRefShouldBeSavedAsDbRef() {
JacksonDBCollection<Owner, String> coll = getCollection(Owner.class, String.class);
JacksonDBCollection<Referenced, String> refColl = getCollection(Referenced.class, String.class);
refColl.insert(new Referenced("hello", 10));
String id = coll.insert(new Owner(new DBRef<Referenced, String>("hello", refColl.getName()))).getSavedId();
Owner saved = coll.findOneById(id);
assertThat(saved.ref, notNullValue());
assertThat(saved.ref.getId(), equalTo("hello"));
assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName()));
// Try loading it
Referenced ref = saved.ref.fetch();
assertThat(ref, notNullValue());
assertThat(ref._id, equalTo("hello"));
assertThat(ref.i, equalTo(10));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void calculate(ValuesProvider valuesProvider, List<ConnectionCandidate> connections, NeuralNetwork nn) {
if (connections.size() > 0) {
List<Connections> chunk = new ArrayList<>();
for (int i = 0; i < connections.size(); i++) {
ConnectionCandidate c = connections.get(i);
chunk.add(c.connection);
if (i == connections.size() - 1 || connections.get(i + 1).target != c.target) {
ConnectionCalculator cc = getConnectionCalculator(c.target);
if (cc != null) {
Tensor t = TensorFactory.tensor(c.target, chunk, valuesProvider);
float[] elements = t.getElements();
IntStream.range(t.getStartIndex(), t.getStartIndex() + t.getSize()).forEach(j -> elements[j] = 0);
cc.calculate(chunk, valuesProvider, c.target);
}
chunk.clear();
triggerEvent(new PropagationEvent(c.target, chunk, nn, valuesProvider));
}
}
}
}
|
#vulnerable code
protected void calculate(ValuesProvider valuesProvider, List<ConnectionCandidate> connections, NeuralNetwork nn) {
if (connections.size() > 0) {
List<Connections> chunk = new ArrayList<>();
for (int i = 0; i < connections.size(); i++) {
ConnectionCandidate c = connections.get(i);
chunk.add(c.connection);
if (i == connections.size() - 1 || connections.get(i + 1).target != c.target) {
ConnectionCalculator cc = getConnectionCalculator(c.target);
if (cc != null) {
Tensor t = TensorFactory.tensor(c.target, chunk, valuesProvider);
t.forEach(j -> t.getElements()[j] = 0);
cc.calculate(chunk, valuesProvider, c.target);
}
chunk.clear();
triggerEvent(new PropagationEvent(c.target, chunk, nn, valuesProvider));
}
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void httpsUrlGitHubNoSuffix() {
testURL("https://[email protected]/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void httpsUrlGitHubNoSuffix() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("https://[email protected]/jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitColonUrlGitHub() {
testURL("git://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitColonUrlGitHub() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("git://github.com/jenkinsci/jenkins.git");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void httpsUrlGitHub() {
testURL("https://[email protected]/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void httpsUrlGitHub() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("https://[email protected]/jenkinsci/jenkins.git");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitAtUrlGitHub() {
testURL("[email protected]:jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitAtUrlGitHub() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("[email protected]:jenkinsci/jenkins.git");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitColonUrlOtherHostNoSuffix() {
testURL("git://company.net/jenkinsci/jenkins", "company.net", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitColonUrlOtherHostNoSuffix() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("git://company.net/jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("company.net", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitColonUrlGitHubNoSuffix() {
testURL("git://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitColonUrlGitHubNoSuffix() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("git://github.com/jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void httpsUrlGitHubWithoutUserNoSuffix() {
testURL("https://github.com/jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void httpsUrlGitHubWithoutUserNoSuffix() {
//this is valid for anonymous usage
GitHubRepositoryName repo = GitHubRepositoryName
.create("https://github.com/jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void trimWhitespace() {
assertThat(" https://[email protected]/jenkinsci/jenkins/ ", repo(allOf(
withHost("github.com"),
withUserName("jenkinsci"),
withRepoName("jenkins")
)));
}
|
#vulnerable code
@Test
public void trimWhitespace() {
GitHubRepositoryName repo = GitHubRepositoryName
.create(" https://[email protected]/jenkinsci/jenkins/ ");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void httpsUrlOtherHost() {
testURL("https://[email protected]/jenkinsci/jenkins.git", "gh.company.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void httpsUrlOtherHost() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("https://[email protected]/jenkinsci/jenkins.git");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("gh.company.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void httpsUrlOtherHostNoSuffix() {
testURL("https://[email protected]/jenkinsci/jenkins", "gh.company.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void httpsUrlOtherHostNoSuffix() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("https://[email protected]/jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("gh.company.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitAtUrlOtherHostNoSuffix() {
testURL("[email protected]:jenkinsci/jenkins", "gh.company.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitAtUrlOtherHostNoSuffix() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("[email protected]:jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("gh.company.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void httpsUrlGitHubWithoutUser() {
testURL("https://github.com/jenkinsci/jenkins.git", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void httpsUrlGitHubWithoutUser() {
//this is valid for anonymous usage
GitHubRepositoryName repo = GitHubRepositoryName
.create("https://github.com/jenkinsci/jenkins.git");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private OkHttpConnector connector(String apiUrl) {
OkHttpClient client = new OkHttpClient().setProxy(getProxy(apiUrl));
if (configuration().getClientCacheSize() > 0) {
File cacheDir = getCacheBaseDirFor(GitHubWebHook.getJenkinsInstance());
Cache cache = new Cache(cacheDir, configuration().getClientCacheSize() * 1024 * 1024);
client.setCache(cache);
}
return new OkHttpConnector(new OkUrlFactory(client));
}
|
#vulnerable code
private OkHttpConnector connector(String apiUrl) {
Jenkins jenkins = GitHubWebHook.getJenkinsInstance();
OkHttpClient client = new OkHttpClient().setProxy(getProxy(apiUrl));
if (configuration().getClientCacheSize() > 0) {
File cacheDir = new File(jenkins.getRootDir(), GitHubPlugin.class.getName() + ".cache");
Cache cache = new Cache(cacheDir, configuration().getClientCacheSize() * 1024 * 1024);
client.setCache(cache);
}
return new OkHttpConnector(new OkUrlFactory(client));
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitAtUrlGitHubNoSuffix() {
testURL("[email protected]:jenkinsci/jenkins", "github.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitAtUrlGitHubNoSuffix() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("[email protected]:jenkinsci/jenkins");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("github.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void gitAtUrlOtherHost() {
testURL("[email protected]:jenkinsci/jenkins.git", "gh.company.com", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitAtUrlOtherHost() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("[email protected]:jenkinsci/jenkins.git");
assertNotNull(repo);
assertEquals("jenkinsci", repo.userName);
assertEquals("jenkins", repo.repositoryName);
assertEquals("gh.company.com", repo.host);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws Exception {
CommandLineParams commandLineParams = new CommandLineParams();
JCommander jCommander = new JCommander(commandLineParams, args);
if (commandLineParams.help) {
jCommander.usage();
System.exit(1);
}
// default to src/main/webapp
if (commandLineParams.paths.size() == 0) {
commandLineParams.paths.add("src/main/webapp");
}
final Tomcat tomcat = new Tomcat();
// set directory for temp files
tomcat.setBaseDir(resolveTomcatBaseDir(commandLineParams.port));
// initialize the connector
Connector nioConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
nioConnector.setPort(commandLineParams.port);
tomcat.setConnector(nioConnector);
tomcat.getService().addConnector(tomcat.getConnector());
tomcat.setPort(commandLineParams.port);
if (commandLineParams.paths.size() > 1) {
System.out.println("WARNING: multiple paths are specified, but no longer supported. First path will be used.");
}
// Get the first path
String path = commandLineParams.paths.get(0);
Context ctx = null;
File war = new File(path);
if (!war.exists()) {
System.err.println("The specified path \"" + path + "\" does not exist.");
jCommander.usage();
System.exit(1);
}
// Use the commandline context-path (or default)
// warn if the contextPath doesn't start with a '/'. This causes issues serving content at the context root.
if (commandLineParams.contextPath.length() > 0 && !commandLineParams.contextPath.startsWith("/")) {
System.out.println("WARNING: You entered a path: [" + commandLineParams.contextPath + "]. Your path should start with a '/'. Tomcat will update this for you, but you may still experience issues.");
}
final String ctxName = commandLineParams.contextPath;
System.out.println("Adding Context " + ctxName + " for " + war.getPath());
ctx = tomcat.addWebapp(ctxName, war.getAbsolutePath());
if(!commandLineParams.shutdownOverride) {
// allow Tomcat to shutdown if a context failure is detected
ctx.addLifecycleListener(new LifecycleListener() {
public void lifecycleEvent(LifecycleEvent event) {
if (event.getLifecycle().getState() == LifecycleState.FAILED) {
Server server = tomcat.getServer();
if (server instanceof StandardServer) {
System.err.println("SEVERE: Context [" + ctxName + "] failed in [" + event.getLifecycle().getClass().getName() + "] lifecycle. Allowing Tomcat to shutdown.");
((StandardServer) server).stopAwait();
}
}
}
});
}
// set the context xml location if there is only one war
if(commandLineParams.contextXml != null) {
System.out.println("Using context config: " + commandLineParams.contextXml);
ctx.setConfigFile(new File(commandLineParams.contextXml).toURI().toURL());
}
// set the session manager
if (commandLineParams.sessionStore != null) {
SessionStore.getInstance(commandLineParams.sessionStore).configureSessionStore(commandLineParams, ctx);
}
//set the session timeout
if(commandLineParams.sessionTimeout != null) {
ctx.setSessionTimeout(commandLineParams.sessionTimeout);
}
commandLineParams = null;
//start the server
tomcat.start();
tomcat.getServer().await();
}
|
#vulnerable code
public static void main(String[] args) throws Exception {
CommandLineParams commandLineParams = new CommandLineParams();
JCommander jCommander = new JCommander(commandLineParams, args);
if (commandLineParams.help) {
jCommander.usage();
System.exit(1);
}
// default to src/main/webapp
if (commandLineParams.paths.size() == 0) {
commandLineParams.paths.add("src/main/webapp");
}
final Tomcat tomcat = new Tomcat();
// set directory for temp files
tomcat.setBaseDir(resolveTomcatBaseDir(commandLineParams.port));
// initialize the connector
Connector nioConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
nioConnector.setPort(commandLineParams.port);
tomcat.setConnector(nioConnector);
tomcat.getService().addConnector(tomcat.getConnector());
tomcat.setPort(commandLineParams.port);
if (commandLineParams.paths.size() > 1) {
System.out.println("FYI... Since you specified more than one path, the context paths will be automatically set to the name of the path without the extension. A path that resolves to a context path of \"/ROOT\" will be replaced with \"/\"");
if(commandLineParams.contextPath != null) {
System.out.println("WARNING: context-path is ignored when more than one path or war file is specified");
}
if(commandLineParams.contextXml != null) {
System.out.println("WARNING: context-xml is ignored when more than one path or war file is specified");
}
}
Context ctx = null;
for (String path : commandLineParams.paths) {
File war = new File(path);
if (!war.exists()) {
System.err.println("The specified path \"" + path + "\" does not exist.");
jCommander.usage();
System.exit(1);
}
String ctxName = "";
// Use the commandline context-path (or default) if there is only one war
if (commandLineParams.paths.size() == 1) {
// warn if the contextPath doesn't start with a '/'. This causes issues serving content at the context root.
if (commandLineParams.contextPath.length() > 0 && !commandLineParams.contextPath.startsWith("/")) {
System.out.println("WARNING: You entered a path: [" + commandLineParams.contextPath + "]. Your path should start with a '/'. Tomcat will update this for you, but you may still experience issues.");
}
ctxName = commandLineParams.contextPath;
}
else {
ctxName = "/" + FilenameUtils.removeExtension(war.getName());
if (ctxName.equals("/ROOT") || (commandLineParams.paths.size() == 1)) {
ctxName = "/";
}
}
System.out.println("Adding Context " + ctxName + " for " + war.getPath());
//Context ctx = tomcat.addWebapp(ctxName, war.getAbsolutePath());
ctx = tomcat.addWebapp(ctxName, war.getAbsolutePath());
}
if(!commandLineParams.shutdownOverride) {
final String ctxName = ctx.getName();
// allow Tomcat to shutdown if a context failure is detected
ctx.addLifecycleListener(new LifecycleListener() {
public void lifecycleEvent(LifecycleEvent event) {
if (event.getLifecycle().getState() == LifecycleState.FAILED) {
Server server = tomcat.getServer();
if (server instanceof StandardServer) {
System.err.println("SEVERE: Context [" + ctxName + "] failed in [" + event.getLifecycle().getClass().getName() + "] lifecycle. Allowing Tomcat to shutdown.");
((StandardServer) server).stopAwait();
}
}
}
});
}
// set the context xml location if there is only one war
if(commandLineParams.contextXml != null && commandLineParams.paths.size() == 1) {
System.out.println("Using context config: " + commandLineParams.contextXml);
ctx.setConfigFile(new File(commandLineParams.contextXml).toURI().toURL());
}
// set the session manager
if (commandLineParams.sessionStore != null) {
SessionStore.getInstance(commandLineParams.sessionStore).configureSessionStore(commandLineParams, ctx);
}
//set the session timeout
if(commandLineParams.sessionTimeout != null) {
ctx.setSessionTimeout(commandLineParams.sessionTimeout);
}
commandLineParams = null;
//start the server
tomcat.start();
tomcat.getServer().await();
}
#location 81
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Process exec(
String namespace, String name, String[] command, String container, boolean stdin, boolean tty)
throws ApiException, IOException {
return newExecutionBuilder(namespace, name, command)
.setContainer(container)
.setStdin(stdin)
.setTty(tty)
.execute();
}
|
#vulnerable code
public Process exec(
String namespace, String name, String[] command, String container, boolean stdin, boolean tty)
throws ApiException, IOException {
if (container == null) {
CoreV1Api api = new CoreV1Api(apiClient);
V1Pod pod = api.readNamespacedPod(name, namespace, "false", null, null);
container = pod.getSpec().getContainers().get(0).getName();
}
String path = makePath(namespace, name, command, container, stdin, tty);
ExecProcess exec = new ExecProcess(apiClient);
WebSocketStreamHandler handler = exec.getHandler();
WebSockets.stream(path, "GET", apiClient, handler);
return exec;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Benchmark
public void fastjson() {
JSON.parseObject(JsoniterBenchmarkState.inputString, byte[].class);
}
|
#vulnerable code
@Benchmark
public void fastjson() {
JSONScanner scanner = new JSONScanner(JsoniterBenchmarkState.inputString);
scanner.nextToken();
do {
scanner.nextToken();
scanner.intValue();
scanner.nextToken();
} while (scanner.token() == JSONToken.COMMA);
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static ApiClient defaultClient() throws IOException {
return ClientBuilder.defaults().build();
}
|
#vulnerable code
public static ApiClient defaultClient() throws IOException {
String kubeConfig = System.getenv(ENV_KUBECONFIG);
if (kubeConfig != null) {
return fromConfig(new FileReader(kubeConfig));
}
File config = new File(
new File(System.getenv(KubeConfig.ENV_HOME),
KubeConfig.KUBEDIR),
KubeConfig.KUBECONFIG);
if (config.exists()) {
return fromConfig(new FileReader(config));
}
File clusterCA = new File(SERVICEACCOUNT_CA_PATH);
if (clusterCA.exists()) {
return fromCluster();
}
ApiClient client = new ApiClient();
client.setBasePath(DEFAULT_FALLBACK_HOST);
return client;
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Benchmark
public void fastjson() {
JSONScanner scanner = new JSONScanner(JsoniterBenchmarkState.inputString);
scanner.nextToken();
do {
scanner.nextToken();
scanner.intValue();
scanner.nextToken();
} while (scanner.token() == JSONToken.COMMA);
}
|
#vulnerable code
@Benchmark
public void fastjson() {
new JSONReaderScanner(new InputStreamReader(new ByteArrayInputStream(JsoniterBenchmarkState.input))).intValue();
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Benchmark
public void jsoniter() throws IOException {
Jsoniter jsoniter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes);
byte[] val = new byte[3];
jsoniter.Read(val);
}
|
#vulnerable code
@Benchmark
public void jsoniter() throws IOException {
Jsoniter iter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes);
while (iter.ReadArray()) {
iter.ReadUnsignedInt();
}
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static ApiClient fromConfig(InputStream stream) throws IOException {
return fromConfig(new InputStreamReader(stream, StandardCharsets.UTF_8.name()));
}
|
#vulnerable code
public static ApiClient fromConfig(InputStream stream) throws IOException {
return fromConfig(new InputStreamReader(stream)); // TODO UTF-8
}
#location 2
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public <T extends Message> ObjectOrStatus<T> request(
T.Builder builder, String path, String method, T body, String apiVersion, String kind)
throws ApiException, IOException {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", MEDIA_TYPE);
headers.put("Accept", MEDIA_TYPE);
String[] localVarAuthNames = new String[] {"BearerToken"};
Request request =
apiClient.buildRequest(
path,
method,
new ArrayList<Pair>(),
new ArrayList<Pair>(),
null,
headers,
new HashMap<String, String>(),
new HashMap<String, Object>(),
localVarAuthNames,
null);
if (body != null) {
byte[] bytes = encode(body, apiVersion, kind);
switch (method) {
case "POST":
request =
request
.newBuilder()
.post(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PUT":
request =
request
.newBuilder()
.put(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PATCH":
request =
request
.newBuilder()
.patch(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
default:
throw new ApiException("Unknown proto client API method: " + method);
}
}
return getObjectOrStatusFromServer(builder, request);
}
|
#vulnerable code
public <T extends Message> ObjectOrStatus<T> request(
T.Builder builder, String path, String method, T body, String apiVersion, String kind)
throws ApiException, IOException {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", MEDIA_TYPE);
headers.put("Accept", MEDIA_TYPE);
String[] localVarAuthNames = new String[] {"BearerToken"};
Request request =
apiClient.buildRequest(
path,
method,
new ArrayList<Pair>(),
new ArrayList<Pair>(),
null,
headers,
new HashMap<String, String>(),
new HashMap<String, Object>(),
localVarAuthNames,
null);
if (body != null) {
byte[] bytes = encode(body, apiVersion, kind);
switch (method) {
case "POST":
request =
request
.newBuilder()
.post(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PUT":
request =
request
.newBuilder()
.put(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
case "PATCH":
request =
request
.newBuilder()
.patch(RequestBody.create(MediaType.parse(MEDIA_TYPE), bytes))
.build();
break;
default:
throw new ApiException("Unknown proto client API method: " + method);
}
}
Response resp = apiClient.getHttpClient().newCall(request).execute();
Unknown u = parse(resp.body().byteStream());
resp.body().close();
if (u.getTypeMeta().getApiVersion().equals("v1")
&& u.getTypeMeta().getKind().equals("Status")) {
Status status = Status.newBuilder().mergeFrom(u.getRaw()).build();
return new ObjectOrStatus(null, status);
}
return new ObjectOrStatus((T) builder.mergeFrom(u.getRaw()).build(), null);
}
#location 49
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static ApiClient fromConfig(String fileName) throws IOException {
KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(fileName)); // TODO UTF-8
config.setFile(new File(fileName));
return fromConfig(config);
}
|
#vulnerable code
public static ApiClient fromConfig(String fileName) throws IOException {
return fromConfig(new FileReader(fileName));
}
#location 2
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static ClientBuilder standard(boolean persistConfig) throws IOException {
final File kubeConfig = findConfigFromEnv();
ClientBuilder clientBuilderEnv = getClientBuilder(persistConfig, kubeConfig);
if (clientBuilderEnv != null) return clientBuilderEnv;
final File config = findConfigInHomeDir();
ClientBuilder clientBuilderHomeDir = getClientBuilder(persistConfig, config);
if (clientBuilderHomeDir != null) return clientBuilderHomeDir;
final File clusterCa = new File(SERVICEACCOUNT_CA_PATH);
if (clusterCa.exists()) {
return cluster();
}
return new ClientBuilder();
}
|
#vulnerable code
public static ClientBuilder standard(boolean persistConfig) throws IOException {
final File kubeConfig = findConfigFromEnv();
if (kubeConfig != null) {
try (BufferedReader kubeConfigReader =
new BufferedReader(
new InputStreamReader(
new FileInputStream(kubeConfig), StandardCharsets.UTF_8.name()))) {
KubeConfig kc = KubeConfig.loadKubeConfig(kubeConfigReader);
if (persistConfig) {
kc.setPersistConfig(new FilePersister(kubeConfig));
}
kc.setFile(kubeConfig);
return kubeconfig(kc);
}
}
final File config = findConfigInHomeDir();
if (config != null) {
try (BufferedReader configReader =
new BufferedReader(
new InputStreamReader(new FileInputStream(config), StandardCharsets.UTF_8.name()))) {
KubeConfig kc = KubeConfig.loadKubeConfig(configReader);
if (persistConfig) {
kc.setPersistConfig(new FilePersister(config));
}
kc.setFile(config);
return kubeconfig(kc);
}
}
final File clusterCa = new File(SERVICEACCOUNT_CA_PATH);
if (clusterCa.exists()) {
return cluster();
}
return new ClientBuilder();
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) {
try {
Example operation = new Example();
operation.executeCommand();
} catch (ApiException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
|
#vulnerable code
public static void main(String[] args) throws IOException, ApiException {
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
CoreV1Api api = new CoreV1Api();
V1PodList list =
api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
for (V1Pod item : list.getItems()) {
System.out.println(item.getMetadata().getName());
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private ApiListType executeRequest(Call call) throws IOException, ApiException {
return client.handleResponse(call.execute(), listType);
}
|
#vulnerable code
private ApiListType executeRequest(Call call)
throws IOException, ApiException, ObjectMetaReflectException {
ApiListType data = client.handleResponse(call.execute(), listType);
V1ListMeta listMetaData = Reflect.listMetadata(data);
continueToken = listMetaData.getContinue();
return data;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Benchmark
public void jsoniter() throws IOException {
Jsoniter iter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes);
while (iter.ReadArray()) {
iter.ReadUnsignedInt();
}
}
|
#vulnerable code
@Benchmark
public void jsoniter() throws IOException {
Jsoniter.parse(new ByteArrayInputStream(JsoniterBenchmarkState.input), 4096).ReadUnsignedInt();
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void writeToStream(DataOutputStream os) throws IOException {
WritableByteChannel dataChannel = Channels.newChannel(os);
os.writeInt(getOriginalSize());
os.writeInt(getSamplingRateSA());
os.writeInt(getSamplingRateISA());
os.writeInt(getSamplingRateNPA());
os.writeInt(getSampleBitWidth());
os.writeInt(getAlphabetSize());
for (int i = 0; i < getAlphabetSize(); i++) {
os.writeInt(alphabet[i]);
}
ByteBuffer bufSA = ByteBuffer.allocate(sa.limit() * SuccinctConstants.LONG_SIZE_BYTES);
bufSA.asLongBuffer().put(sa.buffer());
dataChannel.write(bufSA.order(ByteOrder.BIG_ENDIAN));
sa.rewind();
ByteBuffer bufISA = ByteBuffer.allocate(isa.limit() * SuccinctConstants.LONG_SIZE_BYTES);
bufISA.asLongBuffer().put(isa.buffer());
dataChannel.write(bufISA.order(ByteOrder.BIG_ENDIAN));
isa.rewind();
ByteBuffer bufColOff =
ByteBuffer.allocate(getAlphabetSize() * SuccinctConstants.LONG_SIZE_BYTES);
bufColOff.asLongBuffer().put(columnoffsets.buffer());
dataChannel.write(bufColOff.order(ByteOrder.BIG_ENDIAN));
columnoffsets.rewind();
for (int i = 0; i < columns.length; i++) {
os.writeInt(columns[i].limit());
dataChannel.write(columns[i].order(ByteOrder.BIG_ENDIAN));
columns[i].rewind();
}
}
|
#vulnerable code
public void writeToStream(DataOutputStream os) throws IOException {
WritableByteChannel dataChannel = Channels.newChannel(os);
os.writeInt(getOriginalSize());
os.writeInt(getSamplingRateSA());
os.writeInt(getSamplingRateISA());
os.writeInt(getSamplingRateNPA());
os.writeInt(getSampleBitWidth());
os.writeInt(getAlphabetSize());
for (Byte c : alphabetMap.keySet()) {
Pair<Integer, Integer> cval = alphabetMap.get(c);
os.write(c);
os.writeInt(cval.first);
os.writeInt(cval.second);
}
os.write(alphabet);
ByteBuffer bufSA = ByteBuffer.allocate(sa.limit() * SuccinctConstants.LONG_SIZE_BYTES);
bufSA.asLongBuffer().put(sa.buffer());
dataChannel.write(bufSA.order(ByteOrder.BIG_ENDIAN));
sa.rewind();
ByteBuffer bufISA = ByteBuffer.allocate(isa.limit() * SuccinctConstants.LONG_SIZE_BYTES);
bufISA.asLongBuffer().put(isa.buffer());
dataChannel.write(bufISA.order(ByteOrder.BIG_ENDIAN));
isa.rewind();
ByteBuffer bufColOff =
ByteBuffer.allocate(getAlphabetSize() * SuccinctConstants.LONG_SIZE_BYTES);
bufColOff.asLongBuffer().put(columnoffsets.buffer());
dataChannel.write(bufColOff.order(ByteOrder.BIG_ENDIAN));
columnoffsets.rewind();
for (int i = 0; i < columns.length; i++) {
os.writeInt(columns[i].limit());
dataChannel.write(columns[i].order(ByteOrder.BIG_ENDIAN));
columns[i].rewind();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
if (args.length < 2 || args.length > 3) {
System.err.println("Parameters: [input-path] [output-path] <[file-type]>");
System.exit(-1);
}
File file = new File(args[0]);
if (file.length() > 1L << 31) {
System.err.println("Cant handle files > 2GB");
System.exit(-1);
}
FileOutputStream fos = new FileOutputStream(args[1]);
DataOutputStream os = new DataOutputStream(fos);
String type = "text-file";
if (args.length == 3) {
type = args[2];
}
long start = System.currentTimeMillis();
SuccinctCore.LOG.setLevel(Level.ALL);
switch (type) {
case "text-file": {
SuccinctFileBuffer.construct(readTextFile(file), os);
break;
}
case "binary-file": {
SuccinctFileBuffer.construct(readBinaryFile(file), os);
break;
}
case "indexed-text-file": {
char[] fileData = readTextFile(file);
IntArrayList offsets = new IntArrayList();
offsets.add(0);
for (int i = 0; i < fileData.length; i++) {
if (fileData[i] == '\n') {
offsets.add(i + 1);
}
}
SuccinctIndexedFileBuffer.construct(fileData, offsets.toArray(), os);
break;
}
case "indexed-binary-file": {
byte[] fileData = readBinaryFile(file);
IntArrayList offsets = new IntArrayList();
offsets.add(0);
for (int i = 0; i < fileData.length; i++) {
if (fileData[i] == '\n') {
offsets.add(i + 1);
}
}
SuccinctIndexedFileBuffer.construct(fileData, offsets.toArray(), os);
break;
}
default:
throw new UnsupportedOperationException("Unsupported mode: " + type);
}
long end = System.currentTimeMillis();
System.out.println("Time to construct: " + (end - start) / 1000 + "s");
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
if (args.length < 2 || args.length > 3) {
System.err.println("Parameters: [input-path] [output-path] <[type]>");
System.exit(-1);
}
File file = new File(args[0]);
if (file.length() > 1L << 31) {
System.err.println("Cant handle files > 2GB");
System.exit(-1);
}
byte[] fileData = new byte[(int) file.length()];
System.out.println("File size: " + fileData.length + " bytes");
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData, 0, (int) file.length());
FileOutputStream fos = new FileOutputStream(args[1]);
DataOutputStream os = new DataOutputStream(fos);
String type = "file";
if (args.length == 3) {
type = args[2];
}
long start = System.currentTimeMillis();
SuccinctCore.LOG.setLevel(Level.ALL);
switch (type) {
case "file": {
SuccinctFileBuffer.construct(fileData, os);
break;
}
case "indexed-file": {
IntArrayList offsets = new IntArrayList();
offsets.add(0);
for (int i = 0; i < fileData.length; i++) {
if (fileData[i] == '\n') {
offsets.add(i + 1);
}
}
SuccinctIndexedFileBuffer.construct(fileData, offsets.toArray(), os);
break;
}
default:
throw new UnsupportedOperationException("Unsupported mode: " + type);
}
long end = System.currentTimeMillis();
System.out.println("Time to construct: " + (end - start) / 1000 + "s");
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void setUp() throws Exception {
super.setUp();
instance = new QSufSort();
File inputFile = new File("data/test_file");
byte[] fileData = new byte[(int) inputFile.length()];
DataInputStream dis = new DataInputStream(
new FileInputStream(inputFile));
dis.readFully(fileData);
byte[] data = (new String(fileData) + (char) 1).getBytes();
instance.buildSuffixArray(data);
fileSize = (int) (inputFile.length() + 1);
}
|
#vulnerable code
public void setUp() throws Exception {
super.setUp();
instance = new QSufSort();
File file = new File("data/test_file");
byte[] data = new byte[(int) file.length()];
try {
new FileInputStream(file).read(data);
} catch (Exception e) {
e.printStackTrace();
assertTrue("Could not read from data/test_file.", false);
}
instance.buildSuffixArray(data);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void readFromFile(String path) throws IOException {
readCoreFromFile(path);
}
|
#vulnerable code
public void readFromFile(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
DataInputStream is = new DataInputStream(fis);
readFromStream(is);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
if(args.length != 1) {
System.err.println("Paramters: [input-path]");
System.exit(-1);
}
SuccinctFileBuffer succinctFileBuffer;
if(args[0].endsWith(".succinct")) {
succinctFileBuffer = new SuccinctFileBuffer(args[0], StorageMode.MEMORY_ONLY);
} else {
File file = new File(args[0]);
if (file.length() > 1L << 31) {
System.err.println("Cant handle files > 2GB");
System.exit(-1);
}
byte[] fileData = new byte[(int) file.length()];
System.out.println("File size: " + fileData.length + " bytes");
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData, 0, (int) file.length());
succinctFileBuffer = new SuccinctFileBuffer(fileData);
}
BufferedReader shellReader = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("succinct> ");
String command = shellReader.readLine();
String[] cmdArray = command.split(" ");
if(cmdArray[0].compareTo("count") == 0) {
if(cmdArray.length != 2) {
System.err.println("Could not parse count query.");
System.err.println("Usage: count [query]");
continue;
}
System.out.println("Count[" + cmdArray[1] + "] = " + succinctFileBuffer.count(cmdArray[1].getBytes()));
} else if(cmdArray[0].compareTo("search") == 0) {
if(cmdArray.length != 2) {
System.err.println("Could not parse search query.");
System.err.println("Usage: search [query]");
continue;
}
Long[] results = succinctFileBuffer.search(cmdArray[1].getBytes());
System.out.println("Result size = " + results.length);
System.out.print("Search[" + cmdArray[1] + "] = {");
if(results.length < 10) {
for (int i = 0; i < results.length; i++) {
System.out.print(results[i] + ", ");
}
System.out.println("}");
} else {
for (int i = 0; i < 10; i++) {
System.out.print(results[i] + ", ");
}
System.out.println("...}");
}
} else if(cmdArray[0].compareTo("extract") == 0) {
if(cmdArray.length != 3) {
System.err.println("Could not parse extract query.");
System.err.println("Usage: extract [offset] [length]");
continue;
}
Integer offset, length;
try {
offset = Integer.parseInt(cmdArray[1]);
} catch (Exception e) {
System.err.println("[Extract]: Failed to parse offset: must be an integer.");
continue;
}
try {
length = Integer.parseInt(cmdArray[2]);
} catch (Exception e) {
System.err.println("[Extract]: Failed to parse length: must be an integer.");
continue;
}
System.out.println("Extract[" + offset + ", " + length + "] = " + new String(succinctFileBuffer.extract(offset, length)));
} else if (cmdArray[0].compareTo("regex") == 0) {
if(cmdArray.length != 2) {
System.err.println("Could not parse regex query.");
System.err.println("Usage: regex [query]");
continue;
}
Map<Long, Integer> results = null;
try {
results = succinctFileBuffer.regexSearch(cmdArray[1]);
} catch (RegExParsingException e) {
System.err.println("Could not parse regular expression: [" + cmdArray[1] + "]");
continue;
}
System.out.println("Result size = " + results.size());
System.out.print("Regex[" + cmdArray[1] + "] = {");
int count = 0;
for (Map.Entry<Long, Integer> entry: results.entrySet()) {
if (count >= 10) break;
System.out.print("offset = " + entry.getKey() + "; len = " + entry.getValue() + ", ");
count++;
}
System.out.println("...}");
} else if(cmdArray[0].compareTo("quit") == 0) {
System.out.println("Quitting...");
break;
} else {
System.err.println("Unknown command. Command must be one of: count, search, extract, quit.");
continue;
}
}
}
|
#vulnerable code
public static void main(String[] args) throws IOException {
if(args.length != 1) {
System.err.println("Paramters: [input-path]");
System.exit(-1);
}
File file = new File(args[0]);
if(file.length() > 1L<<31) {
System.err.println("Cant handle files > 2GB");
System.exit(-1);
}
byte[] fileData = new byte[(int) file.length()];
System.out.println("File size: " + fileData.length + " bytes");
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData, 0, (int)file.length());
SuccinctFileBuffer succinctFileBuffer = new SuccinctFileBuffer(fileData);
BufferedReader shellReader = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("succinct> ");
String command = shellReader.readLine();
String[] cmdArray = command.split(" ");
if(cmdArray[0].compareTo("count") == 0) {
if(cmdArray.length != 2) {
System.err.println("Could not parse count query.");
System.err.println("Usage: count [query]");
continue;
}
System.out.println("Count[" + cmdArray[1] + "] = " + succinctFileBuffer.count(cmdArray[1].getBytes()));
} else if(cmdArray[0].compareTo("search") == 0) {
if(cmdArray.length != 2) {
System.err.println("Could not parse search query.");
System.err.println("Usage: search [query]");
continue;
}
Long[] results = succinctFileBuffer.search(cmdArray[1].getBytes());
System.out.println("Result size = " + results.length);
System.out.print("Search[" + cmdArray[1] + "] = {");
if(results.length < 10) {
for (int i = 0; i < results.length; i++) {
System.out.print(results[i] + ", ");
}
System.out.println("}");
} else {
for (int i = 0; i < 10; i++) {
System.out.print(results[i] + ", ");
}
System.out.println("...}");
}
} else if(cmdArray[0].compareTo("extract") == 0) {
if(cmdArray.length != 3) {
System.err.println("Could not parse extract query.");
System.err.println("Usage: extract [offset] [length]");
continue;
}
Integer offset, length;
try {
offset = Integer.parseInt(cmdArray[1]);
} catch (Exception e) {
System.err.println("[Extract]: Failed to parse offset: must be an integer.");
continue;
}
try {
length = Integer.parseInt(cmdArray[2]);
} catch (Exception e) {
System.err.println("[Extract]: Failed to parse length: must be an integer.");
continue;
}
System.out.println("Extract[" + offset + ", " + length + "] = " + new String(succinctFileBuffer.extract(offset, length)));
} else if (cmdArray[0].compareTo("regex") == 0) {
if(cmdArray.length != 2) {
System.err.println("Could not parse regex query.");
System.err.println("Usage: regex [query]");
continue;
}
Map<Long, Integer> results = null;
try {
results = succinctFileBuffer.regexSearch(cmdArray[1]);
} catch (RegExParsingException e) {
System.err.println("Could not parse regular expression: [" + cmdArray[1] + "]");
continue;
}
System.out.println("Result size = " + results.size());
System.out.print("Regex[" + cmdArray[1] + "] = {");
int count = 0;
for (Map.Entry<Long, Integer> entry: results.entrySet()) {
if (count >= 10) break;
System.out.print("offset = " + entry.getKey() + "; len = " + entry.getValue() + ", ");
count++;
}
System.out.println("...}");
} else if(cmdArray[0].compareTo("quit") == 0) {
System.out.println("Quitting...");
break;
} else {
System.err.println("Unknown command. Command must be one of: count, search, extract, quit.");
continue;
}
}
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<StorageState> decode(byte[] bs, Charset charset) throws IOException {
// 获取对象转换定义
ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(StorageState.class);
int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize();
if (bs.length % fixFieldsTotalSize != 0) {
throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length
+ " is invalid!");
}
// 计算反馈对象数量
int count = bs.length / fixFieldsTotalSize;
int offset = 0;
List<StorageState> results = new ArrayList<StorageState>(count);
for (int i = 0; i < count; i++) {
byte[] one = new byte[fixFieldsTotalSize];
System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize);
results.add(FdfsParamMapper.map(one, StorageState.class, charset));
offset += fixFieldsTotalSize;
}
return results;
}
|
#vulnerable code
private List<StorageState> decode(byte[] bs, Charset charset) throws IOException {
// 获取对象转换定义
ObjectMateData objectMateData = FdfsParamMapper.getObjectMap(StorageState.class);
int fixFieldsTotalSize = objectMateData.getFieldsFixTotalSize();
if (bs.length % fixFieldsTotalSize != 0) {
throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length
+ " is invalid!");
}
// 计算反馈对象数量
int count = bs.length / fixFieldsTotalSize;
int offset = 0;
List<StorageState> results = new ArrayList<StorageState>(count);
for (int i = 0; i < count; i++) {
byte[] one = new byte[fixFieldsTotalSize];
System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize);
results.add(FdfsParamMapper.map(one, StorageState.class, charset));
offset += fixFieldsTotalSize;
}
return results;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<GroupState> decode(byte[] bs, Charset charset) throws IOException {
// 获取对象转换定义
ObjectMetaData objectMetaData = FdfsParamMapper.getObjectMap(GroupState.class);
int fixFieldsTotalSize = objectMetaData.getFieldsFixTotalSize();
if (bs.length % fixFieldsTotalSize != 0) {
throw new IOException("byte array length: " + bs.length + " is invalid!");
}
// 计算反馈对象数量
int count = bs.length / fixFieldsTotalSize;
int offset = 0;
List<GroupState> results = new ArrayList<GroupState>(count);
for (int i = 0; i < count; i++) {
byte[] one = new byte[fixFieldsTotalSize];
System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize);
results.add(FdfsParamMapper.map(one, GroupState.class, charset));
offset += fixFieldsTotalSize;
}
return results;
}
|
#vulnerable code
private List<GroupState> decode(byte[] bs, Charset charset) throws IOException {
// 获取对象转换定义
ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(GroupState.class);
int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize();
if (bs.length % fixFieldsTotalSize != 0) {
throw new IOException("byte array length: " + bs.length + " is invalid!");
}
// 计算反馈对象数量
int count = bs.length / fixFieldsTotalSize;
int offset = 0;
List<GroupState> results = new ArrayList<GroupState>(count);
for (int i = 0; i < count; i++) {
byte[] one = new byte[fixFieldsTotalSize];
System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize);
results.add(FdfsParamMapper.map(one, GroupState.class, charset));
offset += fixFieldsTotalSize;
}
return results;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected long getBodyLength(Charset charset) {
ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(this.getClass());
return objectMataData.getFieldsSendTotalByteSize(this, charset) + getFileSize();
}
|
#vulnerable code
protected long getBodyLength(Charset charset) {
ObjectMateData objectMateData = FdfsParamMapper.getObjectMap(this.getClass());
return objectMateData.getFieldsSendTotalByteSize(this, charset) + getFileSize();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void service() {
int i = 0;
try {
serverSocket = new ServerSocket(port);
} catch (BindException e) {
LOGGER.error("端口绑定错误", e.getCause());
throw new RuntimeException("端口已经被绑定");
} catch (IOException e1) {
LOGGER.error("其他错误", e1.getCause());
throw new RuntimeException(e1.getMessage());
}
while (true) {
Socket socket = null;
try {
i++;
socket = serverSocket.accept(); // 主线程获取客户端连接
LOGGER.debug("第{}个客户端成功连接!", i);
Thread workThread = new Thread(new Handler(socket)); // 创建线程
workThread.start(); // 启动线程
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
#vulnerable code
public void service() {
int i = 0;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
e1.printStackTrace();
}
while (true) {
Socket socket = null;
try {
i++;
socket = serverSocket.accept(); // 主线程获取客户端连接
System.out.println("第" + i + "个客户端成功连接!");
Thread workThread = new Thread(new Handler(socket)); // 创建线程
workThread.start(); // 启动线程
} catch (Exception e) {
e.printStackTrace();
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testConnectionManager() {
// 初始化
TrackerConnectionManager manager = crtInvalidateIpListManager();
List<GroupState> list = null;
// 第一次执行
try {
// 连接失败
list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand());
fail("No exception thrown.");
} catch (Exception e) {
assertTrue(e instanceof FdfsConnectException);
}
// 第二次执行
try {
// 连接失败
list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand());
fail("No exception thrown.");
} catch (Exception e) {
assertTrue(e instanceof FdfsConnectException);
}
assertNull(list);
}
|
#vulnerable code
@Test
public void testConnectionManager() {
// 初始化
TrackerConnectionManager manager = new TrackerConnectionManager(createPool());
manager.setTrackerList(trackerIpList);
manager.initTracker();
List<GroupState> list = null;
// 第一次执行
try {
// 连接失败
list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand());
fail("No exception thrown.");
} catch (Exception e) {
assertTrue(e instanceof FdfsConnectException);
}
// 第二次执行
try {
// 连接失败
list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand());
fail("No exception thrown.");
} catch (Exception e) {
assertTrue(e instanceof FdfsConnectException);
}
LOGGER.debug("执行结果{}", list);
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCheck() {
// 创建连接测试
Connection conn = createConnection();
LOGGER.debug("当前连接状态={}", conn.isValid());
conn.close();
}
|
#vulnerable code
public void testCheck() {
// 创建连接测试
Connection conn = createConnection();
System.out.println("当前连接状态" + conn.isValid());
conn.close();
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<StorageState> decode(byte[] bs, Charset charset) throws IOException {
// 获取对象转换定义
ObjectMetaData objectMetaData = FdfsParamMapper.getObjectMap(StorageState.class);
int fixFieldsTotalSize = objectMetaData.getFieldsFixTotalSize();
if (bs.length % fixFieldsTotalSize != 0) {
throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length
+ " is invalid!");
}
// 计算反馈对象数量
int count = bs.length / fixFieldsTotalSize;
int offset = 0;
List<StorageState> results = new ArrayList<StorageState>(count);
for (int i = 0; i < count; i++) {
byte[] one = new byte[fixFieldsTotalSize];
System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize);
results.add(FdfsParamMapper.map(one, StorageState.class, charset));
offset += fixFieldsTotalSize;
}
return results;
}
|
#vulnerable code
private List<StorageState> decode(byte[] bs, Charset charset) throws IOException {
// 获取对象转换定义
ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(StorageState.class);
int fixFieldsTotalSize = objectMataData.getFieldsFixTotalSize();
if (bs.length % fixFieldsTotalSize != 0) {
throw new IOException("fixFieldsTotalSize=" + fixFieldsTotalSize + "but byte array length: " + bs.length
+ " is invalid!");
}
// 计算反馈对象数量
int count = bs.length / fixFieldsTotalSize;
int offset = 0;
List<StorageState> results = new ArrayList<StorageState>(count);
for (int i = 0; i < count; i++) {
byte[] one = new byte[fixFieldsTotalSize];
System.arraycopy(bs, offset, one, 0, fixFieldsTotalSize);
results.add(FdfsParamMapper.map(one, StorageState.class, charset));
offset += fixFieldsTotalSize;
}
return results;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
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.