output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = directMemoryService.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod1 != 0) {
currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod2 != 0) {
valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
|
#vulnerable code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = JvmUtil.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.getAddressSize();
if (addressMod1 != 0) {
currentAddress += (JvmUtil.getAddressSize() - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.getAddressSize();
if (addressMod2 != 0) {
valueAddress += (JvmUtil.getAddressSize() - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
sampleStr = new String();
sampleStrAddress = JvmUtil.addressOf(sampleStr);
sampleCharArray = new char[0];
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void init() {
super.init();
currentAddress = stringsStartAddress;
full = false;
currentSegmentIndex = INDEX_NOT_YET_USED;
currentSegmentBlockIndex = INDEX_NOT_YET_USED;
directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0);
}
|
#vulnerable code
@Override
protected void init() {
super.init();
currentAddress = stringsStartAddress;
full = false;
currentIndex = INDEX_NOT_YET_USED;
currentBlockIndex = INDEX_NOT_YET_USED;
directMemoryService.setMemory(inUseBlockAddress, inUseBlockCount, (byte)0);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
// Allocated objects must start aligned as address size from start address of allocated address
long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
|
#vulnerable code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
objectsEndAddress = allocationEndAddress;
currentAddress = allocationStartAddress - objectSize;
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = allocationStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize();
if (addressMod != 0) {
objStartAddress += (JvmUtil.getAddressSize() - addressMod);
}
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(allocationStartAddress);
switch (JvmUtil.getAddressSize()) {
case JvmUtil.SIZE_32_BIT:
jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.SIZE_64_BIT:
int referenceSize = JvmUtil.getReferenceSize();
switch (referenceSize) {
case JvmUtil.ADDRESSING_4_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.ADDRESSING_8_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
default:
throw new AssertionError("Unsupported reference size: " + referenceSize);
}
break;
default:
throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize());
}
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void init() {
super.init();
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
|
#vulnerable code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
// Allocated objects must start aligned as address size from start address of allocated address
long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = directMemoryService.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod1 != 0) {
currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod2 != 0) {
valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
|
#vulnerable code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = JvmUtil.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.getAddressSize();
if (addressMod1 != 0) {
currentAddress += (JvmUtil.getAddressSize() - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.getAddressSize();
if (addressMod2 != 0) {
valueAddress += (JvmUtil.getAddressSize() - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType);
// All index in object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(
allocationStartAddress + i,
directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount);
// All index is object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress);
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
int estimatedSizeMod = estimatedStringSize % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (estimatedSizeMod != 0) {
estimatedStringSize += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - estimatedSizeMod);
}
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
totalSegmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
totalSegmentCount++;
}
inUseBlockCount = totalSegmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = totalSegmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
sampleStr = new String();
sampleStrAddress = JvmUtil.addressOf(sampleStr);
sampleCharArray = new char[0];
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
// Clear array content
directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0);
primitiveArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress);
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType);
// All index in object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(
allocationStartAddress + i,
directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount);
// All index is object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress);
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize();
if (addressMod != 0) {
objStartAddress += (JvmUtil.getAddressSize() - addressMod);
}
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(allocationStartAddress);
switch (JvmUtil.getAddressSize()) {
case JvmUtil.SIZE_32_BIT:
jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.SIZE_64_BIT:
int referenceSize = JvmUtil.getReferenceSize();
switch (referenceSize) {
case JvmUtil.ADDRESSING_4_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.ADDRESSING_8_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
default:
throw new AssertionError("Unsupported reference size: " + referenceSize);
}
break;
default:
throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize());
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
sampleStr = new String();
sampleStrAddress = JvmUtil.addressOf(sampleStr);
sampleCharArray = new char[0];
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean isMe(A array) {
checkAvailability();
return getObjectArray() == array;
}
|
#vulnerable code
@Override
public boolean isMe(A array) {
checkAvailability();
return objectArray == array;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void objectRetrievedSuccessfullyFromEagerReferencedObjectOffHeapPool() {
EagerReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool =
offHeapService.createOffHeapPool(
new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>().
type(SampleOffHeapClass.class).
objectCount(ELEMENT_COUNT).
referenceType(ObjectPoolReferenceType.EAGER_REFERENCED).
build());
for (int i = 0; true; i++) {
SampleOffHeapClass obj = objectPool.get();
if (obj == null) {
break;
}
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
objectPool.reset();
for (int i = 0; i < ELEMENT_COUNT; i++) {
SampleOffHeapClass obj = objectPool.getAt(i);
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
}
|
#vulnerable code
@Test
public void objectRetrievedSuccessfullyFromEagerReferencedObjectOffHeapPool() {
EagerReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool =
offHeapService.createOffHeapPool(
new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>().
type(SampleOffHeapClass.class).
objectCount(ELEMENT_COUNT).
referenceType(ObjectPoolReferenceType.EAGER_REFERENCED).
build());
for (int i = 0; i < ELEMENT_COUNT; i++) {
SampleOffHeapClass obj = objectPool.get();
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
objectPool.reset();
for (int i = 0; i < ELEMENT_COUNT; i++) {
SampleOffHeapClass obj = objectPool.getAt(i);
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
// Clear array content
directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0);
primitiveArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress);
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
directMemoryService.copyMemory(
sampleObjectAddress,
objStartAddress + (l * objectSize),
objectSize);
}
/*
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
*/
}
else {
// All indexes in object pool array point to empty (null) object
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L);
}
}
//this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
directMemoryService.setObjectField(this, "objectArray", directMemoryService.getObject(arrayStartAddress));
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
directMemoryService.copyMemory(
sampleObjectAddress,
objStartAddress + (l * objectSize),
objectSize);
}
/*
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
*/
}
else {
// All indexes in object pool array point to empty (null) object
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L);
}
}
this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType);
// All index in object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(
allocationStartAddress + i,
directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount);
// All index is object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress);
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
sampleStr = new String();
sampleStrAddress = JvmUtil.addressOf(sampleStr);
sampleCharArray = new char[0];
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
int estimatedSizeMod = estimatedStringSize % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (estimatedSizeMod != 0) {
estimatedStringSize += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - estimatedSizeMod);
}
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
totalSegmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
totalSegmentCount++;
}
inUseBlockCount = totalSegmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = totalSegmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
directMemoryService.copyMemory(
sampleObjectAddress,
objStartAddress + (l * objectSize),
objectSize);
}
/*
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
*/
}
else {
// All indexes in object pool array point to empty (null) object
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L);
}
}
// this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
directMemoryService.copyMemory(
sampleObjectAddress,
objStartAddress + (l * objectSize),
objectSize);
}
/*
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
*/
}
else {
// All indexes in object pool array point to empty (null) object
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L);
}
}
this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void init() {
super.init();
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
|
#vulnerable code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
// Allocated objects must start aligned as address size from start address of allocated address
long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize();
if (addressMod != 0) {
objStartAddress += (JvmUtil.getAddressSize() - addressMod);
}
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(allocationStartAddress);
switch (JvmUtil.getAddressSize()) {
case JvmUtil.SIZE_32_BIT:
jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.SIZE_64_BIT:
int referenceSize = JvmUtil.getReferenceSize();
switch (referenceSize) {
case JvmUtil.ADDRESSING_4_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.ADDRESSING_8_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
default:
throw new AssertionError("Unsupported reference size: " + referenceSize);
}
break;
default:
throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize());
}
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
sampleStr = new String();
sampleStrAddress = JvmUtil.addressOf(sampleStr);
sampleCharArray = new char[0];
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
segmentCount = allocationSize / STRING_SEGMENT_SIZE;
long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE;
if (segmentCountMod != 0) {
segmentCount++;
}
inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK;
if (blockCountMod != 0) {
inUseBlockCount++;
fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1);
}
else {
fullValueOfLastBlock = BLOCK_IS_FULL_VALUE;
}
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleHeader = directMemoryService.getInt(new String(), 0L);
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
|
#vulnerable code
@SuppressWarnings("deprecation")
protected void init(int estimatedStringCount, int estimatedStringLength) {
try {
this.estimatedStringCount = estimatedStringCount;
this.estimatedStringLength = estimatedStringLength;
charArrayIndexScale = JvmUtil.arrayIndexScale(char.class);
charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class);
valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value"));
stringSize = (int) JvmUtil.sizeOf(String.class);
int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength));
allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
allocationStartAddress = directMemoryService.allocateMemory(allocationSize);
allocationEndAddress = allocationStartAddress + allocationSize;
// Allocated objects must start aligned as address size from start address of allocated address
stringsStartAddress = allocationStartAddress;
long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
currentAddress = stringsStartAddress;
sampleStr = new String();
sampleStrAddress = JvmUtil.addressOf(sampleStr);
sampleCharArray = new char[0];
init();
makeAvaiable();
}
catch (Throwable t) {
logger.error("Error occured while initializing \"StringOffHeapPool\"", t);
throw new IllegalStateException(t);
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize();
if (addressMod != 0) {
objStartAddress += (JvmUtil.getAddressSize() - addressMod);
}
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
if (initializeElements) {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = sampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < length; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
else {
// All index is object pool array header point to allocated objects
for (long l = 0; l < length; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0);
}
}
this.objectArray = (A) directMemoryService.getObject(allocationStartAddress);
switch (JvmUtil.getAddressSize()) {
case JvmUtil.SIZE_32_BIT:
jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.SIZE_64_BIT:
int referenceSize = JvmUtil.getReferenceSize();
switch (referenceSize) {
case JvmUtil.ADDRESSING_4_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
case JvmUtil.ADDRESSING_8_BYTE:
jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder();
break;
default:
throw new AssertionError("Unsupported reference size: " + referenceSize);
}
break;
default:
throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize());
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
// Clear array content
directMemoryService.setMemory(arrayIndexStartAddress, arrayIndexScale * length, (byte) 0);
primitiveArray = (A) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, length);
this.primitiveArray = (A) directMemoryService.getObject(allocationStartAddress);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType);
// All index in object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(arrayStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(
allocationStartAddress + i,
directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount);
// All index is object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress);
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public T getAt(int index) {
checkAvailability();
if (index < 0 || index >= objectCount) {
throw new IllegalArgumentException("Invalid index: " + index);
}
if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) {
throw new ObjectInUseException(index);
}
// Address of class could be changed by GC at "Compact" phase.
//long address = objectsStartAddress + (index * objectSize);
//updateClassPointerOfObject(address);
return takeObject(objectArray[index]);
}
|
#vulnerable code
@Override
public T getAt(int index) {
checkAvailability();
if (index < 0 || index >= objectCount) {
throw new IllegalArgumentException("Invalid index: " + index);
}
if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) {
throw new ObjectInUseException(index);
}
if (index == 0) {
System.out.println(directMemoryService.addressOf(objectArray) + ", " + arrayStartAddress);
}
// Address of class could be changed by GC at "Compact" phase.
//long address = objectsStartAddress + (index * objectSize);
//updateClassPointerOfObject(address);
return takeObject(objectArray[index]);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public T getAt(int index) {
checkAvailability();
if (index < 0 || index >= objectCount) {
throw new IllegalArgumentException("Invalid index: " + index);
}
if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) {
throw new ObjectInUseException(index);
}
// Address of class could be changed by GC at "Compact" phase.
//long address = objectsStartAddress + (index * objectSize);
//updateClassPointerOfObject(address);
return takeObject(objectArray[index]);
}
|
#vulnerable code
@Override
public T getAt(int index) {
checkAvailability();
if (index < 0 || index >= objectCount) {
throw new IllegalArgumentException("Invalid index: " + index);
}
if (getInUseFromObjectIndex(index) != OBJECT_IS_AVAILABLE) {
throw new ObjectInUseException(index);
}
if (index == 0) {
System.out.println(directMemoryService.addressOf(objectArray) + ", " + arrayStartAddress);
}
// Address of class could be changed by GC at "Compact" phase.
//long address = objectsStartAddress + (index * objectSize);
//updateClassPointerOfObject(address);
return takeObject(objectArray[index]);
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void init() {
super.init();
currentAddress = stringsStartAddress;
full = false;
currentSegmentIndex = INDEX_NOT_YET_USED;
//directMemoryService.setMemory(inUseSegmentAddress, totalSegmentCount, (byte) 0x00);
}
|
#vulnerable code
@Override
protected void init() {
super.init();
currentAddress = stringsStartAddress;
full = false;
currentSegmentIndex = INDEX_NOT_YET_USED;
directMemoryService.setMemory(inUseSegmentAddress, totalSegmentCount, (byte) 0x00);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
synchronized (sampleObject) {
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
}
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
|
#vulnerable code
protected void init(Class<T> elementType, long objectCount,
NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType,
DirectMemoryService directMemoryService) {
super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService);
if (elementType.isAnnotation()) {
throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isInterface()) {
throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
if (elementType.isAnonymousClass()) {
throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" +
" is not supported !");
}
this.elementType = elementType;
this.objectCount = objectCount;
this.usedObjectCount = 0;
this.directMemoryService = directMemoryService;
inUseBlockCount = objectCount;
inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount);
sampleObject = JvmUtil.getSampleInstance(elementType);
if (sampleObject == null) {
throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName());
}
sampleHeader = directMemoryService.getLong(sampleObject, 0L);
objectSize = directMemoryService.sizeOfObject(sampleObject);
offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize);
directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize);
/*
for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) {
directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i));
}
*/
/*
for (int i = 0; i < objectSize; i++) {
directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i));
}
*/
// directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize);
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = directMemoryService.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod1 != 0) {
currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod2 != 0) {
valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
|
#vulnerable code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = JvmUtil.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.getAddressSize();
if (addressMod1 != 0) {
currentAddress += (JvmUtil.getAddressSize() - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.getAddressSize();
if (addressMod2 != 0) {
valueAddress += (JvmUtil.getAddressSize() - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void objectRetrievedSuccessfullyFromLazyReferencedObjectOffHeapPool() {
LazyReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool =
offHeapService.createOffHeapPool(
new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>().
type(SampleOffHeapClass.class).
objectCount(ELEMENT_COUNT).
referenceType(ObjectPoolReferenceType.LAZY_REFERENCED).
build());
for (int i = 0; true; i++) {
SampleOffHeapClass obj = objectPool.get();
if (obj == null) {
break;
}
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
obj.setSampleOffHeapAggregatedClass(new SampleOffHeapAggregatedClass());
Assert.assertEquals(i, obj.getOrder());
}
objectPool.reset();
for (int i = 0; i < ELEMENT_COUNT; i++) {
SampleOffHeapClass obj = objectPool.getAt(i);
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
}
|
#vulnerable code
@Test
public void objectRetrievedSuccessfullyFromLazyReferencedObjectOffHeapPool() {
LazyReferencedObjectOffHeapPool<SampleOffHeapClass> objectPool =
offHeapService.createOffHeapPool(
new ObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>().
type(SampleOffHeapClass.class).
objectCount(ELEMENT_COUNT).
referenceType(ObjectPoolReferenceType.LAZY_REFERENCED).
build());
for (int i = 0; i < ELEMENT_COUNT; i++) {
SampleOffHeapClass obj = objectPool.get();
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
objectPool.reset();
for (int i = 0; i < ELEMENT_COUNT; i++) {
SampleOffHeapClass obj = objectPool.getAt(i);
Assert.assertEquals(0, obj.getOrder());
obj.setOrder(i);
Assert.assertEquals(i, obj.getOrder());
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public A getArray() {
checkAvailability();
return getObjectArray();
}
|
#vulnerable code
@Override
public A getArray() {
checkAvailability();
return objectArray;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void init() {
super.init();
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
|
#vulnerable code
@Override
protected void init() {
super.init();
objectsStartAddress = allocationStartAddress;
// Allocated objects must start aligned as address size from start address of allocated address
long addressMod = objectsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void sizeRetrievedSuccessfully() {
final int ENTRY_COUNT = Integer.SIZE - 1;
OffHeapJudyHashMap<Integer, Person> map =
new OffHeapJudyHashMap<Integer, Person>(Person.class);
for (int i = 0; i < ENTRY_COUNT; i++) {
map.put(i << i, randomizeOffHeapPerson(i, map.newElement()));
Assert.assertEquals(i + 1, map.size());
}
for (int i = 0; i < ENTRY_COUNT; i++) {
map.remove(i << i);
Assert.assertEquals(ENTRY_COUNT - (i + 1), map.size());
}
}
|
#vulnerable code
@Test
public void sizeRetrievedSuccessfully() {
final int ENTRY_COUNT = Integer.SIZE - 1;
OffHeapJudyHashMap<Integer, Person> map =
new OffHeapJudyHashMap<Integer, Person>(Person.class);
for (int i = 0; i < ENTRY_COUNT; i++) {
map.put(i << i, randomOffHeapPerson(i, map.newElement()));
Assert.assertEquals(i + 1, map.size());
}
for (int i = 0; i < ENTRY_COUNT; i++) {
map.remove(i << i);
Assert.assertEquals(ENTRY_COUNT - (i + 1), map.size());
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
this.currentIndex = 0;
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize();
if (addressMod != 0) {
objectsStartAddress += (JvmUtil.getAddressSize() - addressMod);
}
objectsEndAddress = objectsStartAddress + (objectCount * objectSize);
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(
allocationStartAddress + i,
directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount);
// All index is object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(
arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objectsStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
protected void init() {
super.init();
this.currentIndex = 0;
int arrayHeaderSize = JvmUtil.getArrayHeaderSize();
int arrayIndexScale = JvmUtil.arrayIndexScale(elementType);
long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType);
objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount);
// Allocated objects must start aligned as address size from start address of allocated address
long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress;
long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize();
if (addressMod != 0) {
objStartAddress += (JvmUtil.getAddressSize() - addressMod);
}
// Copy sample array header to object pool array header
for (int i = 0; i < arrayHeaderSize; i++) {
directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i));
}
// Set length of array object pool array
JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount);
// All index is object pool array header point to allocated objects
for (long l = 0; l < objectCount; l++) {
directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale),
JvmUtil.toJvmAddress((objStartAddress + (l * objectSize))));
}
long sourceAddress = offHeapSampleObjectAddress + 4;
long copySize = objectSize - 4;
// Copy sample object to allocated memory region for each object
for (long l = 0; l < objectCount; l++) {
long targetAddress = objStartAddress + (l * objectSize);
directMemoryService.putInt(targetAddress, 0);
directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize);
}
this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress);
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = directMemoryService.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod1 != 0) {
currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY;
if (addressMod2 != 0) {
valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
|
#vulnerable code
protected long allocateStringFromOffHeap(String str) {
long addressOfStr = JvmUtil.addressOf(str);
char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString);
int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length);
int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning
long addressMod1 = currentAddress % JvmUtil.getAddressSize();
if (addressMod1 != 0) {
currentAddress += (JvmUtil.getAddressSize() - addressMod1);
}
if (currentAddress + strSize > allocationEndAddress) {
return 0;
}
// Copy string object content to allocated area
directMemoryService.copyMemory(addressOfStr, currentAddress, strSize);
long valueAddress = currentAddress + stringSize;
long addressMod2 = valueAddress % JvmUtil.getAddressSize();
if (addressMod2 != 0) {
valueAddress += (JvmUtil.getAddressSize() - addressMod2);
}
// Copy value array in allocated string to allocated char array
directMemoryService.copyMemory(
JvmUtil.toNativeAddress(
directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)),
valueAddress,
valueArraySize);
// Now, value array in allocated string points to allocated char array
directMemoryService.putAddress(
currentAddress + valueArrayOffsetInString,
JvmUtil.toJvmAddress(valueAddress));
long allocatedStrAddress = currentAddress;
currentAddress += strSize;
return allocatedStrAddress;
}
#location 35
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) {
ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80);
connection.DELAY_IN_MS = 0;
connection.sendMessage(msg);
Assert.assertArrayEquals(msg.marshall(), baos.toByteArray());
connection.close();
}
|
#vulnerable code
private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) {
ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80);
connection.DELAY_IN_MS = 0;
connection.sendMessage(msg);
Assert.assertArrayEquals(msg.marshall(), baos.toByteArray());
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private synchronized Socket socket() throws NetworkIOException {
if (reconnectPolicy.shouldReconnect()) {
Utilities.close(socket);
socket = null;
}
if (socket == null || socket.isClosed()) {
try {
if (proxy == null) {
socket = factory.createSocket(host, port);
} else if (proxy.type() == Proxy.Type.HTTP) {
TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port);
} else {
boolean success = false;
Socket proxySocket = null;
try {
proxySocket = new Socket(proxy);
proxySocket.connect(new InetSocketAddress(host, port));
socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
success = true;
} finally {
if (!success) {
Utilities.close(proxySocket);
}
}
}
socket.setSoTimeout(readTimeout);
socket.setKeepAlive(true);
if (errorDetection) {
monitorSocket(socket);
}
reconnectPolicy.reconnected();
logger.debug("Made a new connection to APNS");
} catch (IOException e) {
logger.error("Couldn't connect to APNS server", e);
throw new NetworkIOException(e);
}
}
return socket;
}
|
#vulnerable code
private synchronized Socket socket() throws NetworkIOException {
if (reconnectPolicy.shouldReconnect()) {
Utilities.close(socket);
socket = null;
}
if (socket == null || socket.isClosed()) {
try {
if (proxy == null) {
socket = factory.createSocket(host, port);
} else if (proxy.type() == Proxy.Type.HTTP) {
TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port);
} else {
boolean success = false;
Socket proxySocket = null;
try {
proxySocket = new Socket(proxy);
proxySocket.connect(new InetSocketAddress(host, port));
socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
success = true;
} finally {
if (!success) {
Utilities.close(proxySocket);
}
}
}
if (errorDetection) {
monitorSocket(socket);
}
reconnectPolicy.reconnected();
logger.debug("Made a new connection to APNS");
} catch (IOException e) {
logger.error("Couldn't connect to APNS server", e);
throw new NetworkIOException(e);
}
}
return socket;
}
#location 30
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ApnsServiceBuilder withCert(String fileName, String password) {
FileInputStream stream = null;
try {
stream = new FileInputStream(fileName);
return withCert(stream, password);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
Utilities.close(stream);
}
}
|
#vulnerable code
public ApnsServiceBuilder withCert(String fileName, String password) {
try {
return withCert(new FileInputStream(fileName), password);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private synchronized Socket socket() throws NetworkIOException {
if (reconnectPolicy.shouldReconnect()) {
Utilities.close(socket);
socket = null;
}
if (socket == null || socket.isClosed()) {
try {
if (proxy == null) {
socket = factory.createSocket(host, port);
} else if (proxy.type() == Proxy.Type.HTTP) {
TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port);
} else {
boolean success = false;
Socket proxySocket = null;
try {
proxySocket = new Socket(proxy);
proxySocket.connect(new InetSocketAddress(host, port));
socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
success = true;
} finally {
if (!success) {
Utilities.close(proxySocket);
}
}
}
socket.setSoTimeout(readTimeout);
socket.setKeepAlive(true);
if (errorDetection) {
monitorSocket(socket);
}
reconnectPolicy.reconnected();
logger.debug("Made a new connection to APNS");
} catch (IOException e) {
logger.error("Couldn't connect to APNS server", e);
throw new NetworkIOException(e);
}
}
return socket;
}
|
#vulnerable code
private synchronized Socket socket() throws NetworkIOException {
if (reconnectPolicy.shouldReconnect()) {
Utilities.close(socket);
socket = null;
}
if (socket == null || socket.isClosed()) {
try {
if (proxy == null) {
socket = factory.createSocket(host, port);
} else if (proxy.type() == Proxy.Type.HTTP) {
TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port);
} else {
boolean success = false;
Socket proxySocket = null;
try {
proxySocket = new Socket(proxy);
proxySocket.connect(new InetSocketAddress(host, port));
socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
success = true;
} finally {
if (!success) {
Utilities.close(proxySocket);
}
}
}
if (errorDetection) {
monitorSocket(socket);
}
reconnectPolicy.reconnected();
logger.debug("Made a new connection to APNS");
} catch (IOException e) {
logger.error("Couldn't connect to APNS server", e);
throw new NetworkIOException(e);
}
}
return socket;
}
#location 29
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) {
ApnsConnectionImpl connection = new ApnsConnectionImpl(sf, "localhost", 80);
connection.DELAY_IN_MS = 0;
connection.sendMessage(msg);
Assert.assertArrayEquals(msg.marshall(), baos.toByteArray());
}
|
#vulnerable code
private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) {
ApnsConnection connection = new ApnsConnection(sf, "localhost", 80);
connection.DELAY_IN_MS = 0;
connection.sendMessage(msg);
Assert.assertArrayEquals(msg.marshall(), baos.toByteArray());
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
this.setHeader(byteBuffer.readNulsData(new EventHeader()));
// version = new NulsVersion(byteBuffer.readShort());
bestBlockHeight = byteBuffer.readVarInt();
bestBlockHash = byteBuffer.readString();
nulsVersion = byteBuffer.readString();
}
|
#vulnerable code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
this.setHeader(byteBuffer.readNulsData(new EventHeader()));
// version = new NulsVersion(byteBuffer.readShort());
bestBlockHeight = byteBuffer.readVarInt();
bestBlockHash = new String(byteBuffer.readByLengthByte());
nulsVersion = new String(byteBuffer.readByLengthByte());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void checkGenesisBlock() throws IOException {
Block genesisBlock = NulsContext.getInstance().getGenesisBlock();
genesisBlock.verify();
Block localGenesisBlock = this.blockService.getGengsisBlock();
if (null == localGenesisBlock) {
this.blockService.saveBlock(genesisBlock);
return;
}
localGenesisBlock.verify();
String logicHash = genesisBlock.getHeader().getHash().getDigestHex();
String localHash = localGenesisBlock.getHeader().getHash().getDigestHex();
if (!logicHash.equals(localHash)) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
}
|
#vulnerable code
public void checkGenesisBlock() throws IOException {
Block genesisBlock = NulsContext.getInstance().getGenesisBlock();
genesisBlock.verify();
Block localGenesisBlock = this.blockService.getGengsisBlock();
if (null == localGenesisBlock) {
this.blockService.saveBlock(genesisBlock);
return;
}
localGenesisBlock.verify();
System.out.println(genesisBlock.size()+"===="+localGenesisBlock.size());
String logicHash = genesisBlock.getHeader().getHash().getDigestHex();
System.out.println(logicHash);
String localHash = localGenesisBlock.getHeader().getHash().getDigestHex();
System.out.println(localHash);
if (!logicHash.equals(localHash)) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized PocMeetingRound resetCurrentMeetingRound() {
Block currentBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend());
PocMeetingRound currentRound = ROUND_MAP.get(currentRoundData.getRoundIndex());
boolean needCalcRound = false;
do {
if (null == currentRound) {
needCalcRound = true;
break;
}
if (currentRound.getEndTime() < TimeService.currentTimeMillis()) {
needCalcRound = true;
break;
}
boolean thisIsLastBlockOfRound = currentRoundData.getPackingIndexOfRound() == currentRoundData.getConsensusMemberCount();
if (currentRound.getIndex() == currentRoundData.getRoundIndex() && !thisIsLastBlockOfRound) {
needCalcRound = false;
break;
}
if (currentRound.getIndex() == (currentRoundData.getRoundIndex() + 1) && thisIsLastBlockOfRound) {
needCalcRound = false;
break;
}
needCalcRound = true;
} while (false);
PocMeetingRound resultRound = null;
if (needCalcRound) {
if (null != ROUND_MAP.get(currentRoundData.getRoundIndex() + 1)) {
resultRound = ROUND_MAP.get(currentRoundData.getRoundIndex() + 1);
} else {
resultRound = calcNextRound(currentBlock, currentRoundData);
}
}
if (resultRound.getPreRound() == null) {
resultRound.setPreRound(ROUND_MAP.get(currentRoundData.getRoundIndex() + 1));
}
List<Account> accountList = accountService.getAccountList();
resultRound.calcLocalPacker(accountList);
this.currentRound = resultRound;
ROUND_MAP.put(resultRound.getIndex(),currentRound);
return resultRound;
}
|
#vulnerable code
public synchronized PocMeetingRound resetCurrentMeetingRound() {
Block currentBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend());
PocMeetingRound currentRound = ROUND_MAP.get(currentRoundData.getRoundIndex());
boolean needCalcRound = false;
do {
if (null == currentRound) {
needCalcRound = true;
break;
}
if (currentRound.getEndTime() < TimeService.currentTimeMillis()) {
needCalcRound = true;
break;
}
boolean thisIsLastBlockOfRound = currentRoundData.getPackingIndexOfRound() == currentRoundData.getConsensusMemberCount();
if (currentRound.getIndex() == currentRoundData.getRoundIndex() && !thisIsLastBlockOfRound) {
needCalcRound = false;
break;
}
if (currentRound.getIndex() == (currentRoundData.getRoundIndex() + 1) && thisIsLastBlockOfRound) {
needCalcRound = false;
break;
}
needCalcRound = true;
} while (false);
PocMeetingRound resultRound = null;
if (needCalcRound) {
if (null != ROUND_MAP.get(currentRoundData.getRoundIndex() + 1)) {
resultRound = ROUND_MAP.get(currentRoundData.getRoundIndex() + 1);
} else {
resultRound = calcNextRound(currentBlock, currentRoundData);
}
}
if (resultRound.getPreRound() == null) {
resultRound.setPreRound(ROUND_MAP.get(currentRoundData.getRoundIndex() + 1));
}
List<Account> accountList = accountService.getAccountList();
resultRound.calcLocalPacker(accountList);
this.currentRound = resultRound;
return resultRound;
}
#location 35
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Block getHighestBlock() {
BlockHeaderChain chain = bifurcateProcessor.getApprovingChain();
if (null == chain) {
return null;
}
HeaderDigest headerDigest = chain.getLastHd();
if(null==headerDigest){
return null;
}
return this.getBlock(headerDigest.getHash());
}
|
#vulnerable code
public Block getHighestBlock() {
BlockHeaderChain chain = bifurcateProcessor.getApprovingChain();
if (null == chain) {
return null;
}
HeaderDigest headerDigest = chain.getLastHd();
return this.getBlock(headerDigest.getHash());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void init() {
//load local account list into cache
}
|
#vulnerable code
@Override
public void init() {
NulsContext.getServiceBean(AccountLedgerService.class).init();
//load local account list into cache
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ValidateResult validate(BlockHeader header, List<Transaction> txs) {
if (header.getHeight() == 0) {
return ValidateResult.getSuccessResult();
}
BlockRoundData
roundData = new BlockRoundData(header.getExtend());
Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex());
if (null == preBlock) {
//When a block does not exist, it is temporarily validated.
return ValidateResult.getSuccessResult();
}
calc(preBlock);
BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend());
PocMeetingRound localThisRoundData = this.currentRound;
PocMeetingRound localPreRoundData;
if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) {
localPreRoundData = localThisRoundData;
} else {
localPreRoundData = localThisRoundData.getPreRound();
}
if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound());
if (null == member) {
return ValidateResult.getFailedResult("Cannot find the packing member!");
}
if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) {
ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!");
vr.setObject(header);
vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
return vr;
}
if (null == txs) {
return ValidateResult.getSuccessResult();
}
YellowPunishTransaction yellowPunishTx = null;
for (Transaction tx : txs) {
if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
if (yellowPunishTx == null) {
yellowPunishTx = (YellowPunishTransaction) tx;
} else {
return ValidateResult.getFailedResult("There are too many yellow punish transactions!");
}
}
}
//when the blocks are continuous
boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1);
isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() &&
roundData.getPackingIndexOfRound() == 1);
//Too long intervals will not be penalized.
boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1);
if (longTimeAgo && yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
}
if (isContinuous) {
if (yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
} else {
return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!");
}
} else {
if (null == yellowPunishTx) {
return ValidateResult.getFailedResult("It should be a yellow punish tx here!");
}
if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) {
return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!");
}
int interval = 0;
if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) {
interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1;
} else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) {
interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1;
}
if (interval != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval);
} else {
long roundIndex = preRoundData.getRoundIndex();
long indexOfRound = preRoundData.getPackingIndexOfRound() + 1;
List<String> addressList = new ArrayList<>();
while (true) {
PocMeetingRound round = getRoundData(roundIndex);
if (null == round) {
break;
}
if (roundIndex == roundData.getRoundIndex() && roundData.getPackingIndexOfRound() <= indexOfRound) {
break;
}
if (round.getMemberCount() < indexOfRound) {
roundIndex++;
indexOfRound = 1;
continue;
}
PocMeetingMember meetingMember = round.getMember(interval);
if (null == meetingMember) {
return ValidateResult.getFailedResult("the round data has error!");
}
addressList.add(meetingMember.getAgentAddress());
indexOfRound++;
}
if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!");
}
for (String address : addressList) {
boolean contains = false;
for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) {
if (addressObj.getBase58().equals(address)) {
contains = true;
break;
}
}
if (!contains) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address");
}
}
}
}
return checkCoinBaseTx(header, txs, roundData, localThisRoundData);
}
|
#vulnerable code
public ValidateResult validate(BlockHeader header, List<Transaction> txs) {
if (header.getHeight() == 0) {
return ValidateResult.getSuccessResult();
}
BlockRoundData
roundData = new BlockRoundData(header.getExtend());
Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex());
if (null == preBlock) {
//When a block does not exist, it is temporarily validated.
return ValidateResult.getSuccessResult();
}
BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend());
PocMeetingRound localPreRoundData = getRoundDataOrCalc(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData);
PocMeetingRound localThisRoundData = null;
if (localPreRoundData.getIndex() == roundData.getRoundIndex()) {
localThisRoundData = localPreRoundData;
} else {
localThisRoundData = getRoundDataOrCalc(header, header.getHeight(), roundData);
//Verify that the time of the two turns is correct.
ValidateResult result = checkThisRound(localPreRoundData, localThisRoundData, roundData, header);
if (result.isFailed()) {
return result;
}
}
if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound());
if (null == member) {
return ValidateResult.getFailedResult("Cannot find the packing member!");
}
if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) {
ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!");
vr.setObject(header);
vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
return vr;
}
if (null == txs) {
return ValidateResult.getSuccessResult();
}
YellowPunishTransaction yellowPunishTx = null;
for (Transaction tx : txs) {
if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
if (yellowPunishTx == null) {
yellowPunishTx = (YellowPunishTransaction) tx;
} else {
return ValidateResult.getFailedResult("There are too many yellow punish transactions!");
}
}
}
//when the blocks are continuous
boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1);
isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() &&
roundData.getPackingIndexOfRound() == 1);
//Too long intervals will not be penalized.
boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1);
if (longTimeAgo && yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
}
if (isContinuous) {
if (yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
} else {
return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!");
}
} else {
if (null == yellowPunishTx) {
return ValidateResult.getFailedResult("It should be a yellow punish tx here!");
}
if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) {
return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!");
}
int interval = 0;
if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) {
interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1;
} else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) {
interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1;
}
if (interval != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval);
} else {
long roundIndex = preRoundData.getRoundIndex();
long indexOfRound = preRoundData.getPackingIndexOfRound() + 1;
List<String> addressList = new ArrayList<>();
while (true) {
PocMeetingRound round = getRoundData(roundIndex);
if (null == round) {
break;
}
if (roundIndex == roundData.getRoundIndex() && roundData.getPackingIndexOfRound() <= indexOfRound) {
break;
}
if (round.getMemberCount() < indexOfRound) {
roundIndex++;
indexOfRound = 1;
continue;
}
PocMeetingMember meetingMember = round.getMember(interval);
if (null == meetingMember) {
return ValidateResult.getFailedResult("the round data has error!");
}
addressList.add(meetingMember.getAgentAddress());
indexOfRound++;
}
if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!");
}
for (String address : addressList) {
if (!yellowPunishTx.getTxData().getAddressList().contains(address)) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address");
}
}
}
}
return checkCoinBaseTx(header, txs, roundData, localThisRoundData);
}
#location 92
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void init() {
accountService = AccountServiceImpl.getInstance();
//default local account
List<Account> list = this.accountService.getLocalAccountList();
if (null != list && !list.isEmpty()) {
Locla_acount_id = list.get(0).getId();
}
}
|
#vulnerable code
public void init() {
accountService = NulsContext.getInstance().getService(AccountService.class);
//default local account
List<Account> list = this.accountService.getLocalAccountList();
if (null != list && !list.isEmpty()) {
Locla_acount_id = list.get(0).getId();
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void destroy() {
lock.lock();
try {
this.status = Peer.CLOSE;
if (this.writeTarget != null) {
this.writeTarget.closeConnection();
this.writeTarget = null;
}
} finally {
lock.unlock();
}
//todo check failCount and save or remove from database
//this.failCount ++;
}
|
#vulnerable code
public void destroy() {
System.out.println("---------peer destory:" + this.getIp());
lock.lock();
try {
this.status = Peer.CLOSE;
if (this.writeTarget != null) {
this.writeTarget.closeConnection();
this.writeTarget = null;
}
} finally {
lock.unlock();
}
//todo check failCount and save or remove from database
//this.failCount ++;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void rollbackHeaderDigest(String hash) {
for (int i = 0; i < headerDigestList.size(); i++) {
HeaderDigest headerDigest = headerDigestList.get(i);
if (headerDigest.getHash().equals(hash)) {
headerDigestList.remove(headerDigest);
for (int x = i + 1; x < headerDigestList.size(); x++) {
headerDigestList.remove(x);
}
break;
}
}
}
|
#vulnerable code
public void rollbackHeaderDigest(String hash) {
for (int i = 0; i < headerDigestList.size(); i++) {
HeaderDigest headerDigest = headerDigestList.get(i);
if (headerDigest.getHash().equals(hash)) {
headerDigestList.remove(headerDigest);
for (int x = i + 1; x < headerDigestList.size(); x++) {
headerDigestList.remove(x);
}
this.lastHd = null;
break;
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void reSendLocalTx() throws NulsException {
List<Transaction> txList = getLedgerCacheService().getUnconfirmTxList();
List<Transaction> helpList = new ArrayList<>();
for (Transaction tx : txList) {
if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) {
continue;
}
ValidateResult result = getLedgerService().verifyTx(tx, helpList);
if (result.isFailed()) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex());
continue;
}
Transaction transaction = getLedgerService().getTx(tx.getHash());
if (transaction != null) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
ledgerCacheService.removeLocalTx(tx.getHash().getDigestHex());
continue;
}
helpList.add(tx);
TransactionEvent event = new TransactionEvent();
event.setEventBody(tx);
getEventBroadcaster().publishToLocal(event);
}
}
|
#vulnerable code
private void reSendLocalTx() throws NulsException {
List<Transaction> txList = getLedgerService().getWaitingTxList();
List<Transaction> helpList = new ArrayList<>();
for (Transaction tx : txList) {
if (TimeService.currentTimeMillis() - tx.getTime() < DateUtil.MINUTE_TIME * 2) {
continue;
}
ValidateResult result = ledgerService.verifyTx(tx, helpList);
if (result.isFailed()) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
continue;
}
Transaction transaction = getLedgerService().getTx(tx.getHash());
if (transaction != null) {
getLocalDataService().deleteUnCofirmTx(tx.getHash().getDigestHex());
continue;
}
helpList.add(tx);
TransactionEvent event = new TransactionEvent();
event.setEventBody(tx);
getEventBroadcaster().publishToLocal(event);
}
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void start() {
consensusManager.init();
this.registerHandlers();
this.consensusManager.startMaintenanceWork();
consensusManager.joinConsensusMeeting();
consensusManager.startPersistenceWork();
Log.info("the POC consensus module is started!");
TaskManager.createAndRunThread(this.getModuleId(),"block-cache-check",new BlockCacheCheckThread());
}
|
#vulnerable code
@Override
public void start() {
consensusManager.init();
NulsContext.getInstance().setBestBlock(NulsContext.getServiceBean(BlockService.class).getLocalBestBlock());
this.registerHandlers();
this.consensusManager.startMaintenanceWork();
consensusManager.joinConsensusMeeting();
consensusManager.startPersistenceWork();
Log.info("the POC consensus module is started!");
TaskManager.createAndRunThread(this.getModuleId(),"block-cache-check",new BlockCacheCheckThread());
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException {
Block bestBlock = this.blockService.getBestBlock();
List<Transaction> allTxList = txCacheManager.getTxList();
allTxList.sort(TxTimeComparator.getInstance());
BlockData bd = new BlockData();
bd.setHeight(bestBlock.getHeader().getHeight() + 1);
bd.setPreHash(bestBlock.getHeader().getHash());
BlockRoundData roundData = new BlockRoundData();
roundData.setRoundIndex(round.getIndex());
roundData.setConsensusMemberCount(round.getMemberCount());
roundData.setPackingIndexOfRound(self.getPackingIndexOfRound());
roundData.setRoundStartTime(round.getStartTime());
bd.setRoundData(roundData);
List<Integer> outTxList = new ArrayList<>();
List<Transaction> packingTxList = new ArrayList<>();
List<NulsDigestData> outHashList = new ArrayList<>();
long totalSize = 0L;
for (int i = 0; i < allTxList.size(); i++) {
if ((self.getPackEndTime() - TimeService.currentTimeMillis()) <= 500L) {
break;
}
Transaction tx = allTxList.get(i);
tx.setBlockHeight(bd.getHeight());
if ((totalSize + tx.size()) >= PocConsensusConstant.MAX_BLOCK_SIZE) {
break;
}
outHashList.add(tx.getHash());
ValidateResult result = tx.verify();
if (result.isFailed()) {
Log.error(result.getMessage());
outTxList.add(i);
BlockLog.info("discard tx:" + tx.getHash());
continue;
}
try {
ledgerService.approvalTx(tx);
} catch (Exception e) {
Log.error(e);
outTxList.add(i);
BlockLog.info("discard tx:" + tx.getHash());
continue;
}
packingTxList.add(tx);
totalSize += tx.size();
confirmingTxCacheManager.putTx(tx);
}
txCacheManager.removeTx(outHashList);
if (totalSize < PocConsensusConstant.MAX_BLOCK_SIZE) {
addOrphanTx(packingTxList, totalSize, self, bd.getHeight());
}
addConsensusTx(bestBlock, packingTxList, self, round);
bd.setTxList(packingTxList);
Block newBlock = ConsensusTool.createBlock(bd, round.getLocalPacker());
ValidateResult result = newBlock.verify();
if (result.isFailed()) {
BlockLog.warn("packing block error:" + result.getMessage());
for (Transaction tx : newBlock.getTxs()) {
ledgerService.rollbackTx(tx);
}
return null;
}
return newBlock;
}
|
#vulnerable code
private Block doPacking(PocMeetingMember self, PocMeetingRound round) throws NulsException, IOException {
Block bestBlock = this.blockService.getBestBlock();
List<Transaction> allTxList = txCacheManager.getTxList();
allTxList.sort(TxTimeComparator.getInstance());
BlockData bd = new BlockData();
bd.setHeight(bestBlock.getHeader().getHeight() + 1);
bd.setPreHash(bestBlock.getHeader().getHash());
BlockRoundData roundData = new BlockRoundData();
roundData.setRoundIndex(round.getIndex());
roundData.setConsensusMemberCount(round.getMemberCount());
roundData.setPackingIndexOfRound(self.getPackingIndexOfRound());
roundData.setRoundStartTime(round.getStartTime());
StringBuilder str = new StringBuilder();
str.append(self.getPackingAddress());
str.append(" ,order:" + self.getPackingIndexOfRound());
str.append(",packTime:" + new Date(self.getPackEndTime()));
str.append("\n");
BlockLog.debug("pack round:" + str);
bd.setRoundData(roundData);
List<Integer> outTxList = new ArrayList<>();
List<Transaction> packingTxList = new ArrayList<>();
List<NulsDigestData> outHashList = new ArrayList<>();
long totalSize = 0L;
for (int i = 0; i < allTxList.size(); i++) {
if ((self.getPackEndTime() - TimeService.currentTimeMillis()) <= 500L) {
break;
}
Transaction tx = allTxList.get(i);
tx.setBlockHeight(bd.getHeight());
if ((totalSize + tx.size()) >= PocConsensusConstant.MAX_BLOCK_SIZE) {
break;
}
outHashList.add(tx.getHash());
ValidateResult result = tx.verify();
if (result.isFailed()) {
Log.error(result.getMessage());
outTxList.add(i);
continue;
}
try {
ledgerService.approvalTx(tx);
} catch (Exception e) {
Log.error(e);
outTxList.add(i);
continue;
}
packingTxList.add(tx);
totalSize += tx.size();
confirmingTxCacheManager.putTx(tx);
}
txCacheManager.removeTx(outHashList);
if (totalSize < PocConsensusConstant.MAX_BLOCK_SIZE) {
addOrphanTx(packingTxList, totalSize, self,bd.getHeight());
}
addConsensusTx(bestBlock, packingTxList, self, round);
bd.setTxList(packingTxList);
Log.info("txCount:" + packingTxList.size());
Block newBlock = ConsensusTool.createBlock(bd, round.getLocalPacker());
System.out.printf("========height:" + newBlock.getHeader().getHeight() + ",time:" + DateUtil.convertDate(new Date(newBlock.getHeader().getTime())) + ",packEndTime:" +
DateUtil.convertDate(new Date(self.getPackEndTime())));
ValidateResult result = newBlock.verify();
if (result.isFailed()) {
Log.warn("packing block error:" + result.getMessage());
for (Transaction tx : newBlock.getTxs()) {
ledgerService.rollbackTx(tx);
}
return null;
}
return newBlock;
}
#location 63
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean createQueue(String queueName, long maxSize, int latelySecond) {
try {
NulsFQueue queue = new NulsFQueue(queueName, maxSize);
QueueManager.initQueue(queueName, queue, latelySecond);
return true;
} catch (Exception e) {
Log.error("", e);
return false;
}
}
|
#vulnerable code
public boolean createQueue(String queueName, long maxSize, int latelySecond) {
try {
InchainFQueue queue = new InchainFQueue(queueName, maxSize);
QueueManager.initQueue(queueName, queue, latelySecond);
return true;
} catch (Exception e) {
Log.error("", e);
return false;
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean downloadedBlock(String nodeId, Block block) {
if(!this.working){
return false;
}
try {
NodeDownloadingStatus status = nodeStatusMap.get(nodeId);
if (null == status) {
return false;
}
if (!status.containsHeight(block.getHeader().getHeight())) {
return false;
}
ValidateResult result1 = block.verify();
if (result1.isFailed() && result1.getErrorCode() != ErrorCode.ORPHAN_TX && result1.getErrorCode() != ErrorCode.ORPHAN_BLOCK) {
Log.info("recieve a block wrong!:" + nodeId + ",blockHash:" + block.getHeader().getHash());
this.nodeIdList.remove(nodeId);
if (nodeIdList.isEmpty()) {
working = false;
}
return true;
}
blockMap.put(block.getHeader().getHeight(), block);
status.downloaded(block.getHeader().getHeight());
status.setUpdateTime(TimeService.currentTimeMillis());
if (status.finished()) {
this.queueService.offer(queueId, nodeId);
}
} catch (Exception e) {
Log.error(e);
}
return true;
}
|
#vulnerable code
public boolean downloadedBlock(String nodeId, Block block) {
try {
NodeDownloadingStatus status = nodeStatusMap.get(nodeId);
if (null == status) {
return false;
}
if (!status.containsHeight(block.getHeader().getHeight())) {
return false;
}
ValidateResult result1 = block.verify();
if (result1.isFailed() && result1.getErrorCode() != ErrorCode.ORPHAN_TX && result1.getErrorCode() != ErrorCode.ORPHAN_BLOCK) {
Log.info("recieve a block wrong!:" + nodeId + ",blockHash:" + block.getHeader().getHash());
this.nodeIdList.remove(nodeId);
if (nodeIdList.isEmpty()) {
working = false;
}
return true;
}
blockMap.put(block.getHeader().getHeight(), block);
status.downloaded(block.getHeader().getHeight());
status.setUpdateTime(TimeService.currentTimeMillis());
if (status.finished()) {
this.queueService.offer(queueId, nodeId);
}
} catch (Exception e) {
Log.error(e);
}
return true;
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean canPersistence() {
return null != bifurcateProcessor.getLongestChain() && bifurcateProcessor.getLongestChain().size() > PocConsensusConstant.CONFIRM_BLOCK_COUNT;
}
|
#vulnerable code
public boolean canPersistence() {
return bifurcateProcessor.getLongestChain().size()> PocConsensusConstant.CONFIRM_BLOCK_COUNT;
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void getMemoryTxs() throws Exception {
assertNotNull(service);
Transaction tx = new TestTransaction();
tx.setTime(0l);
assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a7ad281");
Result result = service.newTx(tx);
assertNotNull(result);
assertTrue(result.isSuccess());
assertFalse(result.isFailed());
List<Transaction> memoryTxs = service.getMemoryTxs();
assertNotNull(memoryTxs);
assertEquals(1, memoryTxs.size());
tx = memoryTxs.get(0);
assertNotNull(tx);
assertEquals(tx.getHash().getDigestHex(), "0020c7f397ae78f2c1d12b3edc916e8112bcac576a98444c4c26034c207c9a7ad281");
}
|
#vulnerable code
@Test
public void getMemoryTxs() throws Exception {
assertNotNull(service);
Transaction tx = new TestTransaction();
tx.setTime(0l);
assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c43bcc4d80b47909c");
Result result = service.newTx(tx);
assertNotNull(result);
assertTrue(result.isSuccess());
assertFalse(result.isFailed());
List<Transaction> memoryTxs = service.getMemoryTxs();
assertNotNull(memoryTxs);
assertEquals(1, memoryTxs.size());
tx = memoryTxs.get(0);
assertNotNull(tx);
assertEquals(tx.getHash().getDigestHex(), "08001220d194faf5b314f54c3a299ca9ea086f3f8856c75dc44a1e0c43bcc4d80b47909c");
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
Log.debug(" ---------------------- server channelInactive ------------------------- " + nodeId);
String channelId = ctx.channel().id().asLongText();
NioChannelMap.remove(channelId);
Node node = networkService.getNode(nodeId);
if (node != null) {
if (channelId.equals(node.getChannelId())) {
// System.out.println("------------ sever channelInactive remove node-------------" + node.getId());
networkService.removeNode(nodeId);
} else {
Log.info("--------------server channel id different----------------------");
Log.info("--------node:" + node.getId() + ",type:" + node.getType());
Log.info(node.getChannelId());
Log.info(channelId);
}
}
}
|
#vulnerable code
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
Log.debug(" ---------------------- server channelInactive ------------------------- " + nodeId);
String channelId = ctx.channel().id().asLongText();
NioChannelMap.remove(channelId);
Node node = getNetworkService().getNode(nodeId);
if (node != null) {
if (channelId.equals(node.getChannelId())) {
// System.out.println("------------ sever channelInactive remove node-------------" + node.getId());
getNetworkService().removeNode(nodeId);
} else {
Log.debug("--------------channel id different----------------------");
Log.debug(node.getChannelId());
Log.debug(channelId);
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
address = Address.fromHashs(byteBuffer.readByLengthByte());
alias = new String(byteBuffer.readByLengthByte());
encryptedPriKey = byteBuffer.readByLengthByte();
pubKey = byteBuffer.readByLengthByte();
status = (int) (byteBuffer.readByte());
extend = byteBuffer.readByLengthByte();
}
|
#vulnerable code
@Override
protected void parse(NulsByteBuffer byteBuffer) throws NulsException {
alias = new String(byteBuffer.readByLengthByte());
address = new Address(new String(byteBuffer.readByLengthByte()));
encryptedPriKey = byteBuffer.readByLengthByte();
pubKey = byteBuffer.readByLengthByte();
status = (int)(byteBuffer.readVarInt());
extend = byteBuffer.readByLengthByte();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Result exportAccount(String address, String password) {
Account account = null;
if (!StringUtils.isBlank(address)) {
account = accountCacheService.getAccountByAddress(address);
if (account == null) {
return Result.getFailed(ErrorCode.DATA_NOT_FOUND);
}
if (account.isEncrypted()) {
if (!StringUtils.validPassword(password) || !account.decrypt(password)) {
return Result.getFailed(ErrorCode.PASSWORD_IS_WRONG);
}
}
}
Result result = backUpFile("");
if (!result.isSuccess()) {
return result;
}
return exportAccount(account, (File) result.getObject());
}
|
#vulnerable code
@Override
public Result exportAccount(String address, String password) {
Account account = null;
if (!StringUtils.isBlank(address)) {
account = accountCacheService.getAccountByAddress(address);
if (account == null) {
return Result.getFailed(ErrorCode.DATA_NOT_FOUND);
}
}
if (!account.decrypt(password)) {
return Result.getFailed(ErrorCode.PASSWORD_IS_WRONG);
}
Result result = backUpFile("");
if (!result.isSuccess()) {
return result;
}
return exportAccount(account, (File) result.getObject());
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
Log.debug("---------------------- server channelRegistered ------------------------- " + nodeId);
String remoteIP = channel.remoteAddress().getHostString();
Map<String, Node> nodeMap = networkService.getNodes();
//getNetworkService().getNodes();
for (Node node : nodeMap.values()) {
if (node.getIp().equals(remoteIP)) {
if (node.getType() == Node.OUT) {
String localIP = InetAddress.getLocalHost().getHostAddress();
boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP);
if (!isLocalServer) {
ctx.channel().close();
return;
} else {
// System.out.println("----------------sever client register each other remove node-----------------" + node.getId());
getNetworkService().removeNode(node.getId());
}
}
}
}
// if has a node with same ip, and it's a out node, close this channel
// if More than 10 in nodes of the same IP, close this channel
int count = 0;
for (Node n : nodeMap.values()) {
if (n.getIp().equals(remoteIP)) {
count++;
if (count >= NetworkConstant.SAME_IP_MAX_COUNT) {
ctx.channel().close();
return;
}
}
}
}
|
#vulnerable code
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
Log.debug("---------------------- server channelRegistered ------------------------- " + nodeId);
String remoteIP = channel.remoteAddress().getHostString();
Map<String, Node> nodeMap = null;
//getNetworkService().getNodes();
for (Node node : nodeMap.values()) {
if (node.getIp().equals(remoteIP)) {
if (node.getType() == Node.OUT) {
String localIP = InetAddress.getLocalHost().getHostAddress();
boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP);
if (!isLocalServer) {
ctx.channel().close();
return;
} else {
// System.out.println("----------------sever client register each other remove node-----------------" + node.getId());
getNetworkService().removeNode(node.getId());
}
}
}
}
// if has a node with same ip, and it's a out node, close this channel
// if More than 10 in nodes of the same IP, close this channel
int count = 0;
for (Node n : nodeMap.values()) {
if (n.getIp().equals(remoteIP)) {
count++;
if (count >= NetworkConstant.SAME_IP_MAX_COUNT) {
ctx.channel().close();
return;
}
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void onEvent(BlockEvent event, String fromId) {
Block block = event.getEventBody();
if (null == block) {
Log.warn("recieved a null blockEvent form " + fromId);
return;
}
for (Transaction tx : block.getTxs()) {
Transaction cachedTx = txCacheManager.getTx(tx.getHash());
if (cachedTx != null && cachedTx.getStatus() != tx.getStatus()) {
tx.setStatus(cachedTx.getStatus());
if (!(tx instanceof AbstractCoinTransaction)) {
continue;
}
AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx;
AbstractCoinTransaction cachedCoinTx = (AbstractCoinTransaction) cachedTx;
coinTx.setCoinData(cachedCoinTx.getCoinData());
// Log.error("the transaction status is wrong!");
}
}
DownloadCacheHandler.receiveBlock(block);
}
|
#vulnerable code
@Override
public void onEvent(BlockEvent event, String fromId) {
Block block = event.getEventBody();
if (null == block) {
Log.warn("recieved a null blockEvent form " + fromId);
return;
}
//BlockLog.debug("download("+fromId+") block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + block.getHeader().getPackingAddress());
// if (BlockBatchDownloadUtils.getInstance().downloadedBlock(fromId, block)) {
// return;
// }
//blockCacheManager.addBlock(block, true, fromId);
for (Transaction tx : block.getTxs()) {
Transaction cachedTx = ConfirmingTxCacheManager.getInstance().getTx(tx.getHash());
if (null == cachedTx) {
cachedTx = ReceivedTxCacheManager.getInstance().getTx(tx.getHash());
}
if (null == cachedTx) {
cachedTx = OrphanTxCacheManager.getInstance().getTx(tx.getHash());
}
if (cachedTx != null && cachedTx.getStatus() != tx.getStatus()) {
tx.setStatus(cachedTx.getStatus());
if(!(tx instanceof AbstractCoinTransaction)){
continue;
}
AbstractCoinTransaction coinTx = (AbstractCoinTransaction) tx;
AbstractCoinTransaction cachedCoinTx = (AbstractCoinTransaction) cachedTx;
coinTx.setCoinData(cachedCoinTx.getCoinData());
// Log.error("the transaction status is wrong!");
}
}
DownloadCacheHandler.receiveBlock(block);
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean containsKey(String cacheTitle, K key) {
Cache cache = this.cacheManager.getCache(cacheTitle);
if (cache == null) {
return false;
}
boolean result = cache.containsKey(key);
return result;
}
|
#vulnerable code
@Override
public boolean containsKey(String cacheTitle, K key) {
boolean result = this.cacheManager.getCache(cacheTitle).containsKey(key);
return result;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void start() {
List<Node> nodes = discoverHandler.getLocalNodes(network.maxOutCount());
if (nodes == null || nodes.isEmpty()) {
nodes = getSeedNodes();
}
for (Node node : nodes) {
node.setType(Node.OUT);
node.setStatus(Node.WAIT);
addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, node);
}
running = true;
TaskManager.createAndRunThread(NulsConstant.MODULE_ID_NETWORK, "NetworkNodeManager", this);
discoverHandler.start();
}
|
#vulnerable code
public void start() {
List<Node> nodes = discoverHandler.getLocalNodes(network.maxOutCount());
if (nodes == null && nodes.isEmpty()) {
nodes = getSeedNodes();
}
for (Node node : nodes) {
node.setType(Node.OUT);
node.setStatus(Node.WAIT);
addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, node);
}
running = true;
TaskManager.createAndRunThread(NulsConstant.MODULE_ID_NETWORK, "NetworkNodeManager", this);
discoverHandler.start();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized void syncBlock() {
this.status = MaintenanceStatus.DOWNLOADING;
while (true) {
BestCorrectBlock bestCorrectBlock = checkLocalBestCorrentBlock();
boolean doit = false;
long startHeight = 1;
do {
if (null == bestCorrectBlock.getLocalBestBlock() && bestCorrectBlock.getNetBestBlockInfo() == null) {
doit = true;
BlockInfo blockInfo = BEST_HEIGHT_FROM_NET.request(-1);
bestCorrectBlock.setNetBestBlockInfo(blockInfo);
break;
}
startHeight = bestCorrectBlock.getLocalBestBlock().getHeader().getHeight() + 1;
long interval = TimeService.currentTimeMillis() - bestCorrectBlock.getLocalBestBlock().getHeader().getTime();
if (interval < (PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 2000)) {
doit = false;
break;
}
if (null == bestCorrectBlock.getNetBestBlockInfo()) {
bestCorrectBlock.setNetBestBlockInfo(BEST_HEIGHT_FROM_NET.request(0));
}
if (null == bestCorrectBlock.getNetBestBlockInfo()) {
break;
}
if (bestCorrectBlock.getNetBestBlockInfo().getBestHeight() > bestCorrectBlock.getLocalBestBlock().getHeader().getHeight()) {
doit = true;
break;
}
} while (false);
if (null == bestCorrectBlock.getNetBestBlockInfo()) {
return;
}
if (doit) {
downloadBlocks(bestCorrectBlock.getNetBestBlockInfo().getNodeIdList(), startHeight, bestCorrectBlock.getNetBestBlockInfo().getBestHeight());
} else {
break;
}
long start = TimeService.currentTimeMillis();
//todo
long timeout = (bestCorrectBlock.getNetBestBlockInfo().getBestHeight()-startHeight+1)*100;
while (NulsContext.getInstance().getBestHeight()<bestCorrectBlock.getNetBestBlockInfo().getBestHeight()){
if(TimeService.currentTimeMillis()>(timeout+start)){
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.error(e);
}
}
}
}
|
#vulnerable code
public synchronized void syncBlock() {
this.status = MaintenanceStatus.DOWNLOADING;
BestCorrectBlock bestCorrectBlock = checkLocalBestCorrentBlock();
boolean doit = false;
long startHeight = 1;
do {
if (null == bestCorrectBlock.getLocalBestBlock() && bestCorrectBlock.getNetBestBlockInfo() == null) {
doit = true;
BlockInfo blockInfo = BEST_HEIGHT_FROM_NET.request(-1);
bestCorrectBlock.setNetBestBlockInfo(blockInfo);
break;
}
startHeight = bestCorrectBlock.getLocalBestBlock().getHeader().getHeight() + 1;
long interval = TimeService.currentTimeMillis() - bestCorrectBlock.getLocalBestBlock().getHeader().getTime();
if (interval < (PocConsensusConstant.BLOCK_TIME_INTERVAL_SECOND * 2000)) {
doit = false;
break;
}
if (null == bestCorrectBlock.getNetBestBlockInfo()) {
bestCorrectBlock.setNetBestBlockInfo(BEST_HEIGHT_FROM_NET.request(0));
}
if (null == bestCorrectBlock.getNetBestBlockInfo()) {
break;
}
if (bestCorrectBlock.getNetBestBlockInfo().getBestHeight() > bestCorrectBlock.getLocalBestBlock().getHeader().getHeight()) {
doit = true;
break;
}
} while (false);
if (null == bestCorrectBlock.getNetBestBlockInfo()) {
return;
}
if (doit) {
downloadBlocks(bestCorrectBlock.getNetBestBlockInfo().getNodeIdList(), startHeight, bestCorrectBlock.getNetBestBlockInfo().getBestHeight());
} else {
this.status = MaintenanceStatus.SUCCESS;
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void checkIt() {
int maxSize = 0;
BlockHeaderChain longestChain = null;
StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:");
for (BlockHeaderChain chain : chainList) {
str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight());
int listSize = chain.size();
if (maxSize < listSize) {
maxSize = listSize;
longestChain = chain;
} else if (maxSize == listSize) {
HeaderDigest hd = chain.getLastHd();
HeaderDigest hd_long = longestChain.getLastHd();
if (hd.getTime() < hd_long.getTime()) {
longestChain = chain;
}
}
}
if (tempIndex % 10 == 0) {
BlockLog.info(str.toString());
tempIndex++;
}
if (this.approvingChain != null && !this.approvingChain.getId().equals(longestChain.getId())) {
BlockService blockService = NulsContext.getServiceBean(BlockService.class);
for (int i=approvingChain.size()-1;i>=0;i--) {
HeaderDigest hd = approvingChain.getHeaderDigestList().get(i);
try {
blockService.rollbackBlock(hd.getHash());
} catch (NulsException e) {
Log.error(e);
}
}
for(int i=0;i<longestChain.getHeaderDigestList().size();i++){
HeaderDigest hd = longestChain.getHeaderDigestList().get(i);
blockService.approvalBlock(hd.getHash());
}
}
this.approvingChain = longestChain;
Set<String> rightHashSet = new HashSet<>();
Set<String> removeHashSet = new HashSet<>();
for (int i = chainList.size() - 1; i >= 0; i--) {
BlockHeaderChain chain = chainList.get(i);
if (chain.size() < (maxSize - 6)) {
removeHashSet.addAll(chain.getHashSet());
this.chainList.remove(chain);
} else {
rightHashSet.addAll(chain.getHashSet());
}
}
for (String hash : removeHashSet) {
if (!rightHashSet.contains(hash)) {
confirmingBlockCacheManager.removeBlock(hash);
}
}
}
|
#vulnerable code
private void checkIt() {
int maxSize = 0;
BlockHeaderChain longestChain = null;
StringBuilder str = new StringBuilder("++++++++++++++++++++++++chain info:");
for (BlockHeaderChain chain : chainList) {
str.append("+++++++++++\nchain:start-" + chain.getHeaderDigestList().get(0).getHeight() + ", end-" + chain.getHeaderDigestList().get(chain.size() - 1).getHeight());
int listSize = chain.size();
if (maxSize < listSize) {
maxSize = listSize;
longestChain = chain;
} else if (maxSize == listSize) {
HeaderDigest hd = chain.getLastHd();
HeaderDigest hd_long = longestChain.getLastHd();
if (hd.getTime() < hd_long.getTime()) {
longestChain = chain;
}
}
}
if (tempIndex % 10 == 0) {
BlockLog.info(str.toString());
tempIndex++;
}
if (this.approvingChain != null || !this.approvingChain.getId().equals(longestChain.getId())) {
BlockService blockService = NulsContext.getServiceBean(BlockService.class);
for (int i=approvingChain.size()-1;i>=0;i--) {
HeaderDigest hd = approvingChain.getHeaderDigestList().get(i);
try {
blockService.rollbackBlock(hd.getHash());
} catch (NulsException e) {
Log.error(e);
}
}
for(int i=0;i<longestChain.getHeaderDigestList().size();i++){
HeaderDigest hd = longestChain.getHeaderDigestList().get(i);
blockService.approvalBlock(hd.getHash());
}
}
this.approvingChain = longestChain;
Set<String> rightHashSet = new HashSet<>();
Set<String> removeHashSet = new HashSet<>();
for (int i = chainList.size() - 1; i >= 0; i--) {
BlockHeaderChain chain = chainList.get(i);
if (chain.size() < (maxSize - 6)) {
removeHashSet.addAll(chain.getHashSet());
this.chainList.remove(chain);
} else {
rightHashSet.addAll(chain.getHashSet());
}
}
for (String hash : removeHashSet) {
if (!rightHashSet.contains(hash)) {
confirmingBlockCacheManager.removeBlock(hash);
}
}
}
#location 33
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void recalc(Block bestBlock) {
this.currentRound = null;
this.calc(bestBlock);
}
|
#vulnerable code
private void recalc(Block bestBlock) {
this.currentRound = null;
this.previousRound = null;
this.calc(bestBlock);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public LockNulsTransaction createLockNulsTx(CoinTransferData transferData, String password, String remark) throws Exception {
LockNulsTransaction tx = new LockNulsTransaction(transferData, password);
if (StringUtils.isNotBlank(remark)) {
tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING));
}
tx.setHash(NulsDigestData.calcDigestData(tx.serialize()));
AccountService accountService = getAccountService();
if (transferData.getFrom().isEmpty()) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
Account account = accountService.getAccount(transferData.getFrom().get(0));
tx.setSign(accountService.signData(tx.getHash(), account, password));
return tx;
}
|
#vulnerable code
public LockNulsTransaction createLockNulsTx(CoinTransferData transferData, String password, String remark) throws Exception {
LockNulsTransaction tx = new LockNulsTransaction(transferData, password);
if (StringUtils.isNotBlank(remark)) {
tx.setRemark(remark.getBytes(NulsContext.DEFAULT_ENCODING));
}
tx.setHash(NulsDigestData.calcDigestData(tx.serialize()));
tx.setSign(getAccountService().signData(tx.getHash(), password));
return tx;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public PocMeetingRound getCurrentRound() {
List<Account> accountList = accountService.getAccountList();
currentRound.calcLocalPacker(accountList);
return currentRound;
}
|
#vulnerable code
public PocMeetingRound getCurrentRound() {
if (needReSet) {
return null;
}
List<Account> accountList = accountService.getAccountList();
currentRound.calcLocalPacker(accountList);
return currentRound;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public ValidateResult verifyCoinData(AbstractCoinTransaction tx, List<Transaction> txList) {
if (txList == null || txList.isEmpty()) {
//It's all an orphan that can go here
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
UtxoData data = (UtxoData) tx.getCoinData();
Map<String, UtxoOutput> outputMap = getAllOutputMap(txList);
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = ledgerCacheService.getUtxo(input.getKey());
if (output == null && tx.getStatus() == TxStatusEnum.UNCONFIRM) {
output = outputMap.get(input.getKey());
if (null == output) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
} else if (output == null) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND);
}
if (tx.getStatus() == TxStatusEnum.UNCONFIRM) {
if (tx.getType() == TransactionConstant.TX_TYPE_STOP_AGENT) {
if (output.getStatus() != OutPutStatusEnum.UTXO_CONSENSUS_LOCK) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
} else if (output.getStatus() != OutPutStatusEnum.UTXO_UNSPENT) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
}
// else if (tx.getStatus() == TxStatusEnum.AGREED) {
// if (!output.isSpend()) {
// return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
// }
// }
byte[] owner = output.getOwner();
P2PKHScriptSig p2PKHScriptSig = null;
try {
p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig());
} catch (NulsException e) {
return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR);
}
byte[] user = p2PKHScriptSig.getSignerHash160();
if (!Arrays.equals(owner, user)) {
return ValidateResult.getFailedResult(ErrorCode.INVALID_INPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
|
#vulnerable code
@Override
public ValidateResult verifyCoinData(AbstractCoinTransaction tx, List<Transaction> txList) {
if (txList == null || txList.isEmpty()) {
//It's all an orphan that can go here
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
UtxoData data = (UtxoData) tx.getCoinData();
Map<String, UtxoOutput> outputMap = getAllOutputMap(txList);
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = ledgerCacheService.getUtxo(input.getKey());
if (output == null && tx.getStatus() == TxStatusEnum.UNCONFIRM) {
output = outputMap.get(input.getKey());
if (null == output) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
} else if (output == null) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND);
}
if (tx.getStatus() == TxStatusEnum.UNCONFIRM) {
if (tx.getType() == TransactionConstant.TX_TYPE_STOP_AGENT) {
if (output.getStatus() != OutPutStatusEnum.UTXO_CONSENSUS_LOCK) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
} else if (!output.isUsable()) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
}
}
// else if (tx.getStatus() == TxStatusEnum.AGREED) {
// if (!output.isSpend()) {
// return ValidateResult.getFailedResult(ErrorCode.UTXO_STATUS_CHANGE);
// }
// }
byte[] owner = output.getOwner();
P2PKHScriptSig p2PKHScriptSig = null;
try {
p2PKHScriptSig = P2PKHScriptSig.createFromBytes(tx.getScriptSig());
} catch (NulsException e) {
return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR);
}
byte[] user = p2PKHScriptSig.getSignerHash160();
if (!Arrays.equals(owner, user)) {
return ValidateResult.getFailedResult(ErrorCode.INVALID_INPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void sendMessage(AbstractNetworkMessage networkMessage) throws IOException {
if (this.getStatus() == Peer.CLOSE) {
return;
}
if (writeTarget == null) {
throw new NotYetConnectedException();
}
if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) {
throw new NotYetConnectedException();
}
lock.lock();
try {
byte[] data = networkMessage.serialize();
NulsMessage message = new NulsMessage(network.packetMagic(), NulsMessageHeader.NETWORK_MESSAGE, data);
this.writeTarget.write(message.serialize());
} finally {
lock.unlock();
}
}
|
#vulnerable code
public void sendMessage(AbstractNetworkMessage networkMessage) throws IOException {
if (this.getStatus() == Peer.CLOSE) {
return;
}
if (writeTarget == null) {
throw new NotYetConnectedException();
}
if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) {
throw new NotYetConnectedException();
}
byte[] data = networkMessage.serialize();
NulsMessage message = new NulsMessage(network.packetMagic(), NulsMessageHeader.NETWORK_MESSAGE, data);
sendMessage(message);
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ValidateResult validate(BlockHeader header, List<Transaction> txs) {
if (header.getHeight() == 0) {
return ValidateResult.getSuccessResult();
}
BlockRoundData
roundData = new BlockRoundData(header.getExtend());
Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex());
if (null == preBlock) {
//When a block does not exist, it is temporarily validated.
return ValidateResult.getSuccessResult();
}
calc(preBlock);
BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend());
PocMeetingRound localThisRoundData = this.currentRound;
PocMeetingRound localPreRoundData;
if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) {
localPreRoundData = localThisRoundData;
} else {
localPreRoundData = localThisRoundData.getPreRound();
if (localPreRoundData == null) {
localPreRoundData = calcCurrentRound(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData);
}
}
if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound());
if (null == member) {
return ValidateResult.getFailedResult("Cannot find the packing member!");
}
if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) {
ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!");
vr.setObject(header);
vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
return vr;
}
if (null == txs) {
return ValidateResult.getSuccessResult();
}
YellowPunishTransaction yellowPunishTx = null;
for (Transaction tx : txs) {
if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
if (yellowPunishTx == null) {
yellowPunishTx = (YellowPunishTransaction) tx;
} else {
return ValidateResult.getFailedResult("There are too many yellow punish transactions!");
}
}
}
//when the blocks are continuous
boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1);
isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() &&
roundData.getPackingIndexOfRound() == 1);
//Too long intervals will not be penalized.
boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1);
if (longTimeAgo && yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
}
if (isContinuous) {
if (yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
} else {
return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!");
}
} else {
if (null == yellowPunishTx) {
return ValidateResult.getFailedResult("It should be a yellow punish tx here!");
}
if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) {
return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!");
}
int interval = 0;
if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) {
interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1;
} else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) {
interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1;
}
if (interval != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval);
} else {
long roundIndex = preRoundData.getRoundIndex();
int indexOfRound = 0;
if (preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount()) {
roundIndex++;
indexOfRound = 1;
} else {
indexOfRound = preRoundData.getPackingIndexOfRound() + 1;
}
List<String> addressList = new ArrayList<>();
while (true) {
PocMeetingRound tempRound;
if (roundIndex == roundData.getRoundIndex()) {
tempRound = localThisRoundData;
} else if (roundIndex == (roundData.getRoundIndex() - 1)) {
tempRound = localPreRoundData;
} else {
break;
}
if (tempRound == null) {
break;
}
if (tempRound.getIndex() > roundData.getRoundIndex()) {
break;
}
if (tempRound.getIndex() == roundData.getRoundIndex() && indexOfRound >= roundData.getPackingIndexOfRound()) {
break;
}
if (indexOfRound >= tempRound.getMemberCount()) {
roundIndex++;
indexOfRound = 1;
continue;
}
PocMeetingMember smo;
try {
smo = tempRound.getMember(indexOfRound);
if (null == member) {
break;
}
} catch (Exception e) {
break;
}
indexOfRound++;
addressList.add(smo.getAgentAddress());
}
if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!");
}
for (String address : addressList) {
boolean contains = false;
for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) {
if (addressObj.getBase58().equals(address)) {
contains = true;
break;
}
}
if (!contains) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address");
}
}
}
}
return checkCoinBaseTx(header, txs, roundData, localThisRoundData);
}
|
#vulnerable code
public ValidateResult validate(BlockHeader header, List<Transaction> txs) {
if (header.getHeight() == 0) {
return ValidateResult.getSuccessResult();
}
BlockRoundData
roundData = new BlockRoundData(header.getExtend());
Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex());
if (null == preBlock) {
//When a block does not exist, it is temporarily validated.
return ValidateResult.getSuccessResult();
}
calc(preBlock);
BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend());
PocMeetingRound localThisRoundData = this.currentRound;
PocMeetingRound localPreRoundData;
if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) {
localPreRoundData = localThisRoundData;
} else {
localPreRoundData = localThisRoundData.getPreRound();
if (localPreRoundData == null) {
localPreRoundData = calcCurrentRound(preBlock.getHeader(),preBlock.getHeader().getHeight(),preRoundData);
}
}
if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound());
if (null == member) {
return ValidateResult.getFailedResult("Cannot find the packing member!");
}
if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) {
ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!");
vr.setObject(header);
vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
return vr;
}
if (null == txs) {
return ValidateResult.getSuccessResult();
}
YellowPunishTransaction yellowPunishTx = null;
for (Transaction tx : txs) {
if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
if (yellowPunishTx == null) {
yellowPunishTx = (YellowPunishTransaction) tx;
} else {
return ValidateResult.getFailedResult("There are too many yellow punish transactions!");
}
}
}
//when the blocks are continuous
boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1);
isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() &&
roundData.getPackingIndexOfRound() == 1);
//Too long intervals will not be penalized.
boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1);
if (longTimeAgo && yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
}
if (isContinuous) {
if (yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
} else {
return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!");
}
} else {
if (null == yellowPunishTx) {
return ValidateResult.getFailedResult("It should be a yellow punish tx here!");
}
if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) {
return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!");
}
int interval = 0;
if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) {
interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1;
} else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) {
interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1;
}
if (interval != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval);
} else {
long roundIndex = preRoundData.getRoundIndex();
long indexOfRound = preRoundData.getPackingIndexOfRound() + 1;
List<String> addressList = new ArrayList<>();
while (true) {
PocMeetingRound round = getRoundData(roundIndex);
if (null == round) {
break;
}
if (roundIndex == roundData.getRoundIndex() && roundData.getPackingIndexOfRound() <= indexOfRound) {
break;
}
if (round.getMemberCount() < indexOfRound) {
roundIndex++;
indexOfRound = 1;
continue;
}
PocMeetingMember meetingMember = round.getMember(interval);
if (null == meetingMember) {
return ValidateResult.getFailedResult("the round data has error!");
}
addressList.add(meetingMember.getAgentAddress());
indexOfRound++;
}
if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!");
}
for (String address : addressList) {
boolean contains = false;
for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) {
if (addressObj.getBase58().equals(address)) {
contains = true;
break;
}
}
if (!contains) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address");
}
}
}
}
return checkCoinBaseTx(header, txs, roundData, localThisRoundData);
}
#location 90
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public NetworkEventResult process(BaseEvent networkEvent, Node node) {
NodeEvent event = (NodeEvent) networkEvent;
Map<String, Node> outNodes = networkService.getNodeGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP).getNodes();
boolean exist = false;
for (Node newNode : event.getEventBody().getNodes()) {
exist = false;
for (Node outNode : outNodes.values()) {
if (outNode.getIp().equals(node.getIp())) {
exist = true;
break;
}
}
if (!exist) {
newNode.setType(Node.OUT);
newNode.setStatus(Node.WAIT);
getNetworkService().addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, newNode);
}
}
return null;
}
|
#vulnerable code
@Override
public NetworkEventResult process(BaseEvent networkEvent, Node node) {
NodeEvent event = (NodeEvent) networkEvent;
// String key = event.getHeader().getEventType() + "-" + node.getIp();
// if (cacheService.existEvent(key)) {
// networkService.removeNode(node.getId());
// return null;
// }
// cacheService.putEvent(key, event, false);
for (Node newNode : event.getEventBody().getNodes()) {
newNode.setType(Node.OUT);
newNode.setStatus(Node.WAIT);
getNetworkService().addNodeToGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP, newNode);
}
return null;
}
#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 onEvent(BlockHeaderEvent event, String fromId) {
if (DistributedBlockInfoRequestUtils.getInstance().addBlockHeader(fromId, event.getEventBody())) {
return;
}
BlockHeader header = event.getEventBody();
blockCacheManager.cacheBlockHeader(header);
}
|
#vulnerable code
@Override
public void onEvent(BlockHeaderEvent event, String fromId) {
if (DistributedBlockInfoRequestUtils.getInstance().addBlockHeader(fromId, event.getEventBody())) {
return;
}
BlockHeader header = event.getEventBody();
ValidateResult result = header.verify();
if (result.isFailed()) {
networkService.removeNode(fromId);
return;
}
blockCacheManager.cacheBlockHeader(header);
GetSmallBlockEvent getSmallBlockEvent = new GetSmallBlockEvent();
BasicTypeData<Long> data = new BasicTypeData<>(header.getHeight());
getSmallBlockEvent.setEventBody(data);
eventBroadcaster.sendToNode(getSmallBlockEvent, fromId);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
// Log.debug(" ---------------------- server channelRead ------------------------- " + nodeId);
Node node = networkService.getNode(nodeId);
if (node != null && node.isAlive()) {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
buf.release();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
// getNetworkService().receiveMessage(buffer, node);
}
}
|
#vulnerable code
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
// Log.debug(" ---------------------- server channelRead ------------------------- " + nodeId);
Node node = getNetworkService().getNode(nodeId);
if (node != null && node.isAlive()) {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
buf.release();
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
// getNetworkService().receiveMessage(buffer, node);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Result<Integer> saveUnconfirmedTransaction(Transaction tx) {
saveLock.lock();
try {
ValidateResult result1 = tx.verify();
if (result1.isFailed()) {
return result1;
}
result1 = this.ledgerService.verifyCoinData(tx, this.getAllUnconfirmedTransaction().getData());
if (result1.isFailed()) {
return result1;
}
return saveTransaction(tx, TransactionInfo.UNCONFIRMED);
} finally {
saveLock.unlock();
}
}
|
#vulnerable code
@Override
public Result<Integer> saveUnconfirmedTransaction(Transaction tx) {
return saveTransaction(tx, TransactionInfo.UNCONFIRMED);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void onEvent(TransactionEvent event, String fromId) {
Transaction tx = event.getEventBody();
if (null == tx) {
return;
}
ValidateResult result = tx.verify();
if (result.isFailed()) {
if (result.getLevel() == SeverityLevelEnum.NORMAL_FOUL) {
networkService.blackNode(fromId,NodePo.YELLOW);
} else if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
networkService.blackNode(fromId, NodePo.BLACK);
}
}
cacheManager.putTx(tx);
}
|
#vulnerable code
@Override
public void onEvent(TransactionEvent event, String fromId) {
Transaction tx = event.getEventBody();
if (null == tx) {
return;
}
ValidateResult result = tx.verify();
if (result.isFailed()) {
if (result.getLevel() == SeverityLevelEnum.NORMAL_FOUL) {
networkService.removeNode(fromId);
} else if (result.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
networkService.removeNode(fromId);
}
}
cacheManager.putTx(tx);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Account getAccount(String address) {
AssertUtil.canNotEmpty(address, "");
Account account = accountCacheService.getAccountByAddress(address);
return account;
}
|
#vulnerable code
@Override
public Account getAccount(String address) {
AssertUtil.canNotEmpty(address, "");
Account account = accountCacheService.getAccountByAddress(address);
if (account == null) {
AliasPo aliasPo = aliasDataService.getByAddress(address);
if (aliasPo != null) {
try {
account = new Account();
account.setAddress(Address.fromHashs(address));
account.setAlias(aliasPo.getAlias());
} catch (NulsException e) {
e.printStackTrace();
}
}
}
return account;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public BlockInfo request(long start, long end, long split) {
lock.lock();
this.startTime = TimeService.currentTimeMillis();
requesting = true;
hashesMap.clear();
calcMap.clear();
this.start = start;
this.end = end;
this.split = split;
GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split);
nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false);
if (nodeIdList.isEmpty()) {
Log.error("get best height from net faild!");
lock.unlock();
return null;
}
return this.getBlockInfo();
}
|
#vulnerable code
public BlockInfo request(long start, long end, long split) {
lock.lock();
this.startTime = TimeService.currentTimeMillis();
requesting = true;
hashesMap.clear();
calcMap.clear();
this.start = start;
this.end = end;
this.split = split;
GetBlocksHashRequest event = new GetBlocksHashRequest(start, end, split);
nodeIdList = this.eventBroadcaster.broadcastAndCache(event, false);
if (nodeIdList.isEmpty()) {
Log.error("get best height from net faild!");
lock.unlock();
throw new NulsRuntimeException(ErrorCode.NET_MESSAGE_ERROR, "broadcast faild!");
}
return this.getBlockInfo();
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
boolean verifyPublicKey(){
//verify the public-KEY-hashes are the same
byte[] publicKey = scriptSig.getPublicKey();
byte[] reedmAccount = Utils.sha256hash160(Utils.sha256hash160(publicKey));
if(Arrays.equals(reedmAccount,script.getPublicKeyDigest().getDigestBytes())){
return true;
}
return false;
}
|
#vulnerable code
boolean verifyPublicKey(){
//verify the public-KEY-hashes are the same
byte[] publicKey = scriptSig.getPublicKey();
NulsDigestData digestData = NulsDigestData.calcDigestData(publicKey,NulsDigestData.DIGEST_ALG_SHA160);
if(Arrays.equals(digestData.getDigestBytes(),script.getPublicKeyDigest().getDigestBytes())){
return true;
}
return false;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void init() {
try {
NetworkContext.setNetworkConfig(ConfigLoader.loadProperties(NetworkConstant.NETWORK_PROPERTIES));
} catch (IOException e) {
Log.error(e);
throw new NulsRuntimeException(ErrorCode.IO_ERROR);
}
this.registerService(NetworkServiceImpl.class);
networkService = NulsContext.getServiceBean(NetworkService.class);
this.registerEvent();
}
|
#vulnerable code
@Override
public void init() {
try {
NetworkContext.setNetworkConfig(ConfigLoader.loadProperties(NetworkConstant.NETWORK_PROPERTIES));
} catch (IOException e) {
Log.error(e);
throw new NulsRuntimeException(ErrorCode.IO_ERROR);
}
this.registerService(NetworkServiceImpl.class);
networkService = NulsContext.getServiceBean(NetworkService.class);
networkService.init();
this.registerEvent();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean containsSpend(String key) {
for (int i = 0; i < unSpends.size(); i++) {
UtxoOutput output = unSpends.get(i);
if (key.equals(output.getKey())) {
return true;
}
}
return false;
}
|
#vulnerable code
public boolean containsSpend(String key) {
for (int i = 0; i < unSpends.size(); i++) {
UtxoOutput output = unSpends.get(i);
if (key.equals(output.getTxHash().getDigestHex() + "-" + output.getIndex())) {
return true;
}
}
return false;
}
#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 channelRegistered(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
// Log.info("---------------------- server channelRegistered ------------------------- " + nodeId);
String remoteIP = channel.remoteAddress().getHostString();
NodeGroup outGroup = networkService.getNodeGroup(NetworkConstant.NETWORK_NODE_OUT_GROUP);
for (Node node : outGroup.getNodes().values()) {
if (node.getIp().equals(remoteIP)) {
String localIP = InetAddress.getLocalHost().getHostAddress();
boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP);
if (!isLocalServer) {
ctx.channel().close();
return;
} else {
getNetworkService().removeNode(node.getId());
}
}
}
// if has a node with same ip, and it's a out node, close this channel
// if More than 10 in nodes of the same IP, close this channel
int count = 0;
for (Node n : getNetworkService().getNodes().values()) {
if (n.getIp().equals(remoteIP)) {
count++;
if (count >= Node.SAME_IP_MAX_COUNT) {
ctx.channel().close();
return;
}
//
// if (n.getType() == Node.OUT && n.getStatus() == Node.HANDSHAKE) {
// ctx.channel().close();
// return;
// } else {
// count++;
// if (count == 10) {
// ctx.channel().close();
// return;
// }
// }
}
}
}
|
#vulnerable code
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
String nodeId = IpUtil.getNodeId(channel.remoteAddress());
Log.debug("---------------------- server channelRegistered ------------------------- " + nodeId);
String remoteIP = channel.remoteAddress().getHostString();
// String remoteId = IpUtil.getNodeId(channel.remoteAddress());
// Node node = getNetworkService().getNode(remoteId);
// if (node != null) {
// if (node.getStatus() == Node.CONNECT) {
// ctx.channel().close();
// return;
// }
// //When nodes try to connect to each other but not connected, select one of the smaller IP addresses as the server
//// if (node.getType() == Node.OUT) {
//// String localIP = InetAddress.getLocalHost().getHostAddress();
//// boolean isLocalServer = IpUtil.judgeIsLocalServer(localIP, remoteIP);
////
//// if (!isLocalServer) {
//// ctx.channel().close();
//// return;
//// } else {
//// getNetworkService().removeNode(remoteId);
//// }
//// }
// } else {
// if has a node with same ip, and it's a out node, close this channel
// if More than 10 in nodes of the same IP, close this channel
int count = 0;
for (Node n : getNetworkService().getNodes().values()) {
if (n.getIp().equals(remoteIP)) {
count++;
if (count >= Node.SAME_IP_MAX_COUNT) {
ctx.channel().close();
return;
}
//
// if (n.getType() == Node.OUT && n.getStatus() == Node.HANDSHAKE) {
// ctx.channel().close();
// return;
// } else {
// count++;
// if (count == 10) {
// ctx.channel().close();
// return;
// }
// }
}
}
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void approve(CoinData coinData, Transaction tx) throws NulsException {
//spent the transaction specified output in the cache when the newly received transaction is approved.
UtxoData utxoData = (UtxoData) coinData;
for (UtxoInput input : utxoData.getInputs()) {
input.setTxHash(tx.getHash());
}
for (UtxoOutput output : utxoData.getOutputs()) {
output.setTxHash(tx.getHash());
}
List<UtxoOutput> unSpends = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
try {
lock.lock();
//update inputs referenced utxo status
for (int i = 0; i < utxoData.getInputs().size(); i++) {
UtxoInput input = utxoData.getInputs().get(i);
UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey());
if (null == unSpend) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!");
}
if (!unSpend.isUsable()) {
throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE);
}
if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) {
unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) {
unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND);
}
unSpends.add(unSpend);
addressSet.add(unSpend.getAddress());
}
//cache new utxo ,it is unConfirm
approveProcessOutput(utxoData.getOutputs(), tx, addressSet);
} catch (Exception e) {
//rollback
for (UtxoOutput output : unSpends) {
if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) {
ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) {
ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND);
}
}
// remove cache new utxo
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
ledgerCacheService.removeUtxo(output.getKey());
}
throw e;
} finally {
lock.unlock();
//calc balance
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, false);
}
}
}
|
#vulnerable code
@Override
public void approve(CoinData coinData, Transaction tx) throws NulsException {
//spent the transaction specified output in the cache when the newly received transaction is approved.
UtxoData utxoData = (UtxoData) coinData;
for (UtxoInput input : utxoData.getInputs()) {
input.setTxHash(tx.getHash());
}
for (UtxoOutput output : utxoData.getOutputs()) {
output.setTxHash(tx.getHash());
}
List<UtxoOutput> unSpends = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
try {
//update inputs referenced utxo status
for (int i = 0; i < utxoData.getInputs().size(); i++) {
UtxoInput input = utxoData.getInputs().get(i);
UtxoOutput unSpend = ledgerCacheService.getUtxo(input.getKey());
if (null == unSpend) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "the output is not exist!");
}
if (!unSpend.isUsable()) {
throw new NulsRuntimeException(ErrorCode.UTXO_UNUSABLE);
}
if (OutPutStatusEnum.UTXO_CONFIRM_UNSPEND == unSpend.getStatus()) {
unSpend.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == unSpend.getStatus()) {
unSpend.setStatus(OutPutStatusEnum.UTXO_UNCONFIRM_SPEND);
}
unSpends.add(unSpend);
addressSet.add(unSpend.getAddress());
}
//cache new utxo ,it is unConfirm
approveProcessOutput(utxoData.getOutputs(), tx, addressSet);
} catch (Exception e) {
//rollback
for (UtxoOutput output : unSpends) {
if (OutPutStatusEnum.UTXO_CONFIRM_SPEND.equals(output.getStatus())) {
ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_CONFIRM_UNSPEND, OutPutStatusEnum.UTXO_CONFIRM_SPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND.equals(output.getStatus())) {
ledgerCacheService.updateUtxoStatus(output.getKey(), OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND, OutPutStatusEnum.UTXO_UNCONFIRM_SPEND);
}
}
// remove cache new utxo
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
ledgerCacheService.removeUtxo(output.getKey());
}
throw e;
} finally {
//calc balance
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, false);
}
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ValidateResult validate(BlockHeader header, List<Transaction> txs) {
if (header.getHeight() == 0) {
return ValidateResult.getSuccessResult();
}
BlockRoundData
roundData = new BlockRoundData(header.getExtend());
Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex());
if (null == preBlock) {
//When a block does not exist, it is temporarily validated.
return ValidateResult.getSuccessResult();
}
BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend());
PocMeetingRound localThisRoundData = calcCurrentRound(header, header.getHeight(), roundData);
PocMeetingRound localPreRoundData = calcCurrentRound(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData);
if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound());
if (null == member) {
return ValidateResult.getFailedResult("Cannot find the packing member!");
}
if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) {
ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!");
vr.setObject(header);
vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
return vr;
}
if (null == txs) {
return ValidateResult.getSuccessResult();
}
YellowPunishTransaction yellowPunishTx = null;
for (Transaction tx : txs) {
if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
if (yellowPunishTx == null) {
yellowPunishTx = (YellowPunishTransaction) tx;
} else {
return ValidateResult.getFailedResult("There are too many yellow punish transactions!");
}
}
}
//when the blocks are continuous
boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1);
isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() &&
roundData.getPackingIndexOfRound() == 1);
//Too long intervals will not be penalized.
boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1);
if (longTimeAgo && yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
}
if (isContinuous) {
if (yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
} else {
return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!");
}
} else {
if (null == yellowPunishTx) {
return ValidateResult.getFailedResult("It should be a yellow punish tx here!");
}
if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) {
return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!");
}
int interval = 0;
if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) {
interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1;
} else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) {
interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1;
}
if (interval != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval);
} else {
long roundIndex = preRoundData.getRoundIndex();
int indexOfRound = 0;
if (preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount()) {
roundIndex++;
indexOfRound = 1;
} else {
indexOfRound = preRoundData.getPackingIndexOfRound() + 1;
}
List<String> addressList = new ArrayList<>();
while (true) {
PocMeetingRound tempRound;
if (roundIndex == roundData.getRoundIndex()) {
tempRound = localThisRoundData;
} else if (roundIndex == (roundData.getRoundIndex() - 1)) {
tempRound = localPreRoundData;
} else {
break;
}
if (tempRound == null) {
break;
}
if (tempRound.getIndex() > roundData.getRoundIndex()) {
break;
}
if (tempRound.getIndex() == roundData.getRoundIndex() && indexOfRound >= roundData.getPackingIndexOfRound()) {
break;
}
if (indexOfRound >= tempRound.getMemberCount()) {
roundIndex++;
indexOfRound = 1;
continue;
}
PocMeetingMember smo;
try {
smo = tempRound.getMember(indexOfRound);
if (null == member) {
break;
}
} catch (Exception e) {
break;
}
indexOfRound++;
addressList.add(smo.getAgentAddress());
}
if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!");
}
for (String address : addressList) {
boolean contains = false;
for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) {
if (addressObj.getBase58().equals(address)) {
contains = true;
break;
}
}
if (!contains) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address");
}
}
}
}
return checkCoinBaseTx(header, txs, roundData, localThisRoundData);
}
|
#vulnerable code
public ValidateResult validate(BlockHeader header, List<Transaction> txs) {
if (header.getHeight() == 0) {
return ValidateResult.getSuccessResult();
}
BlockRoundData
roundData = new BlockRoundData(header.getExtend());
Block preBlock = getBlockService().getBlock(header.getPreHash().getDigestHex());
if (null == preBlock) {
//When a block does not exist, it is temporarily validated.
return ValidateResult.getSuccessResult();
}
calc(preBlock);
BlockRoundData preRoundData = new BlockRoundData(preBlock.getHeader().getExtend());
PocMeetingRound localThisRoundData = this.currentRound;
PocMeetingRound localPreRoundData;
if (preRoundData.getRoundIndex() == roundData.getRoundIndex()) {
localPreRoundData = localThisRoundData;
} else {
localPreRoundData = localThisRoundData.getPreRound();
if (localPreRoundData == null) {
localPreRoundData = calcCurrentRound(preBlock.getHeader(), preBlock.getHeader().getHeight(), preRoundData);
}
}
if (roundData.getConsensusMemberCount() != localThisRoundData.getMemberCount()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
if (roundData.getRoundIndex() == (localPreRoundData.getIndex() + 1) && roundData.getRoundStartTime() != localPreRoundData.getEndTime()) {
return ValidateResult.getFailedResult("The round data of the block is wrong!");
}
PocMeetingMember member = localThisRoundData.getMember(roundData.getPackingIndexOfRound());
if (null == member) {
return ValidateResult.getFailedResult("Cannot find the packing member!");
}
if (member.getIndexOfRound() != roundData.getPackingIndexOfRound() || !member.getPackingAddress().equals(header.getPackingAddress())) {
ValidateResult vr = ValidateResult.getFailedResult("It's not the address's turn to pack the block!");
vr.setObject(header);
vr.setLevel(SeverityLevelEnum.FLAGRANT_FOUL);
return vr;
}
if (null == txs) {
return ValidateResult.getSuccessResult();
}
YellowPunishTransaction yellowPunishTx = null;
for (Transaction tx : txs) {
if (tx.getType() == TransactionConstant.TX_TYPE_YELLOW_PUNISH) {
if (yellowPunishTx == null) {
yellowPunishTx = (YellowPunishTransaction) tx;
} else {
return ValidateResult.getFailedResult("There are too many yellow punish transactions!");
}
}
}
//when the blocks are continuous
boolean isContinuous = preRoundData.getRoundIndex() == roundData.getRoundIndex() && preRoundData.getPackingIndexOfRound() == (roundData.getPackingIndexOfRound() - 1);
isContinuous = isContinuous || (preRoundData.getRoundIndex() == (roundData.getRoundIndex() - 1) && preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount() &&
roundData.getPackingIndexOfRound() == 1);
//Too long intervals will not be penalized.
boolean longTimeAgo = preRoundData.getRoundIndex() < (roundData.getRoundIndex() - 1);
if (longTimeAgo && yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
}
if (isContinuous) {
if (yellowPunishTx == null) {
return ValidateResult.getSuccessResult();
} else {
return ValidateResult.getFailedResult("the block shouldn't has any yellow punish tx!");
}
} else {
if (null == yellowPunishTx) {
return ValidateResult.getFailedResult("It should be a yellow punish tx here!");
}
if (yellowPunishTx.getTxData().getHeight() != header.getHeight()) {
return ValidateResult.getFailedResult("The yellow punish tx's height is wrong!");
}
int interval = 0;
if (roundData.getRoundIndex() == preRoundData.getRoundIndex()) {
interval = roundData.getPackingIndexOfRound() - preRoundData.getPackingIndexOfRound() - 1;
} else if ((roundData.getRoundIndex() - 1) == preRoundData.getRoundIndex()) {
interval = preRoundData.getConsensusMemberCount() - preRoundData.getPackingIndexOfRound() + roundData.getPackingIndexOfRound() - 1;
}
if (interval != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The count of YellowPunishTx is wrong,it should be " + interval);
} else {
long roundIndex = preRoundData.getRoundIndex();
int indexOfRound = 0;
if (preRoundData.getPackingIndexOfRound() == preRoundData.getConsensusMemberCount()) {
roundIndex++;
indexOfRound = 1;
} else {
indexOfRound = preRoundData.getPackingIndexOfRound() + 1;
}
List<String> addressList = new ArrayList<>();
while (true) {
PocMeetingRound tempRound;
if (roundIndex == roundData.getRoundIndex()) {
tempRound = localThisRoundData;
} else if (roundIndex == (roundData.getRoundIndex() - 1)) {
tempRound = localPreRoundData;
} else {
break;
}
if (tempRound == null) {
break;
}
if (tempRound.getIndex() > roundData.getRoundIndex()) {
break;
}
if (tempRound.getIndex() == roundData.getRoundIndex() && indexOfRound >= roundData.getPackingIndexOfRound()) {
break;
}
if (indexOfRound >= tempRound.getMemberCount()) {
roundIndex++;
indexOfRound = 1;
continue;
}
PocMeetingMember smo;
try {
smo = tempRound.getMember(indexOfRound);
if (null == member) {
break;
}
} catch (Exception e) {
break;
}
indexOfRound++;
addressList.add(smo.getAgentAddress());
}
if (addressList.size() != yellowPunishTx.getTxData().getAddressList().size()) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!address list size is wrong!");
}
for (String address : addressList) {
boolean contains = false;
for (Address addressObj : yellowPunishTx.getTxData().getAddressList()) {
if (addressObj.getBase58().equals(address)) {
contains = true;
break;
}
}
if (!contains) {
return ValidateResult.getFailedResult("The block has wrong yellow punish Tx!It has wrong address");
}
}
}
}
return checkCoinBaseTx(header, txs, roundData, localThisRoundData);
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static String getPwd() {
return getPwd(null);
}
|
#vulnerable code
public static String getPwd(){
System.out.print("Please enter the password, if the account has no password directly return.\nEnter your password:");
ConsoleReader reader = null;
try {
reader = new ConsoleReader();
String pwd = reader.readLine('*');
return pwd;
} catch (IOException e) {
return null;
}finally {
try {
if(!reader.delete()){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.