instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testDeleteViewIndexSequences() throws Exception {
createBaseTable(tableName, false, null, null);
Connection conn1 = getConnection();
Connection conn2 = getConnection();
String viewName = schemaName + "." + VIEW_NAME;
conn1.createStatement().execute("CREATE VIEW " + viewName + " AS SELECT * FROM " + tableName);
conn1.createStatement().execute("CREATE INDEX " + indexName + " ON " + viewName + " (v1)");
conn2.createStatement().executeQuery("SELECT * FROM " + tableName).next();
String query = "SELECT sequence_schema, sequence_name, current_value, increment_by FROM SYSTEM.\"SEQUENCE\" WHERE sequence_schema like '%"
+ schemaName + "%'";
ResultSet rs = conn1.prepareStatement(query).executeQuery();
assertTrue(rs.next());
assertEquals(MetaDataUtil.getViewIndexSequenceSchemaName(PNameFactory.newName(tableName), isNamespaceMapped),
rs.getString("sequence_schema"));
assertEquals(MetaDataUtil.getViewIndexSequenceName(PNameFactory.newName(tableName), null, isNamespaceMapped),
rs.getString("sequence_name"));
assertEquals(-32767, rs.getInt("current_value"));
assertEquals(1, rs.getInt("increment_by"));
assertFalse(rs.next());
HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
conn1.createStatement().execute("DROP VIEW " + viewName);
conn1.createStatement().execute("DROP TABLE "+ tableName);
admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
assertFalse("View index table should be deleted.", admin.tableExists(TableName.valueOf(viewIndexPhysicalTableName)));
rs = conn2.createStatement().executeQuery("SELECT "
+ PhoenixDatabaseMetaData.SEQUENCE_SCHEMA + ","
+ PhoenixDatabaseMetaData.SEQUENCE_NAME
+ " FROM " + PhoenixDatabaseMetaData.SYSTEM_SEQUENCE);
assertFalse("View index sequences should be deleted.", rs.next());
}
|
#vulnerable code
@Test
public void testDeleteViewIndexSequences() throws Exception {
createBaseTable(tableName, false, null, null);
Connection conn1 = getConnection();
Connection conn2 = getConnection();
conn1.createStatement().execute("CREATE VIEW " + VIEW_NAME + " AS SELECT * FROM " + tableName);
conn1.createStatement().execute("CREATE INDEX " + indexName + " ON " + VIEW_NAME + " (v1)");
conn2.createStatement().executeQuery("SELECT * FROM " + tableName).next();
HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
conn1.createStatement().execute("DROP VIEW " + VIEW_NAME);
conn1.createStatement().execute("DROP TABLE "+ tableName);
admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
assertFalse("View index table should be deleted.", admin.tableExists(TableName.valueOf(viewIndexPhysicalTableName)));
ResultSet rs = conn2.createStatement().executeQuery("SELECT "
+ PhoenixDatabaseMetaData.SEQUENCE_SCHEMA + ","
+ PhoenixDatabaseMetaData.SEQUENCE_NAME
+ " FROM " + PhoenixDatabaseMetaData.SYSTEM_SEQUENCE);
assertFalse("View index sequences should be deleted.", rs.next());
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void initTxServiceClient() {
txZKClientService = TransactionFactory.getTransactionProvider().getTransactionContext().setTransactionClient(config, props, connectionInfo);
}
|
#vulnerable code
private void initTxServiceClient() {
txZKClientService = TransactionFactory.getTransactionFactory().getTransactionContext().setTransactionClient(config, props, connectionInfo);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public DataValue getDataForRule(Scenario scenario, Column phxMetaColumn) throws Exception {
// TODO Make a Set of Rules that have already been applied so that so we don't generate for every value
List<Scenario> scenarios = parser.getScenarios();
DataValue value = null;
if (scenarios.contains(scenario)) {
logger.debug("We found a correct Scenario");
// Assume the first rule map
Map<DataTypeMapping, List> ruleMap = modelList.get(0);
List<Column> ruleList = ruleMap.get(phxMetaColumn.getType());
// Make sure Column from Phoenix Metadata matches a rule column
if (ruleList.contains(phxMetaColumn)) {
// Generate some random data based on this rule
logger.debug("We found a correct column rule");
Column columnRule = getColumnForRule(ruleList, phxMetaColumn);
value = getDataValue(columnRule);
} else {
logger.warn("Attempted to apply rule to data, but could not find a rule to match type:"
+ phxMetaColumn.getType()
);
}
}
return value;
}
|
#vulnerable code
public DataValue getDataForRule(Scenario scenario, Column phxMetaColumn) throws Exception {
// TODO Make a Set of Rules that have already been applied so that so we don't generate for every value
List<Scenario> scenarios = parser.getScenarios();
DataValue value = null;
if (scenarios.contains(scenario)) {
logger.debug("We found a correct Scenario");
// Assume the first rule map
Map<DataTypeMapping, List> ruleMap = modelList.get(0);
List<Column> ruleList = ruleMap.get(phxMetaColumn.getType());
// Make sure Column from Phoenix Metadata matches a rule column
if (ruleList.contains(phxMetaColumn)) {
// Generate some random data based on this rule
logger.debug("We found a correct column rule");
Column columnRule = getColumnForRule(ruleList, phxMetaColumn);
value = getDataValue(columnRule);
synchronized (value) {
// Add the prefix to the value if it exists.
if (columnRule.getPrefix() != null) {
value.setValue(columnRule.getPrefix() + value.getValue());
}
}
} else {
logger.warn("Attempted to apply rule to data, but could not find a rule to match type:"
+ phxMetaColumn.getType()
);
}
}
return value;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testLocalIndexTableRegionSplitPolicyAndSplitKeys() throws Exception {
createBaseTable(DATA_TABLE_NAME, null,"('e','i','o')");
Connection conn1 = DriverManager.getConnection(getUrl());
Connection conn2 = DriverManager.getConnection(getUrl());
conn1.createStatement().execute("CREATE LOCAL INDEX " + INDEX_TABLE_NAME + " ON " + DATA_TABLE_NAME + "(v1)");
conn2.createStatement().executeQuery("SELECT * FROM " + DATA_TABLE_FULL_NAME).next();
HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
HTableDescriptor htd = admin.getTableDescriptor(TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)));
assertEquals(IndexRegionSplitPolicy.class.getName(), htd.getValue(HTableDescriptor.SPLIT_POLICY));
try (HTable userTable = new HTable(admin.getConfiguration(),TableName.valueOf(DATA_TABLE_NAME))) {
try (HTable indexTable = new HTable(admin.getConfiguration(),TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)))) {
assertArrayEquals("Both user table and index table should have same split keys.", userTable.getStartKeys(), indexTable.getStartKeys());
}
}
}
|
#vulnerable code
@Test
public void testLocalIndexTableRegionSplitPolicyAndSplitKeys() throws Exception {
createBaseTable(DATA_TABLE_NAME, null,"('e','i','o')");
Connection conn1 = DriverManager.getConnection(getUrl());
Connection conn2 = DriverManager.getConnection(getUrl());
conn1.createStatement().execute("CREATE LOCAL INDEX " + INDEX_TABLE_NAME + " ON " + DATA_TABLE_NAME + "(v1)");
conn2.createStatement().executeQuery("SELECT * FROM " + DATA_TABLE_FULL_NAME).next();
HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
HTableDescriptor htd = admin.getTableDescriptor(TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)));
assertEquals(IndexRegionSplitPolicy.class.getName(), htd.getValue(HTableDescriptor.SPLIT_POLICY));
HTable userTable = new HTable(admin.getConfiguration(),TableName.valueOf(DATA_TABLE_NAME));
HTable indexTable = new HTable(admin.getConfiguration(),TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)));
assertArrayEquals("Both user table and index table should have same split keys.", userTable.getStartKeys(), indexTable.getStartKeys());
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testUpsertSelectSameBatchConcurrently() throws Exception {
try (Connection conn = driver.connect(url, props)) {
int numUpsertSelectRunners = 5;
ExecutorService exec = Executors.newFixedThreadPool(numUpsertSelectRunners);
CompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>(exec);
List<Future<Boolean>> futures = Lists.newArrayListWithExpectedSize(numUpsertSelectRunners);
// run one UPSERT SELECT for 100 rows (that locks the rows for a long time)
futures.add(completionService.submit(new UpsertSelectRunner(dataTable, 0, 105, 1)));
// run four UPSERT SELECTS for 5 rows (that overlap with slow running UPSERT SELECT)
for (int i = 0; i < 100; i += 25) {
futures.add(completionService.submit(new UpsertSelectRunner(dataTable, i, i+25, 5)));
}
int received = 0;
while (received < futures.size()) {
Future<Boolean> resultFuture = completionService.take();
Boolean result = resultFuture.get();
received++;
assertTrue(result);
}
exec.shutdownNow();
}
}
|
#vulnerable code
@Test
public void testUpsertSelectSameBatchConcurrently() throws Exception {
final String dataTable = generateUniqueName();
final String index = "IDX_" + dataTable;
// create the table and ensure its empty
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = driver.connect(url, props);
conn.createStatement()
.execute("CREATE TABLE " + dataTable + " (k INTEGER NOT NULL PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)");
// create the index and ensure its empty as well
conn.createStatement().execute("CREATE INDEX " + index + " ON " + dataTable + " (v1)");
conn = DriverManager.getConnection(getUrl(), props);
PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + dataTable + " VALUES(?,?,?)");
conn.setAutoCommit(false);
for (int i = 0; i < 100; i++) {
stmt.setInt(1, i);
stmt.setString(2, "v1" + i);
stmt.setString(3, "v2" + i);
stmt.execute();
}
conn.commit();
int numUpsertSelectRunners = 5;
ExecutorService exec = Executors.newFixedThreadPool(numUpsertSelectRunners);
CompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>(exec);
List<Future<Boolean>> futures = Lists.newArrayListWithExpectedSize(numUpsertSelectRunners);
// run one UPSERT SELECT for 100 rows (that locks the rows for a long time)
futures.add(completionService.submit(new UpsertSelectRunner(dataTable, 0, 105, 1)));
// run four UPSERT SELECTS for 5 rows (that overlap with slow running UPSERT SELECT)
for (int i = 0; i < 100; i += 25) {
futures.add(completionService.submit(new UpsertSelectRunner(dataTable, i, i+25, 5)));
}
int received = 0;
while (received < futures.size()) {
Future<Boolean> resultFuture = completionService.take();
Boolean result = resultFuture.get();
received++;
assertTrue(result);
}
exec.shutdownNow();
conn.close();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testLocalIndexTableRegionSplitPolicyAndSplitKeys() throws Exception {
createBaseTable(DATA_TABLE_NAME, null,"('e','i','o')");
Connection conn1 = DriverManager.getConnection(getUrl());
Connection conn2 = DriverManager.getConnection(getUrl());
conn1.createStatement().execute("CREATE LOCAL INDEX " + INDEX_TABLE_NAME + " ON " + DATA_TABLE_NAME + "(v1)");
conn2.createStatement().executeQuery("SELECT * FROM " + DATA_TABLE_FULL_NAME).next();
HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
HTableDescriptor htd = admin.getTableDescriptor(TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)));
assertEquals(IndexRegionSplitPolicy.class.getName(), htd.getValue(HTableDescriptor.SPLIT_POLICY));
try (HTable userTable = new HTable(admin.getConfiguration(),TableName.valueOf(DATA_TABLE_NAME))) {
try (HTable indexTable = new HTable(admin.getConfiguration(),TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)))) {
assertArrayEquals("Both user table and index table should have same split keys.", userTable.getStartKeys(), indexTable.getStartKeys());
}
}
}
|
#vulnerable code
@Test
public void testLocalIndexTableRegionSplitPolicyAndSplitKeys() throws Exception {
createBaseTable(DATA_TABLE_NAME, null,"('e','i','o')");
Connection conn1 = DriverManager.getConnection(getUrl());
Connection conn2 = DriverManager.getConnection(getUrl());
conn1.createStatement().execute("CREATE LOCAL INDEX " + INDEX_TABLE_NAME + " ON " + DATA_TABLE_NAME + "(v1)");
conn2.createStatement().executeQuery("SELECT * FROM " + DATA_TABLE_FULL_NAME).next();
HBaseAdmin admin = driver.getConnectionQueryServices(getUrl(), TestUtil.TEST_PROPERTIES).getAdmin();
HTableDescriptor htd = admin.getTableDescriptor(TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)));
assertEquals(IndexRegionSplitPolicy.class.getName(), htd.getValue(HTableDescriptor.SPLIT_POLICY));
HTable userTable = new HTable(admin.getConfiguration(),TableName.valueOf(DATA_TABLE_NAME));
HTable indexTable = new HTable(admin.getConfiguration(),TableName.valueOf(MetaDataUtil.getLocalIndexTableName(DATA_TABLE_NAME)));
assertArrayEquals("Both user table and index table should have same split keys.", userTable.getStartKeys(), indexTable.getStartKeys());
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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
@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
@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
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
@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
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
@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, 42, file);
int sector = df.write(0x1FFFF, ByteBuffer.wrap(b));
ByteBuffer buf = df.read(0x1FFFF, sector, b.length);
Assert.assertArrayEquals(b, buf.array());
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();
DataFile df = new DataFile(store, 42, file);
int sector = df.write(0x1FFFF, ByteBuffer.wrap(b));
ByteBuffer buf = df.read(0x1FFFF, sector, b.length);
Assert.assertArrayEquals(b, buf.array());
file.delete();
}
#location 11
#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
@Test
public void test() throws IOException
{
Store store = new Store(new java.io.File("d:/rs/07/cache"));//c:/rs/cache"));
store.load();
System.out.println(store);
}
|
#vulnerable code
@Test
public void test() throws IOException
{
Store store = new Store(new java.io.File("c:/rs/cache"));
store.load();
}
#location 5
#vulnerability type RESOURCE_LEAK
|
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 9
#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
@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
@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 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 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
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 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 gitColonUrlOtherHost() {
testURL("git://company.net/jenkinsci/jenkins.git", "company.net", "jenkinsci", "jenkins");
}
|
#vulnerable code
@Test
public void gitColonUrlOtherHost() {
GitHubRepositoryName repo = GitHubRepositoryName
.create("git://company.net/jenkinsci/jenkins.git");
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 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
@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
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 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
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
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 != 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
protected long getBodyLength(Charset charset) {
ObjectMetaData objectMetaData = FdfsParamMapper.getObjectMap(this.getClass());
return objectMetaData.getFieldsSendTotalByteSize(this, charset) + getFileSize();
}
|
#vulnerable code
protected long getBodyLength(Charset charset) {
ObjectMataData objectMataData = FdfsParamMapper.getObjectMap(this.getClass());
return objectMataData.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
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.
|
#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 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testImaging144() throws Exception {
tiffOutputSet.setGPSInDegrees(1.0, 1.0);
TiffOutputDirectory gpsDirectory = tiffOutputSet.getGPSDirectory();
TiffOutputField gpsVersionId = gpsDirectory.findField(GpsTagConstants.GPS_TAG_GPS_VERSION_ID);
assertNotNull(gpsVersionId);
assertTrue(gpsVersionId.bytesEqual(GpsTagConstants.GPS_VERSION));
}
|
#vulnerable code
@Test
public void testImaging144() throws Exception {
tiffOutputSet.setGPSInDegrees(1.0, 1.0);
TiffOutputDirectory gpsDirectory = tiffOutputSet.getGPSDirectory();
TiffOutputField gpsVersionId = getGpsVersionId(gpsDirectory);
assertNotNull(gpsVersionId);
assertTrue(gpsVersionId.bytesEqual(GpsTagConstants.GPS_VERSION));
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = null;
try {
bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
} finally {
if (bis != null) {
bis.close();
}
}
}
|
#vulnerable code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void dump()
{
PrintWriter pw = new PrintWriter(System.out);
dump(pw);
pw.flush();
}
|
#vulnerable code
public void dump()
{
dump(new PrintWriter(new OutputStreamWriter(System.out)));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public final void debugNumber(String msg, int data, int bytes)
{
PrintWriter pw = new PrintWriter(System.out);
debugNumber(pw, msg,
data, bytes);
pw.flush();
}
|
#vulnerable code
public final void debugNumber(String msg, int data, int bytes)
{
debugNumber(new PrintWriter(new OutputStreamWriter(System.out)), msg,
data, bytes);
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public byte[] compress(byte bytes[]) throws IOException {
MyByteArrayOutputStream baos = null;
try {
baos = new MyByteArrayOutputStream(
bytes.length * 2); // max length 1 extra byte for every 128
int ptr = 0;
int count = 0;
while (ptr < bytes.length) {
count++;
int dup = findNextDuplicate(bytes, ptr);
if (dup == ptr) // write run length
{
int len = findRunLength(bytes, dup);
int actual_len = Math.min(len, 128);
baos.write(-(actual_len - 1));
baos.write(bytes[ptr]);
ptr += actual_len;
} else { // write literals
int len = dup - ptr;
if (dup > 0) {
int runlen = findRunLength(bytes, dup);
if (runlen < 3) // may want to discard next run.
{
int nextptr = ptr + len + runlen;
int nextdup = findNextDuplicate(bytes, nextptr);
if (nextdup != nextptr) // discard 2-byte run
{
dup = nextdup;
len = dup - ptr;
}
}
}
if (dup < 0)
len = bytes.length - ptr;
int actual_len = Math.min(len, 128);
baos.write(actual_len - 1);
for (int i = 0; i < actual_len; i++) {
baos.write(bytes[ptr]);
ptr++;
}
}
}
byte result[] = baos.toByteArray();
return result;
} finally {
if (baos != null) {
baos.close();
}
}
}
|
#vulnerable code
public byte[] compress(byte bytes[]) throws IOException {
MyByteArrayOutputStream baos = new MyByteArrayOutputStream(
bytes.length * 2); // max length 1 extra byte for every 128
int ptr = 0;
int count = 0;
while (ptr < bytes.length) {
count++;
int dup = findNextDuplicate(bytes, ptr);
if (dup == ptr) // write run length
{
int len = findRunLength(bytes, dup);
int actual_len = Math.min(len, 128);
baos.write(-(actual_len - 1));
baos.write(bytes[ptr]);
ptr += actual_len;
} else { // write literals
int len = dup - ptr;
if (dup > 0) {
int runlen = findRunLength(bytes, dup);
if (runlen < 3) // may want to discard next run.
{
int nextptr = ptr + len + runlen;
int nextdup = findNextDuplicate(bytes, nextptr);
if (nextdup != nextptr) // discard 2-byte run
{
dup = nextdup;
len = dup - ptr;
}
}
}
if (dup < 0)
len = bytes.length - ptr;
int actual_len = Math.min(len, 128);
baos.write(actual_len - 1);
for (int i = 0; i < actual_len; i++) {
baos.write(bytes[ptr]);
ptr++;
}
}
}
byte result[] = baos.toByteArray();
return result;
}
#location 46
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static byte[] decompressModifiedHuffman(final byte[] compressed,
final int width, final int height) throws ImageReadException {
try (ByteArrayInputStream baos = new ByteArrayInputStream(compressed);
BitInputStreamFlexible inputStream = new BitInputStreamFlexible(baos);
BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
for (int y = 0; y < height; y++) {
int color = WHITE;
int rowLength;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
if (rowLength == width) {
inputStream.flushCache();
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
return ret;
} catch (final IOException ioException) {
throw new ImageReadException("Error reading image to decompress", ioException);
}
}
|
#vulnerable code
public static byte[] decompressModifiedHuffman(final byte[] compressed,
final int width, final int height) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(
new ByteArrayInputStream(compressed));
BitArrayOutputStream outputStream = null;
boolean canThrow = false;
try {
outputStream = new BitArrayOutputStream();
for (int y = 0; y < height; y++) {
int color = WHITE;
int rowLength;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
if (rowLength == width) {
inputStream.flushCache();
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
canThrow = true;
return ret;
} finally {
try {
IoUtils.closeQuietly(canThrow, outputStream);
} catch (final IOException ioException) {
throw new ImageReadException("I/O error", ioException);
}
}
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void removeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos)) {
new ExifRewriter().removeExifMetadata(jpegImageFile, os);
}
}
|
#vulnerable code
public void removeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().removeExifMetadata(jpegImageFile, os);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void dump()
{
PrintWriter pw = new PrintWriter(System.out);
dump(pw);
pw.flush();
}
|
#vulnerable code
public void dump()
{
dump(new PrintWriter(new OutputStreamWriter(System.out)));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void writeImage(BufferedImage src, OutputStream os, Map params)
throws ImageWriteException, IOException
{
// make copy of params; we'll clear keys as we consume them.
params = (params == null) ? new HashMap() : new HashMap(params);
PixelDensity pixelDensity = null;
// clear format key.
if (params.containsKey(PARAM_KEY_FORMAT))
params.remove(PARAM_KEY_FORMAT);
if (params.containsKey(PARAM_KEY_PIXEL_DENSITY))
pixelDensity = (PixelDensity) params.remove(PARAM_KEY_PIXEL_DENSITY);
if (params.size() > 0)
{
Object firstKey = params.keySet().iterator().next();
throw new ImageWriteException("Unknown parameter: " + firstKey);
}
final SimplePalette palette = new PaletteFactory().makePaletteSimple(
src, 256);
BmpWriter writer = null;
if (palette == null)
writer = new BmpWriterRgb();
else
writer = new BmpWriterPalette(palette);
byte imagedata[] = writer.getImageData(src);
BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL);
{
// write BitmapFileHeader
os.write(0x42); // B, Windows 3.1x, 95, NT, Bitmap
os.write(0x4d); // M
int filesize = BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE + // header
// size
4 * writer.getPaletteSize() + // palette size in bytes
imagedata.length;
bos.write4Bytes(filesize);
bos.write4Bytes(0); // reserved
bos.write4Bytes(BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE
+ 4 * writer.getPaletteSize()); // Bitmap Data Offset
}
int width = src.getWidth();
int height = src.getHeight();
{ // write BitmapInfoHeader
bos.write4Bytes(BITMAP_INFO_HEADER_SIZE); // Bitmap Info Header Size
bos.write4Bytes(width); // width
bos.write4Bytes(height); // height
bos.write2Bytes(1); // Number of Planes
bos.write2Bytes(writer.getBitsPerPixel()); // Bits Per Pixel
bos.write4Bytes(BI_RGB); // Compression
bos.write4Bytes(imagedata.length); // Bitmap Data Size
bos.write4Bytes(pixelDensity != null ? (int)Math.round(pixelDensity.horizontalDensityMetres()) : 0); // HResolution
bos.write4Bytes(pixelDensity != null ? (int)Math.round(pixelDensity.verticalDensityMetres()) : 0); // VResolution
if (palette == null)
bos.write4Bytes(0); // Colors
else
bos.write4Bytes(palette.length()); // Colors
bos.write4Bytes(0); // Important Colors
// bos.write_4_bytes(0); // Compression
}
{ // write Palette
writer.writePalette(bos);
}
{ // write Image Data
bos.writeByteArray(imagedata);
}
}
|
#vulnerable code
public void writeImage(BufferedImage src, OutputStream os, Map params)
throws ImageWriteException, IOException
{
// make copy of params; we'll clear keys as we consume them.
params = (params == null) ? new HashMap() : new HashMap(params);
Integer xResolution = Integer.valueOf(0);
Integer yResolution = Integer.valueOf(0);
// clear format key.
if (params.containsKey(PARAM_KEY_FORMAT))
params.remove(PARAM_KEY_FORMAT);
if (params.containsKey(PARAM_KEY_X_RESOLUTION))
xResolution = (Integer) params.remove(PARAM_KEY_X_RESOLUTION);
if (params.containsKey(PARAM_KEY_Y_RESOLUTION))
yResolution = (Integer) params.remove(PARAM_KEY_Y_RESOLUTION);
if (params.size() > 0)
{
Object firstKey = params.keySet().iterator().next();
throw new ImageWriteException("Unknown parameter: " + firstKey);
}
final SimplePalette palette = new PaletteFactory().makePaletteSimple(
src, 256);
BmpWriter writer = null;
if (palette == null)
writer = new BmpWriterRgb();
else
writer = new BmpWriterPalette(palette);
byte imagedata[] = writer.getImageData(src);
BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL);
{
// write BitmapFileHeader
os.write(0x42); // B, Windows 3.1x, 95, NT, Bitmap
os.write(0x4d); // M
int filesize = BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE + // header
// size
4 * writer.getPaletteSize() + // palette size in bytes
imagedata.length;
bos.write4Bytes(filesize);
bos.write4Bytes(0); // reserved
bos.write4Bytes(BITMAP_FILE_HEADER_SIZE + BITMAP_INFO_HEADER_SIZE
+ 4 * writer.getPaletteSize()); // Bitmap Data Offset
}
int width = src.getWidth();
int height = src.getHeight();
{ // write BitmapInfoHeader
bos.write4Bytes(BITMAP_INFO_HEADER_SIZE); // Bitmap Info Header Size
bos.write4Bytes(width); // width
bos.write4Bytes(height); // height
bos.write2Bytes(1); // Number of Planes
bos.write2Bytes(writer.getBitsPerPixel()); // Bits Per Pixel
bos.write4Bytes(BI_RGB); // Compression
bos.write4Bytes(imagedata.length); // Bitmap Data Size
bos.write4Bytes(xResolution.intValue()); // HResolution
bos.write4Bytes(yResolution.intValue()); // VResolution
if (palette == null)
bos.write4Bytes(0); // Colors
else
bos.write4Bytes(palette.length()); // Colors
bos.write4Bytes(0); // Important Colors
// bos.write_4_bytes(0); // Compression
}
{ // write Palette
writer.writePalette(bos);
}
{ // write Image Data
bos.writeByteArray(imagedata);
}
}
#location 78
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = null;
try {
bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
} finally {
if (bis != null) {
bis.close();
}
}
}
|
#vulnerable code
protected List<IptcBlock> parseAllBlocks(byte bytes[], boolean verbose,
boolean strict) throws ImageReadException, IOException {
List<IptcBlock> blocks = new ArrayList<IptcBlock>();
BinaryInputStream bis = new BinaryInputStream(bytes, APP13_BYTE_ORDER);
// Note that these are unsigned quantities. Name is always an even
// number of bytes (including the 1st byte, which is the size.)
byte[] idString = bis.readByteArray(
PHOTOSHOP_IDENTIFICATION_STRING.size(),
"App13 Segment missing identification string");
if (!PHOTOSHOP_IDENTIFICATION_STRING.equals(idString))
throw new ImageReadException("Not a Photoshop App13 Segment");
// int index = PHOTOSHOP_IDENTIFICATION_STRING.length;
while (true) {
byte[] imageResourceBlockSignature = bis
.readByteArray(CONST_8BIM.size(),
"App13 Segment missing identification string",
false, false);
if (null == imageResourceBlockSignature)
break;
if (!CONST_8BIM.equals(imageResourceBlockSignature))
throw new ImageReadException(
"Invalid Image Resource Block Signature");
int blockType = bis
.read2ByteInteger("Image Resource Block missing type");
if (verbose)
Debug.debug("blockType",
blockType + " (0x" + Integer.toHexString(blockType)
+ ")");
int blockNameLength = bis
.read1ByteInteger("Image Resource Block missing name length");
if (verbose && blockNameLength > 0)
Debug.debug("blockNameLength", blockNameLength + " (0x"
+ Integer.toHexString(blockNameLength) + ")");
byte[] blockNameBytes;
if (blockNameLength == 0) {
bis.read1ByteInteger("Image Resource Block has invalid name");
blockNameBytes = new byte[0];
} else {
blockNameBytes = bis.readByteArray(blockNameLength,
"Invalid Image Resource Block name", verbose, strict);
if (null == blockNameBytes)
break;
if (blockNameLength % 2 == 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
int blockSize = bis
.read4ByteInteger("Image Resource Block missing size");
if (verbose)
Debug.debug("blockSize",
blockSize + " (0x" + Integer.toHexString(blockSize)
+ ")");
/*
* doesn't catch cases where blocksize is invalid but is still less
* than bytes.length but will at least prevent OutOfMemory errors
*/
if (blockSize > bytes.length) {
throw new ImageReadException("Invalid Block Size : "
+ blockSize + " > " + bytes.length);
}
byte[] blockData = bis.readByteArray(blockSize,
"Invalid Image Resource Block data", verbose, strict);
if (null == blockData)
break;
blocks.add(new IptcBlock(blockType, blockNameBytes, blockData));
if ((blockSize % 2) != 0)
bis.read1ByteInteger("Image Resource Block missing padding byte");
}
return blocks;
}
#location 23
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void changeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos);) {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add a field/tag to the output set.
//
// Note that you should first remove the field/tag if it already
// exists in this directory, or you may end up with duplicate
// tags. See above.
//
// Certain fields/tags are expected in certain Exif directories;
// Others can occur in more than one directory (and often have a
// different meaning in different directories).
//
// TagInfo constants often contain a description of what
// directories are associated with a given tag.
//
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateExifDirectory();
// make sure to remove old value if present (this method will
// not fail if the tag does not exist).
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_APERTURE_VALUE,
new RationalNumber(3, 10));
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
// printTagValue(jpegMetadata, TiffConstants.TIFF_TAG_DATE_TIME);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
}
}
|
#vulnerable code
public void changeExifMetadata(final File jpegImageFile, final File dst)
throws IOException, ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add a field/tag to the output set.
//
// Note that you should first remove the field/tag if it already
// exists in this directory, or you may end up with duplicate
// tags. See above.
//
// Certain fields/tags are expected in certain Exif directories;
// Others can occur in more than one directory (and often have a
// different meaning in different directories).
//
// TagInfo constants often contain a description of what
// directories are associated with a given tag.
//
final TiffOutputDirectory exifDirectory = outputSet
.getOrCreateExifDirectory();
// make sure to remove old value if present (this method will
// not fail if the tag does not exist).
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
exifDirectory.add(ExifTagConstants.EXIF_TAG_APERTURE_VALUE,
new RationalNumber(3, 10));
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
// printTagValue(jpegMetadata, TiffConstants.TIFF_TAG_DATE_TIME);
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 80
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void test() throws Exception {
String imagesFolderPath = FilenameUtils
.separatorsToSystem("src\\test\\data\\images\\png\\3");
File imagesFolder = new File(imagesFolderPath);
assertTrue(imagesFolder.exists() && imagesFolder.isDirectory());
File files[] = imagesFolder.listFiles();
for (File file : files) {
File imageFile = file;
if (!imageFile.isFile())
continue;
if (!imageFile.getName().toLowerCase().endsWith(".png"))
continue;
Debug.debug();
Debug.debug("imageFile", imageFile);
File lastFile = imageFile;
for (int j = 0; j < 10; j++) {
Map<String,Object> readParams = new HashMap<String,Object>();
// readParams.put(SanselanConstants.BUFFERED_IMAGE_FACTORY,
// new RgbBufferedImageFactory());
BufferedImage image = Imaging.getBufferedImage(lastFile,
readParams);
assertNotNull(image);
File tempFile = createTempFile(imageFile.getName() + "." + j
+ ".", ".png");
Debug.debug("tempFile", tempFile);
Map<String,Object> writeParams = new HashMap<String,Object>();
Imaging.writeImage(image, tempFile,
ImageFormat.IMAGE_FORMAT_PNG, writeParams);
lastFile = tempFile;
}
}
}
|
#vulnerable code
public void test() throws Exception {
String imagesFolderPath = FilenameUtils
.separatorsToSystem("src\\test\\data\\images\\png\\3");
File imagesFolder = new File(imagesFolderPath);
assertTrue(imagesFolder.exists() && imagesFolder.isDirectory());
File files[] = imagesFolder.listFiles();
for (int i = 0; i < files.length; i++) {
File imageFile = files[i];
if (!imageFile.isFile())
continue;
if (!imageFile.getName().toLowerCase().endsWith(".png"))
continue;
Debug.debug();
Debug.debug("imageFile", imageFile);
File lastFile = imageFile;
for (int j = 0; j < 10; j++) {
Map<String,Object> readParams = new HashMap<String,Object>();
// readParams.put(SanselanConstants.BUFFERED_IMAGE_FACTORY,
// new RgbBufferedImageFactory());
BufferedImage image = Imaging.getBufferedImage(lastFile,
readParams);
assertNotNull(image);
File tempFile = createTempFile(imageFile.getName() + "." + j
+ ".", ".png");
Debug.debug("tempFile", tempFile);
Map<String,Object> writeParams = new HashMap<String,Object>();
Imaging.writeImage(image, tempFile,
ImageFormat.IMAGE_FORMAT_PNG, writeParams);
lastFile = tempFile;
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testAll5x2Images() {
int[] combinations = new int[10];
BufferedImage image = new BufferedImage(5, 2, BufferedImage.TYPE_INT_RGB);
do {
for (int x = 0; x < 5; x++) {
if (combinations[x] == 0) {
image.setRGB(x, 0, 0xFFFFFF);
} else {
image.setRGB(x, 0, 0);
}
}
for (int x = 0; x < 5; x++) {
if (combinations[5 + x] == 0) {
image.setRGB(x, 1, 0xFFFFFF);
} else {
image.setRGB(x, 1, 0);
}
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_1D);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 0);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 1);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 5);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
} while (nextCombination(combinations, 1));
}
|
#vulnerable code
public void testAll5x2Images() {
int[] combinations = new int[10];
BufferedImage image = new BufferedImage(5, 2, BufferedImage.TYPE_INT_RGB);
do {
for (int x = 0; x < 5; x++) {
if (combinations[x] == 0) {
image.setRGB(x, 0, 0xFFFFFF);
} else {
image.setRGB(x, 0, 0);
}
}
for (int x = 0; x < 5; x++) {
if (combinations[5 + x] == 0) {
image.setRGB(x, 1, 0xFFFFFF);
} else {
image.setRGB(x, 1, 0);
}
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_1D);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 0);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
FileOutputStream fos = new FileOutputStream("/tmp/test.tiff");
fos.write(compressed);
fos.close();
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 1);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_3);
params.put(TiffConstants.PARAM_KEY_T4_OPTIONS, 5);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
try {
HashMap params = new HashMap();
params.put(SanselanConstants.PARAM_KEY_COMPRESSION, TiffConstants.TIFF_COMPRESSION_CCITT_GROUP_4);
byte[] compressed = Sanselan.writeImageToBytes(image, ImageFormat.IMAGE_FORMAT_TIFF, params);
BufferedImage result = Sanselan.getBufferedImage(compressed);
compareImages(image, result);
} catch (ImageWriteException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (ImageReadException ex) {
Debug.debug(ex);
assertFalse(true);
} catch (IOException ex) {
Debug.debug(ex);
assertFalse(true);
}
} while (nextCombination(combinations, 1));
}
#location 26
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAddIptcData() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
if (metadata == null) {
// FIXME select only files with meta for this test
return;
}
final List<IptcBlock> newBlocks = new ArrayList<IptcBlock>();
newBlocks.addAll(metadata.photoshopApp13Data.getNonIptcBlocks());
final List<IptcRecord> oldRecords = metadata.photoshopApp13Data.getRecords();
List<IptcRecord> newRecords = new ArrayList<IptcRecord>();
for (final IptcRecord record : oldRecords) {
if (record.iptcType != IptcTypes.CITY
&& record.iptcType != IptcTypes.CREDIT) {
newRecords.add(record);
}
}
newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
newRecords.add(new IptcRecord(IptcTypes.CREDIT, "William Sorensen"));
final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords, newBlocks);
final File updated = createTempFile(imageFile.getName() + ".iptc.add.", ".jpg");
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(updated);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
final ByteSource updateByteSource = new ByteSourceFile(updated);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(updateByteSource, params);
assertNotNull(outMetadata);
assertTrue(outMetadata.getItems().size() == newRecords.size());
}
|
#vulnerable code
@Test
public void testAddIptcData() throws Exception {
final ByteSource byteSource = new ByteSourceFile(imageFile);
final Map<String, Object> params = new HashMap<String, Object>();
final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
params.put(PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));
final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
{
final List<IptcBlock> newBlocks = new ArrayList<IptcBlock>();
List<IptcRecord> newRecords = new ArrayList<IptcRecord>();
if (null != metadata) {
final boolean keepOldIptcNonTextValues = true;
if (keepOldIptcNonTextValues) {
newBlocks.addAll(metadata.photoshopApp13Data
.getNonIptcBlocks());
}
final boolean keepOldIptcTextValues = true;
if (keepOldIptcTextValues) {
final List<IptcRecord> oldRecords = metadata.photoshopApp13Data
.getRecords();
newRecords = new ArrayList<IptcRecord>();
for (int j = 0; j < oldRecords.size(); j++) {
final IptcRecord record = oldRecords.get(j);
if (record.iptcType != IptcTypes.CITY
&& record.iptcType != IptcTypes.CREDIT) {
newRecords.add(record);
}
}
}
}
newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
newRecords.add(new IptcRecord(IptcTypes.CREDIT,
"William Sorensen"));
final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords,
newBlocks);
final File updated = createTempFile(imageFile.getName()
+ ".iptc.add.", ".jpg");
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(updated);
os = new BufferedOutputStream(os);
new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
// Debug.debug("Destination Segments:");
// new JpegUtils().dumpJFIF(new ByteSourceFile(updated));
final ByteSource updateByteSource = new ByteSourceFile(updated);
final JpegPhotoshopMetadata outMetadata = new JpegImageParser()
.getPhotoshopMetadata(updateByteSource, params);
// Debug.debug("outMetadata", outMetadata.toString());
// Debug.debug("hasIptcSegment", new JpegImageParser()
// .hasIptcSegment(updateByteSource));
assertNotNull(outMetadata);
assertTrue(outMetadata.getItems().size() == newRecords.size());
// assertEquals(metadata.toString(), outMetadata.toString());
}
}
#location 54
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void removeExifTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos)) {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
if (null == outputSet) {
// file does not contain any exif metadata. We don't need to
// update the file; just copy it.
FileUtils.copyFile(jpegImageFile, dst);
return;
}
{
// Example of how to remove a single tag/field.
// There are two ways to do this.
// Option 1: brute force
// Note that this approach is crude: Exif data is organized in
// directories. The same tag/field may appear in more than one
// directory, and have different meanings in each.
outputSet.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
// Option 2: precision
// We know the exact directory the tag should appear in, in this
// case the "exif" directory.
// One complicating factor is that in some cases, manufacturers
// will place the same tag in different directories.
// To learn which directory a tag appears in, either refer to
// the constants in ExifTagConstants.java or go to Phil Harvey's
// EXIF website.
final TiffOutputDirectory exifDirectory = outputSet
.getExifDirectory();
if (null != exifDirectory) {
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
}
}
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
}
}
|
#vulnerable code
public void removeExifTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
if (null == outputSet) {
// file does not contain any exif metadata. We don't need to
// update the file; just copy it.
FileUtils.copyFile(jpegImageFile, dst);
return;
}
{
// Example of how to remove a single tag/field.
// There are two ways to do this.
// Option 1: brute force
// Note that this approach is crude: Exif data is organized in
// directories. The same tag/field may appear in more than one
// directory, and have different meanings in each.
outputSet.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
// Option 2: precision
// We know the exact directory the tag should appear in, in this
// case the "exif" directory.
// One complicating factor is that in some cases, manufacturers
// will place the same tag in different directories.
// To learn which directory a tag appears in, either refer to
// the constants in ExifTagConstants.java or go to Phil Harvey's
// EXIF website.
final TiffOutputDirectory exifDirectory = outputSet
.getExifDirectory();
if (null != exifDirectory) {
exifDirectory
.removeField(ExifTagConstants.EXIF_TAG_APERTURE_VALUE);
}
}
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 68
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void performTest(final String name) {
final File target = new File(name);
final Formatter fmt = new Formatter(System.out);
double sumTime = 0;
int n = 1;
for (int i = 0; i < 10; i++) {
try {
ByteSourceFile byteSource = new ByteSourceFile(target);
// This test code allows you to test cases where the
// input is processed using Apache Imaging's
// ByteSourceInputStream rather than the ByteSourceFile.
// You might also want to experiment with ByteSourceArray.
// FileInputStream fins = new FileInputStream(target);
// BufferedInputStream bins = new BufferedInputStream(fins);
// ByteSourceInputStream byteSource =
// new ByteSourceInputStream(bins, target.getName());
// ready the parser (you may modify this code block
// to use your parser of choice)
HashMap<String,Object> params = new HashMap<String,Object>();
TiffImageParser tiffImageParser = new TiffImageParser();
// load the file and record time needed to do so
final long time0 = System.nanoTime();
BufferedImage bImage = tiffImageParser.getBufferedImage(
byteSource, params);
final long time1 = System.nanoTime();
// tabulate results
final double testTime = (time1 - time0) / 1000000.0;
if (i > 1) {
n = i - 1;
sumTime += testTime;
}
final double avgTime = sumTime / n;
// tabulate the memory results. Note that the
// buffered image, the byte source, and the parser
// are all still in scope. This approach is taken
// to get some sense of peak memory use, but Java
// may have already started collecting garbage,
// so there are limits to the reliability of these
// statistics
final Runtime r = Runtime.getRuntime();
final long freeMemory = r.freeMemory();
final long totalMemory = r.totalMemory();
final long usedMemory = totalMemory - freeMemory;
if (i == 0) {
// print header info
fmt.format("\n");
fmt.format("Processing file: %s\n", target.getName());
fmt.format(" image size: %d by %d\n\n", bImage.getWidth(),
bImage.getHeight());
fmt.format(" time to load image -- memory\n");
fmt.format(" time ms avg ms -- used mb total mb\n");
}
fmt.format("%9.3f %9.3f -- %9.3f %9.3f \n", testTime,
avgTime, usedMemory / (1024.0 * 1024.0), totalMemory
/ (1024.0 * 1024.0));
bImage = null;
byteSource = null;
params = null;
tiffImageParser = null;
} catch (final ImageReadException ire) {
ire.printStackTrace();
System.exit(-1);
} catch (final IOException ioex) {
ioex.printStackTrace();
System.exit(-1);
} finally {
fmt.close();
}
try {
// sleep between loop iterations allows time
// for the JVM to clean up memory. The Netbeans IDE
// doesn't "get" the fact that we're doing this operation
// deliberately and is apt offer hints
// suggesting that the code should be modified
Runtime.getRuntime().gc();
Thread.sleep(1000);
} catch (final InterruptedException iex) {
// this isn't fatal, but shouldn't happen
iex.printStackTrace();
}
}
}
|
#vulnerable code
private void performTest(final String name) {
final File target = new File(name);
final Formatter fmt = new Formatter(System.out);
double sumTime = 0;
int n = 1;
for (int i = 0; i < 10; i++) {
try {
ByteSourceFile byteSource = new ByteSourceFile(target);
// This test code allows you to test cases where the
// input is processed using Apache Imaging's
// ByteSourceInputStream rather than the ByteSourceFile.
// You might also want to experiment with ByteSourceArray.
// FileInputStream fins = new FileInputStream(target);
// BufferedInputStream bins = new BufferedInputStream(fins);
// ByteSourceInputStream byteSource =
// new ByteSourceInputStream(bins, target.getName());
// ready the parser (you may modify this code block
// to use your parser of choice)
HashMap<String,Object> params = new HashMap<String,Object>();
TiffImageParser tiffImageParser = new TiffImageParser();
// load the file and record time needed to do so
final long time0 = System.nanoTime();
BufferedImage bImage = tiffImageParser.getBufferedImage(
byteSource, params);
final long time1 = System.nanoTime();
// tabulate results
final double testTime = (time1 - time0) / 1000000.0;
if (i > 1) {
n = i - 1;
sumTime += testTime;
}
final double avgTime = sumTime / n;
// tabulate the memory results. Note that the
// buffered image, the byte source, and the parser
// are all still in scope. This approach is taken
// to get some sense of peak memory use, but Java
// may have already started collecting garbage,
// so there are limits to the reliability of these
// statistics
final Runtime r = Runtime.getRuntime();
final long freeMemory = r.freeMemory();
final long totalMemory = r.totalMemory();
final long usedMemory = totalMemory - freeMemory;
if (i == 0) {
// print header info
fmt.format("\n");
fmt.format("Processing file: %s\n", target.getName());
fmt.format(" image size: %d by %d\n\n", bImage.getWidth(),
bImage.getHeight());
fmt.format(" time to load image -- memory\n");
fmt.format(" time ms avg ms -- used mb total mb\n");
}
fmt.format("%9.3f %9.3f -- %9.3f %9.3f \n", testTime,
avgTime, usedMemory / (1024.0 * 1024.0), totalMemory
/ (1024.0 * 1024.0));
bImage = null;
byteSource = null;
params = null;
tiffImageParser = null;
} catch (final ImageReadException ire) {
ire.printStackTrace();
System.exit(-1);
} catch (final IOException ioex) {
ioex.printStackTrace();
System.exit(-1);
}
try {
// sleep between loop iterations allows time
// for the JVM to clean up memory. The Netbeans IDE
// doesn't "get" the fact that we're doing this operation
// deliberately and is apt offer hints
// suggesting that the code should be modified
Runtime.getRuntime().gc();
Thread.sleep(1000);
} catch (final InterruptedException iex) {
// this isn't fatal, but shouldn't happen
iex.printStackTrace();
}
}
}
#location 35
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected File createTempFile(final byte src[]) throws IOException {
final File file = createTempFile("raw_", ".bin");
// write test bytes to file.
try (FileOutputStream fos = new FileOutputStream(file);
OutputStream os = new BufferedOutputStream(fos)) {
os.write(src);
}
// test that all bytes written to file.
assertTrue(src.length == file.length());
return file;
}
|
#vulnerable code
protected File createTempFile(final byte src[]) throws IOException {
final File file = createTempFile("raw_", ".bin");
// write test bytes to file.
OutputStream os = null;
boolean canThrow = false;
try {
os = new FileOutputStream(file);
os = new BufferedOutputStream(os);
os.write(src);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
// test that all bytes written to file.
assertTrue(src.length == file.length());
return file;
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void setData(final byte[] bytes) throws IOException {
data = bytes;
InputStream bis = null;
boolean canThrow = false;
try {
bis = new ByteArrayInputStream(bytes);
dataTypeSignature = BinaryFunctions.read4Bytes("data type signature", bis,
"ICC: corrupt tag data", ByteOrder.BIG_ENDIAN);
itdt = getIccTagDataType(dataTypeSignature);
// if (itdt != null)
// {
// System.out.println("\t\t\t" + "itdt: " + itdt.name);
// }
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, bis);
}
}
|
#vulnerable code
public void setData(final byte[] bytes) throws IOException {
data = bytes;
BinaryInputStream bis = null;
boolean canThrow = false;
try {
bis = new BinaryInputStream(new ByteArrayInputStream(
bytes), ByteOrder.BIG_ENDIAN);
dataTypeSignature = bis.read4Bytes("data type signature",
"ICC: corrupt tag data");
itdt = getIccTagDataType(dataTypeSignature);
// if (itdt != null)
// {
// System.out.println("\t\t\t" + "itdt: " + itdt.name);
// }
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, bis);
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void writeImage(BufferedImage src, OutputStream os, Map params)
throws ImageWriteException, IOException {
// make copy of params; we'll clear keys as we consume them.
params = (params == null) ? new HashMap() : new HashMap(params);
// clear format key.
if (params.containsKey(PARAM_KEY_FORMAT))
params.remove(PARAM_KEY_FORMAT);
PixelDensity pixelDensity = (PixelDensity) params.remove(PARAM_KEY_PIXEL_DENSITY);
if (params.size() > 0) {
Object firstKey = params.keySet().iterator().next();
throw new ImageWriteException("Unknown parameter: " + firstKey);
}
final PaletteFactory paletteFactory = new PaletteFactory();
final SimplePalette palette = paletteFactory
.makePaletteSimple(src, 256);
final int bitCount;
final boolean hasTransparency = paletteFactory.hasTransparency(src);
if (palette == null) {
if (hasTransparency)
bitCount = 32;
else
bitCount = 24;
} else if (palette.length() <= 2)
bitCount = 1;
else if (palette.length() <= 16)
bitCount = 4;
else
bitCount = 8;
BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL);
int scanline_size = (bitCount * src.getWidth() + 7) / 8;
if ((scanline_size % 4) != 0)
scanline_size += 4 - (scanline_size % 4); // pad scanline to 4 byte
// size.
int t_scanline_size = (src.getWidth() + 7) / 8;
if ((t_scanline_size % 4) != 0)
t_scanline_size += 4 - (t_scanline_size % 4); // pad scanline to 4
// byte size.
int imageSize = 40 + 4 * (bitCount <= 8 ? (1 << bitCount) : 0)
+ src.getHeight() * scanline_size + src.getHeight()
* t_scanline_size;
// ICONDIR
bos.write2Bytes(0); // reserved
bos.write2Bytes(1); // 1=ICO, 2=CUR
bos.write2Bytes(1); // count
// ICONDIRENTRY
int iconDirEntryWidth = src.getWidth();
int iconDirEntryHeight = src.getHeight();
if (iconDirEntryWidth > 255 || iconDirEntryHeight > 255) {
iconDirEntryWidth = 0;
iconDirEntryHeight = 0;
}
bos.write(iconDirEntryWidth);
bos.write(iconDirEntryHeight);
bos.write((bitCount >= 8) ? 0 : (1 << bitCount));
bos.write(0); // reserved
bos.write2Bytes(1); // color planes
bos.write2Bytes(bitCount);
bos.write4Bytes(imageSize);
bos.write4Bytes(22); // image offset
// BITMAPINFOHEADER
bos.write4Bytes(40); // size
bos.write4Bytes(src.getWidth());
bos.write4Bytes(2 * src.getHeight());
bos.write2Bytes(1); // planes
bos.write2Bytes(bitCount);
bos.write4Bytes(0); // compression
bos.write4Bytes(0); // image size
bos.write4Bytes(pixelDensity == null ? 0 : (int)Math.round(pixelDensity.horizontalDensityMetres())); // x pixels per meter
bos.write4Bytes(pixelDensity == null ? 0 : (int)Math.round(pixelDensity.horizontalDensityMetres())); // y pixels per meter
bos.write4Bytes(0); // colors used, 0 = (1 << bitCount) (ignored)
bos.write4Bytes(0); // colors important
if (palette != null) {
for (int i = 0; i < (1 << bitCount); i++) {
if (i < palette.length()) {
int argb = palette.getEntry(i);
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0);
} else {
bos.write(0);
bos.write(0);
bos.write(0);
bos.write(0);
}
}
}
int bit_cache = 0;
int bits_in_cache = 0;
int row_padding = scanline_size - (bitCount * src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
if (bitCount < 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bit_cache <<= bitCount;
bit_cache |= index;
bits_in_cache += bitCount;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
} else if (bitCount == 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bos.write(0xff & index);
} else if (bitCount == 24) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
} else if (bitCount == 32) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0xff & (argb >> 24));
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < row_padding; x++)
bos.write(0);
}
int t_row_padding = t_scanline_size - (src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
int alpha = 0xff & (argb >> 24);
bit_cache <<= 1;
if (alpha == 0)
bit_cache |= 1;
bits_in_cache++;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < t_row_padding; x++)
bos.write(0);
}
}
|
#vulnerable code
@Override
public void writeImage(BufferedImage src, OutputStream os, Map params)
throws ImageWriteException, IOException {
// make copy of params; we'll clear keys as we consume them.
params = (params == null) ? new HashMap() : new HashMap(params);
// clear format key.
if (params.containsKey(PARAM_KEY_FORMAT))
params.remove(PARAM_KEY_FORMAT);
if (params.size() > 0) {
Object firstKey = params.keySet().iterator().next();
throw new ImageWriteException("Unknown parameter: " + firstKey);
}
final PaletteFactory paletteFactory = new PaletteFactory();
final SimplePalette palette = paletteFactory
.makePaletteSimple(src, 256);
final int bitCount;
final boolean hasTransparency = paletteFactory.hasTransparency(src);
if (palette == null) {
if (hasTransparency)
bitCount = 32;
else
bitCount = 24;
} else if (palette.length() <= 2)
bitCount = 1;
else if (palette.length() <= 16)
bitCount = 4;
else
bitCount = 8;
BinaryOutputStream bos = new BinaryOutputStream(os, BYTE_ORDER_INTEL);
int scanline_size = (bitCount * src.getWidth() + 7) / 8;
if ((scanline_size % 4) != 0)
scanline_size += 4 - (scanline_size % 4); // pad scanline to 4 byte
// size.
int t_scanline_size = (src.getWidth() + 7) / 8;
if ((t_scanline_size % 4) != 0)
t_scanline_size += 4 - (t_scanline_size % 4); // pad scanline to 4
// byte size.
int imageSize = 40 + 4 * (bitCount <= 8 ? (1 << bitCount) : 0)
+ src.getHeight() * scanline_size + src.getHeight()
* t_scanline_size;
// ICONDIR
bos.write2Bytes(0); // reserved
bos.write2Bytes(1); // 1=ICO, 2=CUR
bos.write2Bytes(1); // count
// ICONDIRENTRY
int iconDirEntryWidth = src.getWidth();
int iconDirEntryHeight = src.getHeight();
if (iconDirEntryWidth > 255 || iconDirEntryHeight > 255) {
iconDirEntryWidth = 0;
iconDirEntryHeight = 0;
}
bos.write(iconDirEntryWidth);
bos.write(iconDirEntryHeight);
bos.write((bitCount >= 8) ? 0 : (1 << bitCount));
bos.write(0); // reserved
bos.write2Bytes(1); // color planes
bos.write2Bytes(bitCount);
bos.write4Bytes(imageSize);
bos.write4Bytes(22); // image offset
// BITMAPINFOHEADER
bos.write4Bytes(40); // size
bos.write4Bytes(src.getWidth());
bos.write4Bytes(2 * src.getHeight());
bos.write2Bytes(1); // planes
bos.write2Bytes(bitCount);
bos.write4Bytes(0); // compression
bos.write4Bytes(0); // image size
bos.write4Bytes(0); // x pixels per meter
bos.write4Bytes(0); // y pixels per meter
bos.write4Bytes(0); // colors used, 0 = (1 << bitCount) (ignored)
bos.write4Bytes(0); // colors important
if (palette != null) {
for (int i = 0; i < (1 << bitCount); i++) {
if (i < palette.length()) {
int argb = palette.getEntry(i);
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0);
} else {
bos.write(0);
bos.write(0);
bos.write(0);
bos.write(0);
}
}
}
int bit_cache = 0;
int bits_in_cache = 0;
int row_padding = scanline_size - (bitCount * src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
if (bitCount < 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bit_cache <<= bitCount;
bit_cache |= index;
bits_in_cache += bitCount;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
} else if (bitCount == 8) {
int rgb = 0xffffff & argb;
int index = palette.getPaletteIndex(rgb);
bos.write(0xff & index);
} else if (bitCount == 24) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
} else if (bitCount == 32) {
bos.write(0xff & argb);
bos.write(0xff & (argb >> 8));
bos.write(0xff & (argb >> 16));
bos.write(0xff & (argb >> 24));
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < row_padding; x++)
bos.write(0);
}
int t_row_padding = t_scanline_size - (src.getWidth() + 7) / 8;
for (int y = src.getHeight() - 1; y >= 0; y--) {
for (int x = 0; x < src.getWidth(); x++) {
int argb = src.getRGB(x, y);
int alpha = 0xff & (argb >> 24);
bit_cache <<= 1;
if (alpha == 0)
bit_cache |= 1;
bits_in_cache++;
if (bits_in_cache >= 8) {
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
}
if (bits_in_cache > 0) {
bit_cache <<= (8 - bits_in_cache);
bos.write(0xff & bit_cache);
bit_cache = 0;
bits_in_cache = 0;
}
for (int x = 0; x < t_row_padding; x++)
bos.write(0);
}
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void setExifGPSTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
try (FileOutputStream fos = new FileOutputStream(dst);
OutputStream os = new BufferedOutputStream(fos)) {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
}
}
|
#vulnerable code
public void setExifGPSTag(final File jpegImageFile, final File dst) throws IOException,
ImageReadException, ImageWriteException {
OutputStream os = null;
boolean canThrow = false;
try {
TiffOutputSet outputSet = null;
// note that metadata might be null if no metadata is found.
final ImageMetadata metadata = Imaging.getMetadata(jpegImageFile);
final JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
if (null != jpegMetadata) {
// note that exif might be null if no Exif metadata is found.
final TiffImageMetadata exif = jpegMetadata.getExif();
if (null != exif) {
// TiffImageMetadata class is immutable (read-only).
// TiffOutputSet class represents the Exif data to write.
//
// Usually, we want to update existing Exif metadata by
// changing
// the values of a few fields, or adding a field.
// In these cases, it is easiest to use getOutputSet() to
// start with a "copy" of the fields read from the image.
outputSet = exif.getOutputSet();
}
}
// if file does not contain any exif metadata, we create an empty
// set of exif metadata. Otherwise, we keep all of the other
// existing tags.
if (null == outputSet) {
outputSet = new TiffOutputSet();
}
{
// Example of how to add/update GPS info to output set.
// New York City
final double longitude = -74.0; // 74 degrees W (in Degrees East)
final double latitude = 40 + 43 / 60.0; // 40 degrees N (in Degrees
// North)
outputSet.setGPSInDegrees(longitude, latitude);
}
os = new FileOutputStream(dst);
os = new BufferedOutputStream(os);
new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
outputSet);
canThrow = true;
} finally {
IoUtils.closeQuietly(canThrow, os);
}
}
#location 53
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static byte[] decompressT4_1D(final byte[] compressed, final int width,
final int height, final boolean hasFill) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed));
try (BitArrayOutputStream outputStream = new BitArrayOutputStream()) {
for (int y = 0; y < height; y++) {
int rowLength;
try {
T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream);
if (!isEOL(entry, hasFill)) {
throw new ImageReadException("Expected EOL not found");
}
int color = WHITE;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
} catch (final HuffmanTreeException huffmanException) {
throw new ImageReadException("Decompression error", huffmanException);
}
if (rowLength == width) {
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
return ret;
}
}
|
#vulnerable code
public static byte[] decompressT4_1D(final byte[] compressed, final int width,
final int height, final boolean hasFill) throws ImageReadException {
final BitInputStreamFlexible inputStream = new BitInputStreamFlexible(new ByteArrayInputStream(compressed));
BitArrayOutputStream outputStream = null;
boolean canThrow = false;
try {
outputStream = new BitArrayOutputStream();
for (int y = 0; y < height; y++) {
int rowLength;
try {
T4_T6_Tables.Entry entry = CONTROL_CODES.decode(inputStream);
if (!isEOL(entry, hasFill)) {
throw new ImageReadException("Expected EOL not found");
}
int color = WHITE;
for (rowLength = 0; rowLength < width;) {
final int runLength = readTotalRunLength(inputStream, color);
for (int i = 0; i < runLength; i++) {
outputStream.writeBit(color);
}
color = 1 - color;
rowLength += runLength;
}
} catch (final HuffmanTreeException huffmanException) {
throw new ImageReadException("Decompression error", huffmanException);
}
if (rowLength == width) {
outputStream.flush();
} else if (rowLength > width) {
throw new ImageReadException("Unrecoverable row length error in image row " + y);
}
}
final byte[] ret = outputStream.toByteArray();
canThrow = true;
return ret;
} finally {
try {
IoUtils.closeQuietly(canThrow, outputStream);
} catch (final IOException ioException) {
throw new ImageReadException("I/O error", ioException);
}
}
}
#location 39
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void performAction() {
AbstractFile targetFile = mainFrame.getActiveTable().getSelectedFile();
if (targetFile == null) {
targetFile = mainFrame.getActiveTable().getFileTableModel().getFileAt(0).getParent();
}
AbstractFile linkPath = mainFrame.getInactivePanel().getCurrentFolder();
new CreateSymLinkDialog(mainFrame, linkPath, targetFile).showDialog();
}
|
#vulnerable code
@Override
public void performAction() {
AbstractFile targetFile = mainFrame.getActiveTable().getSelectedFile();
if (targetFile == null) {
targetFile = mainFrame.getInactiveTable().getFileTableModel().getFileAt(0).getParent();
}
AbstractFile linkPath = mainFrame.getActivePanel().getCurrentFolder();
new CreateSymLinkDialog(mainFrame, linkPath, targetFile).showDialog();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldHandleExceptionDuringRequestCreation() throws URISyntaxException, IOException {
exception.expect(IOException.class);
exception.expectMessage("Could not create request");
final AsyncClientHttpRequestFactory factory = (uri, httpMethod) -> {
throw new IOException("Could not create request");
};
Rest.builder().requestFactory(factory).build()
.get("http://localhost/")
.dispatch(series(),
on(SUCCESSFUL).call(pass()));
}
|
#vulnerable code
@Test
public void shouldHandleExceptionDuringRequestCreation() throws URISyntaxException, IOException {
exception.expect(IOException.class);
exception.expectMessage("Could not create request");
final AsyncClientHttpRequestFactory factory = (uri, httpMethod) -> {
throw new IOException("Could not create request");
};
Rest.create(factory, emptyList())
.get("http://localhost/")
.dispatch(series(),
on(SUCCESSFUL).call(pass()));
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCreateDeletePostGISDatastore() {
if (!enabled()) {
return;
}
deleteAll();
String wsName = DEFAULT_WS;
String datastoreName = "resttestpostgis";
String description = "description";
String dsNamespace = "http://www.geo-solutions.it";
boolean exposePrimaryKeys = true;
boolean validateConnections = false;
String primaryKeyMetadataTable = "test";
GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();
datastoreEncoder.defaultInit();
datastoreEncoder.addName(datastoreName);
datastoreEncoder.addDescription(description);
datastoreEncoder.addNamespace(dsNamespace);
datastoreEncoder.addHost(pgHost);
datastoreEncoder.addPort(pgPort);
datastoreEncoder.addDatabase(pgDatabase);
datastoreEncoder.addSchema(pgSchema);
datastoreEncoder.addUser(pgUser);
datastoreEncoder.addPassword(pgPassword);
datastoreEncoder.addExposePrimaryKeys(exposePrimaryKeys);
datastoreEncoder.addValidateConnections(validateConnections);
datastoreEncoder.addPrimaryKeyMetadataTable(primaryKeyMetadataTable);
assertTrue(publisher.createWorkspace(wsName));
// creation test
boolean created = publisher.createPostGISDatastore(wsName, datastoreEncoder);
if( ! pgIgnore )
assertTrue("PostGIS datastore not created", created);
else if( ! created)
LOGGER.error("*** Datastore " + datastoreName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(wsName, datastoreName);
LOGGER.info("The type of the created datastore is: " + datastore.getType());
// removing test
boolean removed = publisher.removeDatastore(wsName, datastoreName);
if( ! pgIgnore )
assertTrue("PostGIS datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + datastoreName + " has not been removed.");
assertTrue(publisher.removeWorkspace(wsName));
}
|
#vulnerable code
public void testCreateDeletePostGISDatastore() {
if (!enabled()) {
return;
}
String wsName = "it.geosolutions";
String datastoreName = "resttestpostgis";
String description = "description";
String dsNamespace = "http://www.geo-solutions.it";
boolean exposePrimaryKeys = true;
boolean validateConnections = false;
String primaryKeyMetadataTable = "test";
GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();
datastoreEncoder.defaultInit();
datastoreEncoder.addName(datastoreName);
datastoreEncoder.addDescription(description);
datastoreEncoder.addNamespace(dsNamespace);
datastoreEncoder.addHost(pgHost);
datastoreEncoder.addPort(pgPort);
datastoreEncoder.addDatabase(pgDatabase);
datastoreEncoder.addSchema(pgSchema);
datastoreEncoder.addUser(pgUser);
datastoreEncoder.addPassword(pgPassword);
datastoreEncoder.addExposePrimaryKeys(exposePrimaryKeys);
datastoreEncoder.addValidateConnections(validateConnections);
datastoreEncoder.addPrimaryKeyMetadataTable(primaryKeyMetadataTable);
// creation test
boolean created = publisher.createPostGISDatastore(wsName, datastoreEncoder);
if( ! pgIgnore )
assertTrue("PostGIS datastore not created", created);
else if( ! created)
LOGGER.error("*** Datastore " + datastoreName + " has not been created.");
RESTDataStore datastore = reader.getDatastore(wsName, datastoreName);
LOGGER.info("The type of the created datastore is: " + datastore.getType());
// removing test
boolean removed = publisher.removeDatastore(wsName, datastoreName);
if( ! pgIgnore )
assertTrue("PostGIS datastore not removed", removed);
else if( ! removed )
LOGGER.error("*** Datastore " + datastoreName + " has not been removed.");
}
#location 39
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void deleteAllLayerGroups() {
List<String> groups = reader.getLayerGroups().getNames();
LOGGER.info("Found " + groups.size() + " layerGroups");
for (String groupName : groups) {
RESTLayerGroup group = reader.getLayerGroup(groupName);
if (groups != null) {
StringBuilder sb = new StringBuilder("Group: ").append(groupName).append(":");
for (NameLinkElem layer : group.getPublishedList()) {
sb.append(" ").append(layer);
}
boolean removed = publisher.removeLayerGroup(groupName);
LOGGER.info(sb.toString() + ": removed: " + removed);
assertTrue("LayerGroup not removed: " + groupName, removed);
}
}
}
|
#vulnerable code
private void deleteAllLayerGroups() {
List<String> groups = reader.getLayerGroups().getNames();
LOGGER.info("Found " + groups.size() + " layerGroups");
for (String groupName : groups) {
RESTLayerGroup group = reader.getLayerGroup(groupName);
if (groups != null) {
StringBuilder sb = new StringBuilder("Group: ").append(groupName).append(":");
for (NameLinkElem layer : group.getLayerList()) {
sb.append(" ").append(layer);
}
boolean removed = publisher.removeLayerGroup(groupName);
LOGGER.info(sb.toString() + ": removed: " + removed);
assertTrue("LayerGroup not removed: " + groupName, removed);
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private GSImageMosaicEncoder copyParameters(String wsName, String coverageStoreName,
String csname) throws NumberFormatException {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
if (coverage==null)
return null;
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
return coverageEncoder;
}
|
#vulnerable code
private GSImageMosaicEncoder copyParameters(String wsName, String coverageStoreName,
String csname) throws NumberFormatException {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
return coverageEncoder;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void deleteStylesForWorkspace(String workspace) {
RESTStyleList styles = styleManager.getStyles(workspace);
if (styles==null)
return;
for (NameLinkElem nameLinkElem : styles) {
removeStyleInWorkspace(workspace, nameLinkElem.getName(), true);
}
}
|
#vulnerable code
private void deleteStylesForWorkspace(String workspace) {
RESTStyleList styles = styleManager.getStyles(workspace);
for (NameLinkElem nameLinkElem : styles) {
removeStyleInWorkspace(workspace, nameLinkElem.getName(), true);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Before
public void setup() throws Exception {
if (enabled()){
init();
}
}
|
#vulnerable code
@Before
public void setup() throws Exception {
String ws = "topp";
String storeName = "testshpcollection";
// Delete all resources except styles
deleteAllWorkspacesRecursively();
// Create workspace
assertTrue(publisher.createWorkspace(ws));
// Publish shp collection
URI location = new ClassPathResource("testdata/multipleshp.zip").getFile().toURI();
assertTrue(publisher.publishShpCollection(ws, storeName, location));
String storeType = reader.getDatastore(ws, storeName).getStoreType();
assertEquals(storeType, "Shapefile");
// Test published layer names
List<String> layers = reader.getLayers().getNames();
assertTrue(layers.contains("cities"));
assertTrue(layers.contains("boundaries"));
// Publish style
publisher.publishStyle(new ClassPathResource("testdata/default_line.sld").getFile(), "default_line");
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void fixDimensions(String wsName, String coverageStoreName, String csname) {
final GSImageMosaicEncoder coverageEncoder = copyParameters(wsName, coverageStoreName,
csname);
// activate time dimension
final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true);
time.setUnit("Seconds");
time.setUnitSymbol("s");
time.setPresentation(Presentation.CONTINUOUS_INTERVAL);
coverageEncoder.setMetadataDimension("time", time);
// activate run which is a custom dimension
final GSDimensionInfoEncoder run=new GSDimensionInfoEncoder(true);
run.setPresentation(Presentation.LIST);
run.setUnit("Hours");
run.setUnitSymbol("h");
coverageEncoder.setMetadataDimension("run", run,true);
// persiste the changes
boolean config=publisher.configureCoverage(coverageEncoder, wsName, csname);
assertTrue(config);
}
|
#vulnerable code
private void fixDimensions(String wsName, String coverageStoreName, String csname) {
// get current config for the coverage to extract the params we want to set again
final RESTCoverage coverage = reader.getCoverage(wsName, coverageStoreName, csname);
final Map<String, String> params = coverage.getParametersList();
// prepare and fill the encoder
final GSImageMosaicEncoder coverageEncoder = new GSImageMosaicEncoder();
coverageEncoder.setName("mosaic");
// set the current params, change here if you want to change the values
for(Map.Entry<String, String> entry:params.entrySet()){
if(entry.getKey().equals(GSImageMosaicEncoder.allowMultithreading)){
coverageEncoder.setAllowMultithreading(Boolean.parseBoolean(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.backgroundValues)){
coverageEncoder.setBackgroundValues(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.filter)){
coverageEncoder.setFilter(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.inputTransparentColor)){
coverageEncoder.setInputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.maxAllowedTiles)){
coverageEncoder.setMaxAllowedTiles(Integer.parseInt(entry.getValue()));
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.MERGEBEHAVIOR)){
coverageEncoder.setMergeBehavior(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.outputTransparentColor)){
coverageEncoder.setOutputTransparentColor(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SORTING)){
coverageEncoder.setSORTING(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.SUGGESTED_TILE_SIZE)){
coverageEncoder.setSUGGESTED_TILE_SIZE(entry.getValue());
continue;
}
if(entry.getKey().equals(GSImageMosaicEncoder.USE_JAI_IMAGEREAD)){
coverageEncoder.setUSE_JAI_IMAGEREAD(Boolean.parseBoolean(entry.getValue()));
continue;
}
}
// activate time dimension
final GSDimensionInfoEncoder time=new GSDimensionInfoEncoder(true);
time.setUnit("Seconds");
time.setUnitSymbol("s");
time.setPresentation(Presentation.CONTINUOUS_INTERVAL);
coverageEncoder.setMetadataDimension("time", time);
// activate run which is a custom dimension
final GSDimensionInfoEncoder run=new GSDimensionInfoEncoder(true);
run.setPresentation(Presentation.LIST);
run.setUnit("Hours");
run.setUnitSymbol("h");
coverageEncoder.setMetadataDimension("run", run,true);
// persiste the changes
boolean config=publisher.configureCoverage(coverageEncoder, wsName, csname);
assertTrue(config);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
|
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
|
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
|
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
// In practice, it's safe not to synchornize here, but this make Findbugs happy.
synchronized (this) {
this.isStarted = false;
}
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
|
#vulnerable code
@Override
public void stop() {
this.channelPool.stop();
if (this.sslChannelPool != null) {
this.sslChannelPool.stop();
}
if (this.http2ChannelPool != null) {
this.http2ChannelPool.stop();
}
this.isStarted = false;
if (this.host != null) {
this.host.stopService(this.callbackService);
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
ScheduledExecutorService getScheduledExecutor() {
return this.scheduledExecutor;
}
|
#vulnerable code
void startOrSynchService(Operation post, Service child) {
Service s = findService(post.getUri().getPath());
if (s == null) {
startService(post, child);
return;
}
Operation synchPut = Operation.createPut(post.getUri())
.setBody(new ServiceDocument())
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_FORWARDING)
.setReplicationDisabled(true)
.addRequestHeader(Operation.REPLICATION_PHASE_HEADER,
Operation.REPLICATION_PHASE_SYNCHRONIZE)
.setReferer(post.getReferer())
.setCompletion((o, e) -> {
if (e != null) {
post.setStatusCode(o.getStatusCode()).setBodyNoCloning(o.getBodyRaw())
.fail(e);
return;
}
post.complete();
});
sendRequest(synchPut);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Autowired(type = PandaTypes.TYPES_LABEL)
@AutowiredParameters(skip = 3, value = {
@Type(with = Src.class, value = "return"),
@Type(with = Src.class, value = "name"),
@Type(with = Src.class, value = "*parameters")
})
boolean parse(ParserData data, LocalData local, ExtractorResult result, Tokens type, String method, Tokens parametersSource) {
MethodVisibility visibility = MethodVisibility.PUBLIC;
boolean isStatic = result.getIdentifiers().contains("static");
ModuleLoader registry = data.getComponent(PandaComponents.PANDA_SCRIPT).getModuleLoader();
ClassPrototypeReference returnType = registry.forClass(type.asString());
ParameterParser parameterParser = new ParameterParser();
List<Parameter> parameters = parameterParser.parse(data, parametersSource);
ClassPrototypeReference[] parameterTypes = ParameterUtils.toTypes(parameters);
MethodScope methodScope = local.allocateInstance(new MethodScope(method, parameters));
ParameterUtils.addAll(methodScope.getVariables(), parameters, 0);
data.setComponent(PandaComponents.SCOPE, methodScope);
ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
ClassPrototypeScope classScope = data.getComponent(ClassPrototypeComponents.CLASS_SCOPE);
PrototypeMethod prototypeMethod = PandaMethod.builder()
.prototype(prototype.getReference())
.parameterTypes(parameterTypes)
.methodName(method)
.visibility(visibility)
.returnType(returnType)
.isStatic(isStatic)
.methodBody(new PandaMethodCallback(methodScope))
.build();
prototype.getMethods().registerMethod(prototypeMethod);
return true;
}
|
#vulnerable code
@Autowired(type = PandaTypes.TYPES_LABEL)
@AutowiredParameters(skip = 3, value = {
@Type(with = Src.class, value = "return"),
@Type(with = Src.class, value = "name"),
@Type(with = Src.class, value = "*parameters")
})
boolean parse(ParserData data, LocalData local, ExtractorResult result, Tokens type, String method, Tokens parametersSource) {
MethodVisibility visibility = MethodVisibility.PUBLIC;
boolean isStatic = result.getIdentifiers().contains("static");
ModuleLoader registry = data.getComponent(PandaComponents.PANDA_SCRIPT).getModuleLoader();
ClassPrototype returnType = registry.forClass(type.asString()).get();
ParameterParser parameterParser = new ParameterParser();
List<Parameter> parameters = parameterParser.parse(data, parametersSource);
ClassPrototype[] parameterTypes = ParameterUtils.toTypes(parameters);
MethodScope methodScope = local.allocateInstance(new MethodScope(method, parameters));
ParameterUtils.addAll(methodScope.getVariables(), parameters, 0);
data.setComponent(PandaComponents.SCOPE, methodScope);
ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE);
ClassPrototypeScope classScope = data.getComponent(ClassPrototypeComponents.CLASS_SCOPE);
PrototypeMethod prototypeMethod = PandaMethod.builder()
.prototype(prototype)
.parameterTypes(parameterTypes)
.methodName(method)
.visibility(visibility)
.returnType(returnType)
.isStatic(isStatic)
.methodBody(new PandaMethodCallback(methodScope))
.build();
prototype.getMethods().registerMethod(prototypeMethod);
return true;
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.