instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
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
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 34
#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
@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("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 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
@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
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("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
@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 6
#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
@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
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 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 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
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 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
@Override
public void parse(NulsByteBuffer buffer) throws NulsException {
magicNumber = buffer.readUint32();
severPort = buffer.readUint16();
port = severPort;
ip = buffer.readString();
this.groupSet = ConcurrentHashMap.newKeySet();
}
|
#vulnerable code
@Override
public void parse(NulsByteBuffer buffer) throws NulsException {
magicNumber = (int) buffer.readVarInt();
severPort = (int) buffer.readVarInt();
port = severPort;
ip = new String(buffer.readByLengthByte());
this.groupSet = ConcurrentHashMap.newKeySet();
}
#location 6
#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
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
@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 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
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 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 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 35
#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 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 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 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 int getChainId(String chainName) {
return CHAIN_ID_MAP.get(chainName);
}
|
#vulnerable code
public int getChainId(String chainName) {
return chain_id_map.get(chainName);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void processMessage(NulsMessage message) throws IOException {
//todo
if (true) {
try {
System.out.println("------receive message:" + Hex.encode(message.serialize()));
} catch (IOException e) {
e.printStackTrace();
}
if (this.status != Peer.HANDSHAKE) {
return;
}
if (checkBroadcastExist(message.getData())) {
return;
}
eventProcessorService.dispatch(message.getData(), this.getHash());
} else {
byte[] networkHeader = new byte[NetworkDataHeader.NETWORK_HEADER_SIZE];
System.arraycopy(message.getData(), 0, networkHeader, 0, NetworkDataHeader.NETWORK_HEADER_SIZE);
NetworkDataHeader header;
BaseNetworkData networkMessage;
try {
header = new NetworkDataHeader(new NulsByteBuffer(networkHeader));
networkMessage = BaseNetworkData.transfer(header.getType(), message.getData());
} catch (NulsException e) {
Log.error("networkMessage transfer error:", e);
this.destroy();
return;
}
if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) {
return;
}
asynExecute(networkMessage);
}
}
|
#vulnerable code
public void processMessage(NulsMessage message) throws IOException {
if (message.getHeader().getHeadType() == NulsMessageHeader.EVENT_MESSAGE) {
try {
System.out.println("------receive message:" + Hex.encode(message.serialize()));
} catch (IOException e) {
e.printStackTrace();
}
if (this.status != Peer.HANDSHAKE) {
return;
}
if (checkBroadcastExist(message.getData())) {
return;
}
eventProcessorService.dispatch(message.getData(), this.getHash());
} else {
byte[] networkHeader = new byte[NetworkDataHeader.NETWORK_HEADER_SIZE];
System.arraycopy(message.getData(), 0, networkHeader, 0, NetworkDataHeader.NETWORK_HEADER_SIZE);
NetworkDataHeader header;
BaseNetworkData networkMessage;
try {
header = new NetworkDataHeader(new NulsByteBuffer(networkHeader));
networkMessage = BaseNetworkData.transfer(header.getType(), message.getData());
} catch (NulsException e) {
Log.error("networkMessage transfer error:", e);
this.destroy();
return;
}
if (this.status != Peer.HANDSHAKE && !isHandShakeMessage(networkMessage)) {
return;
}
asynExecute(networkMessage);
}
}
#location 31
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean downloadedBlock(String nodeId, Block block) {
System.out.println("downloaded:" + block.getHeader().getHeight());
NodeDownloadingStatus status = nodeStatusMap.get(nodeId);
if (null == status) {
return false;
}
if (!status.containsHeight(block.getHeader().getHeight())) {
return false;
}
blockMap.put(block.getHeader().getHeight(), block);
status.downloaded(block.getHeader().getHeight());
status.setUpdateTime(System.currentTimeMillis());
if (status.finished()) {
this.queueService.offer(queueId, nodeId);
}
verify();
return true;
}
|
#vulnerable code
public boolean downloadedBlock(String nodeId, Block block) {
System.out.println("downloaded:"+block.getHeader().getHeight());
NodeDownloadingStatus status = nodeStatusMap.get(nodeId);
if (null == status) {
return false;
}
if (!status.containsHeight(block.getHeader().getHeight())) {
return false;
}
blockMap.put(block.getHeader().getHeight(), block);
status.downloaded(block.getHeader().getHeight());
status.setUpdateTime(System.currentTimeMillis());
if (status.finished()) {
this.queueService.offer(queueId, nodeId);
}
verify();
return true;
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@DbSession
public boolean saveBlock(Block block) throws IOException {
BlockLog.debug("save block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
BlockHeader bestBlockHeader = getLocalBestBlockHeader();
if((bestBlockHeader == null && block.getHeader().getHeight() != 0L) || (bestBlockHeader != null && !bestBlockHeader.getHash().equals(block.getHeader().getPreHash()))) {
throw new NulsRuntimeException(ErrorCode.FAILED, "save blcok error , prehash is error , height: " + block.getHeader().getHeight() + " , hash: " + block.getHeader().getHash());
}
List<Transaction> commitedList = new ArrayList<>();
for (int x = 0; x < block.getHeader().getTxCount(); x++) {
Transaction tx = block.getTxs().get(x);
tx.setIndex(x);
tx.setBlockHeight(block.getHeader().getHeight());
try {
tx.verifyWithException();
commitedList.add(tx);
ledgerService.commitTx(tx, block);
} catch (Exception e) {
Log.error(e);
this.rollback(commitedList);
throw new NulsRuntimeException(e);
}
}
ledgerService.saveTxList(block.getTxs());
blockStorageService.save(block);
List<Transaction> localTxList = null;
try {
localTxList = this.ledgerService.getWaitingTxList();
} catch (Exception e) {
Log.error(e);
}
if (null != localTxList && !localTxList.isEmpty()) {
for (Transaction tx : localTxList) {
try {
ValidateResult result = ledgerService.conflictDetectTx(tx, block.getTxs());
if (result.isFailed()) {
ledgerService.deleteLocalTx(tx.getHash().getDigestHex());
}
} catch (NulsException e) {
Log.error(e);
}
}
}
return true;
}
|
#vulnerable code
@Override
@DbSession
public boolean saveBlock(Block block) throws IOException {
BlockLog.debug("save block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
BlockHeader bestBlockHeader = getLocalBestBlockHeader();
if(!bestBlockHeader.getHash().equals(block.getHeader().getPreHash())) {
throw new NulsRuntimeException(ErrorCode.FAILED, "save blcok error , prehash is error , height: " + block.getHeader().getHeight() + " , hash: " + block.getHeader().getHash());
}
List<Transaction> commitedList = new ArrayList<>();
for (int x = 0; x < block.getHeader().getTxCount(); x++) {
Transaction tx = block.getTxs().get(x);
tx.setIndex(x);
tx.setBlockHeight(block.getHeader().getHeight());
try {
tx.verifyWithException();
commitedList.add(tx);
ledgerService.commitTx(tx, block);
} catch (Exception e) {
Log.error(e);
this.rollback(commitedList);
throw new NulsRuntimeException(e);
}
}
ledgerService.saveTxList(block.getTxs());
blockStorageService.save(block);
List<Transaction> localTxList = null;
try {
localTxList = this.ledgerService.getWaitingTxList();
} catch (Exception e) {
Log.error(e);
}
if (null != localTxList && !localTxList.isEmpty()) {
for (Transaction tx : localTxList) {
try {
ValidateResult result = ledgerService.conflictDetectTx(tx, block.getTxs());
if (result.isFailed()) {
ledgerService.deleteLocalTx(tx.getHash().getDigestHex());
}
} catch (NulsException e) {
Log.error(e);
}
}
}
return true;
}
#location 7
#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 {
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 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult vResult = block.verify();
if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) {
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
}
|
#vulnerable code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || vResult.isFailed()) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData redPunishData = vResult.getObject();
ConsensusMeetingRunner.putPunishData(redPunishData);
}
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
}
#location 32
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public PocMeetingRound getCurrentRound() {
return currentRound;
}
|
#vulnerable code
public PocMeetingRound getCurrentRound() {
Block currentBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData currentRoundData = new BlockRoundData(currentBlock.getHeader().getExtend());
PocMeetingRound round = ROUND_MAP.get(currentRoundData.getRoundIndex());
if (null == round) {
round = resetCurrentMeetingRound();
}
return round;
}
#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 NetworkEventResult process(BaseEvent networkEvent, Node node) {
VersionEvent event = (VersionEvent) networkEvent;
// String key = event.getHeader().getEventType() + "-" + node.getId();
// if (cacheService.existEvent(key)) {
// Log.info("----------VersionEventHandler cacheService existEvent--------");
// getNetworkService().removeNode(node.getId());
// return null;
// }
// cacheService.putEvent(key, event, true);
if (event.getBestBlockHeight() < 0) {
throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR);
}
node.setVersionMessage(event);
if (!node.isHandShake()) {
node.setStatus(Node.HANDSHAKE);
node.setPort(event.getExternalPort());
node.setLastTime(TimeService.currentTimeMillis());
getNodeDao().saveChange(NodeTransferTool.toPojo(node));
}
return null;
}
|
#vulnerable code
@Override
public NetworkEventResult process(BaseEvent networkEvent, Node node) {
VersionEvent event = (VersionEvent) networkEvent;
String key = event.getHeader().getEventType() + "-" + node.getId();
if (cacheService.existEvent(key)) {
Log.info("----------VersionEventHandler cacheService existEvent--------");
getNetworkService().removeNode(node.getId());
return null;
}
cacheService.putEvent(key, event, true);
if (event.getBestBlockHeight() < 0) {
throw new NetworkMessageException(ErrorCode.NET_MESSAGE_ERROR);
}
node.setVersionMessage(event);
if (!node.isHandShake()) {
node.setStatus(Node.HANDSHAKE);
node.setPort(event.getExternalPort());
node.setLastTime(TimeService.currentTimeMillis());
getNodeDao().saveChange(NodeTransferTool.toPojo(node));
}
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean saveLocalTx(Transaction tx) throws IOException {
try {
ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList());
if (validateResult.isFailed()) {
throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage());
}
} catch (Exception e) {
Log.error(e);
throw new NulsRuntimeException(e);
}
TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx);
localPo.setTxStatus(TransactionLocalPo.UNCONFIRM);
localTxDao.save(localPo);
ledgerCacheService.putLocalTx(tx);
// save relation
if (tx instanceof AbstractCoinTransaction) {
AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx;
UtxoData utxoData = (UtxoData) abstractTx.getCoinData();
if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) {
UtxoInput input = utxoData.getInputs().get(0);
UtxoOutput output = input.getFrom();
TxAccountRelationPo relationPo = new TxAccountRelationPo();
relationPo.setTxHash(tx.getHash().getDigestHex());
relationPo.setAddress(output.getAddress());
relationDataService.save(relationPo);
}
}
return true;
}
|
#vulnerable code
@Override
public boolean saveLocalTx(Transaction tx) throws IOException {
try {
ValidateResult validateResult = this.conflictDetectTx(tx, this.getWaitingTxList());
if (validateResult.isFailed()) {
throw new NulsRuntimeException(validateResult.getErrorCode(), validateResult.getMessage());
}
} catch (Exception e) {
Log.error(e);
throw new NulsRuntimeException(e);
}
TransactionLocalPo localPo = UtxoTransferTool.toLocalTransactionPojo(tx);
localPo.setTxStatus(TransactionLocalPo.UNCONFIRM);
localTxDao.save(localPo);
// save relation
if (tx instanceof AbstractCoinTransaction) {
AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx;
UtxoData utxoData = (UtxoData) abstractTx.getCoinData();
if (utxoData.getInputs() != null && !utxoData.getInputs().isEmpty()) {
UtxoInput input = utxoData.getInputs().get(0);
UtxoOutput output = input.getFrom();
TxAccountRelationPo relationPo = new TxAccountRelationPo();
relationPo.setTxHash(tx.getHash().getDigestHex());
relationPo.setAddress(output.getAddress());
relationDataService.save(relationPo);
}
}
// if (tx instanceof AbstractCoinTransaction) {
// AbstractCoinTransaction abstractTx = (AbstractCoinTransaction) tx;
// UtxoData utxoData = (UtxoData) abstractTx.getCoinData();
//
// for (UtxoOutput output : utxoData.getOutputs()) {
// if (output.isUsable() && NulsContext.LOCAL_ADDRESS_LIST.contains(output.getAddress())) {
// output.setTxHash(tx.getHash());
// ledgerCacheService.putUtxo(output.getKey(), output, false);
// }
// }
// }
return true;
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<Transaction> getTxList(Block block, List<NulsDigestData> txHashList) {
List<Transaction> txList = new ArrayList<>();
for (Transaction tx : block.getTxs()) {
if (txHashList.contains(tx.getHash())) {
txList.add(tx);
}
}
if (txList.size() != txHashList.size()) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
return txList;
}
|
#vulnerable code
private List<Transaction> getTxList(Block block, List<NulsDigestData> txHashList) {
List<Transaction> txList = new ArrayList<>();
Map<String, Integer> allTxMap = new HashMap<>();
for (int i = 0; i < block.getHeader().getTxCount(); i++) {
Transaction tx = block.getTxs().get(i);
allTxMap.put(tx.getHash().getDigestHex(), i);
}
for (NulsDigestData hash : txHashList) {
txList.add(block.getTxs().get(allTxMap.get(hash.getDigestHex())));
}
if (txList.size() != txHashList.size()) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
return txList;
}
#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 onMessage(GetBlockRequest message, Node fromNode) {
BlockSendThread.offer(message, fromNode);
}
|
#vulnerable code
@Override
public void onMessage(GetBlockRequest message, Node fromNode) throws NulsException {
GetBlockDataParam param = message.getMsgBody();
if (param.getSize() > MAX_SIZE) {
return;
}
if (param.getSize() == 1) {
Block block = null;
Result<Block> result = this.blockService.getBlock(param.getStartHash());
if (result.isFailed()) {
sendNotFound(param.getStartHash(), fromNode);
return;
}
block = result.getData();
sendBlock(block, fromNode);
return;
}
Block chainStartBlock = null;
Result<Block> blockResult = this.blockService.getBlock(param.getStartHash());
if (blockResult.isFailed()) {
sendNotFound(param.getStartHash(), fromNode);
return;
} else {
chainStartBlock = blockResult.getData();
}
Block chainEndBlock = null;
blockResult = this.blockService.getBlock(param.getEndHash());
if (blockResult.isFailed()) {
sendNotFound(param.getEndHash(), fromNode);
return;
} else {
chainEndBlock = blockResult.getData();
}
if (chainEndBlock.getHeader().getHeight() < chainStartBlock.getHeader().getHeight()) {
return;
}
long end = param.getStart() + param.getSize() - 1;
if (chainStartBlock.getHeader().getHeight() > param.getStart() || chainEndBlock.getHeader().getHeight() < end) {
sendNotFound(param.getStartHash(), fromNode);
return;
}
Block block = chainEndBlock;
while (true) {
this.sendBlock(block, fromNode);
if (block.getHeader().getHash().equals(chainStartBlock.getHeader().getHash())) {
break;
}
if (block.getHeader().getPreHash().equals(chainStartBlock.getHeader().getHash())) {
block = chainStartBlock;
continue;
}
block = blockService.getBlock(block.getHeader().getPreHash()).getData();
}
}
#location 46
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1);
BlockRoundData preRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, preRoundData.getRoundEndTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
|
#vulnerable code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getPreRoundFirstBlock(i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult vResult = block.verify();
if (vResult.isFailed()&&vResult.getErrorCode()!=ErrorCode.ORPHAN_BLOCK&&vResult.getErrorCode()!=ErrorCode.ORPHAN_TX) {
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
}
|
#vulnerable code
public void requestTxGroup(NulsDigestData blockHash, String nodeId) {
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam data = new GetTxGroupParam();
data.setBlockHash(blockHash);
List<NulsDigestData> txHashList = new ArrayList<>();
SmallBlock smb = temporaryCacheManager.getSmallBlock(blockHash.getDigestHex());
for (NulsDigestData txHash : smb.getTxHashList()) {
boolean exist = txCacheManager.txExist(txHash);
if (!exist) {
txHashList.add(txHash);
}
}
if (txHashList.isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(smb.getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : smb.getTxHashList()) {
Transaction tx = txCacheManager.getTx(txHash);
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || vResult.isFailed()) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData redPunishData = vResult.getObject();
ConsensusMeetingRunner.putPunishData(redPunishData);
}
return;
}
blockManager.addBlock(block, false,nodeId);
AssembledBlockNotice notice = new AssembledBlockNotice();
notice.setEventBody(header);
eventBroadcaster.publishToLocal(notice);
return;
}
data.setTxHashList(txHashList);
request.setEventBody(data);
tgRequest.put(blockHash.getDigestHex(), System.currentTimeMillis());
Integer value = tgRequestCount.get(blockHash.getDigestHex());
if (null == value) {
value = 0;
}
tgRequestCount.put(blockHash.getDigestHex(), 1 + value);
if (StringUtils.isBlank(nodeId)) {
eventBroadcaster.broadcastAndCache(request, false);
} else {
eventBroadcaster.sendToNode(request, nodeId);
}
}
#location 34
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
List<UtxoOutputPo> spendPoList = new ArrayList<>();
List<TxAccountRelationPo> txRelations = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
lock.lock();
try {
processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet);
List<UtxoOutputPo> outputPoList = new ArrayList<>();
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
output = ledgerCacheService.getUtxo(output.getKey());
if (output == null) {
throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND);
}
if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) {
Log.error("-----------------------------------save() output status is" + output.getStatus().name());
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo");
}
if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
}
UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output);
outputPoList.add(outputPo);
addressSet.add(Address.fromHashs(output.getAddress()).getBase58());
}
for (String address : addressSet) {
TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address);
txRelations.add(relationPo);
}
outputDataService.updateStatus(spendPoList);
inputDataService.save(inputPoList);
outputDataService.save(outputPoList);
relationDataService.save(txRelations);
afterSaveDatabase(spends, utxoData, tx);
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, true);
}
} catch (Exception e) {
//rollback
// Log.warn(e.getMessage(), e);
// for (UtxoOutput output : utxoData.getOutputs()) {
// ledgerCacheService.removeUtxo(output.getKey());
// }
// for (UtxoOutput spend : spends) {
// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT);
// }
throw e;
} finally {
lock.unlock();
}
}
|
#vulnerable code
@Override
@DbSession
public void save(CoinData coinData, Transaction tx) throws NulsException {
UtxoData utxoData = (UtxoData) coinData;
List<UtxoInputPo> inputPoList = new ArrayList<>();
List<UtxoOutput> spends = new ArrayList<>();
List<UtxoOutputPo> spendPoList = new ArrayList<>();
List<TxAccountRelationPo> txRelations = new ArrayList<>();
Set<String> addressSet = new HashSet<>();
try {
processDataInput(utxoData, inputPoList, spends, spendPoList, addressSet);
List<UtxoOutputPo> outputPoList = new ArrayList<>();
for (int i = 0; i < utxoData.getOutputs().size(); i++) {
UtxoOutput output = utxoData.getOutputs().get(i);
output = ledgerCacheService.getUtxo(output.getKey());
if (output == null) {
throw new NulsRuntimeException(ErrorCode.DATA_NOT_FOUND);
}
if (output.isConfirm() || OutPutStatusEnum.UTXO_SPENT == output.getStatus()) {
Log.error("-----------------------------------save() output status is" + output.getStatus().name());
throw new NulsRuntimeException(ErrorCode.DATA_ERROR, "use a not legal utxo");
}
if (OutPutStatusEnum.UTXO_UNCONFIRM_CONSENSUS_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_CONSENSUS_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_TIME_LOCK == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_TIME_LOCK);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_UNSPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_UNSPEND);
} else if (OutPutStatusEnum.UTXO_UNCONFIRM_SPEND == output.getStatus()) {
output.setStatus(OutPutStatusEnum.UTXO_CONFIRM_SPEND);
}
UtxoOutputPo outputPo = UtxoTransferTool.toOutputPojo(output);
outputPoList.add(outputPo);
addressSet.add(Address.fromHashs(output.getAddress()).getBase58());
}
for (String address : addressSet) {
TxAccountRelationPo relationPo = new TxAccountRelationPo(tx.getHash().getDigestHex(), address);
txRelations.add(relationPo);
}
outputDataService.updateStatus(spendPoList);
inputDataService.save(inputPoList);
outputDataService.save(outputPoList);
relationDataService.save(txRelations);
afterSaveDatabase(spends, utxoData, tx);
for (String address : addressSet) {
UtxoTransactionTool.getInstance().calcBalance(address, true);
}
} catch (Exception e) {
//rollback
// Log.warn(e.getMessage(), e);
// for (UtxoOutput output : utxoData.getOutputs()) {
// ledgerCacheService.removeUtxo(output.getKey());
// }
// for (UtxoOutput spend : spends) {
// ledgerCacheService.updateUtxoStatus(spend.getKey(), UtxoOutput.UTXO_CONFIRM_LOCK, UtxoOutput.UTXO_SPENT);
// }
throw e;
}
}
#location 13
#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(SmallBlockEvent event, String fromId) {
ValidateResult result = event.getEventBody().verify();
if (result.isFailed()) {
return;
}
temporaryCacheManager.cacheSmallBlock(event.getEventBody());
downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex());
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam param = new GetTxGroupParam();
param.setBlockHash(event.getEventBody().getBlockHash());
for (NulsDigestData hash : event.getEventBody().getTxHashList()) {
if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) {
param.addHash(hash);
}
}
if (param.getTxHashList().isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : event.getEventBody().getTxHashList()) {
Transaction tx = receivedTxCacheManager.getTx(txHash);
if (null == tx) {
tx = orphanTxCacheManager.getTx(txHash);
}
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData data = vResult.getObject();
ConsensusMeetingRunner.putPunishData(data);
networkService.blackNode(fromId, NodePo.BLACK);
} else {
networkService.removeNode(fromId, NodePo.YELLOW);
}
return;
}
blockManager.addBlock(block, false, fromId);
downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex());
BlockHeaderEvent headerEvent = new BlockHeaderEvent();
headerEvent.setEventBody(header);
eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId);
return;
}
request.setEventBody(param);
this.eventBroadcaster.sendToNode(request, fromId);
}
|
#vulnerable code
@Override
public void onEvent(SmallBlockEvent event, String fromId) {
ValidateResult result = event.getEventBody().verify();
if (result.isFailed()) {
return;
}
temporaryCacheManager.cacheSmallBlock(event.getEventBody());
downloadDataUtils.removeSmallBlock(event.getEventBody().getBlockHash().getDigestHex());
GetTxGroupRequest request = new GetTxGroupRequest();
GetTxGroupParam param = new GetTxGroupParam();
param.setBlockHash(event.getEventBody().getBlockHash());
for (NulsDigestData hash : event.getEventBody().getTxHashList()) {
if (!receivedTxCacheManager.txExist(hash) && !orphanTxCacheManager.txExist(hash)) {
param.addHash(hash);
}
}
if (param.getTxHashList().isEmpty()) {
BlockHeader header = temporaryCacheManager.getBlockHeader(event.getEventBody().getBlockHash().getDigestHex());
if (null == header) {
return;
}
Block block = new Block();
block.setHeader(header);
List<Transaction> txs = new ArrayList<>();
for (NulsDigestData txHash : event.getEventBody().getTxHashList()) {
Transaction tx = receivedTxCacheManager.getTx(txHash);
if (null == tx) {
tx = orphanTxCacheManager.getTx(txHash);
}
if (null == tx) {
throw new NulsRuntimeException(ErrorCode.DATA_ERROR);
}
txs.add(tx);
}
block.setTxs(txs);
ValidateResult<RedPunishData> vResult = block.verify();
if (null == vResult || (vResult.isFailed() && vResult.getErrorCode() != ErrorCode.ORPHAN_TX)) {
if (vResult.getLevel() == SeverityLevelEnum.FLAGRANT_FOUL) {
RedPunishData data = vResult.getObject();
ConsensusMeetingRunner.putPunishData(data);
networkService.blackNode(fromId, NodePo.BLACK);
} else {
networkService.removeNode(fromId, NodePo.YELLOW);
}
return;
}
blockManager.addBlock(block, false, fromId);
downloadDataUtils.removeTxGroup(block.getHeader().getHash().getDigestHex());
BlockHeaderEvent headerEvent = new BlockHeaderEvent();
headerEvent.setEventBody(header);
eventBroadcaster.broadcastHashAndCacheAysn(headerEvent, false, fromId);
return;
}
request.setEventBody(param);
this.eventBroadcaster.sendToNode(request, fromId);
}
#location 39
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Result saveLocalTx(Transaction tx) {
if (tx == null) {
return Result.getFailed(KernelErrorCode.NULL_PARAMETER);
}
byte[] txHashBytes = new byte[0];
try {
txHashBytes = tx.getHash().serialize();
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
CoinData coinData = tx.getCoinData();
if (coinData != null) {
// delete - from
List<Coin> froms = coinData.getFrom();
Set<byte[]> fromsSet = new HashSet<>();
for (Coin from : froms) {
byte[] fromSource = from.getOwner();
byte[] utxoFromSource = new byte[tx.getHash().size()];
byte[] fromIndex = new byte[fromSource.length - utxoFromSource.length];
System.arraycopy(fromSource, 0, utxoFromSource, 0, tx.getHash().size());
System.arraycopy(fromSource, tx.getHash().size(), fromIndex, 0, fromIndex.length);
Transaction sourceTx = null;
try {
sourceTx = ledgerService.getTx(NulsDigestData.fromDigestHex(Hex.encode(fromSource)));
} catch (Exception e) {
throw new NulsRuntimeException(e);
}
if (sourceTx == null) {
return Result.getFailed(AccountLedgerErrorCode.SOURCE_TX_NOT_EXSITS);
}
byte[] address = sourceTx.getCoinData().getTo().get((int) new VarInt(fromIndex, 0).value).getOwner();
fromsSet.add(org.spongycastle.util.Arrays.concatenate(address, from.getOwner()));
}
storageService.batchDeleteUTXO(fromsSet);
// save utxo - to
List<Coin> tos = coinData.getTo();
byte[] indexBytes;
Map<byte[], byte[]> toMap = new HashMap<>();
for (int i = 0, length = tos.size(); i < length; i++) {
try {
byte[] outKey = org.spongycastle.util.Arrays.concatenate(tos.get(i).getOwner(), tx.getHash().serialize(), new VarInt(i).encode());
toMap.put(outKey, tos.get(i).serialize());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
}
storageService.batchSaveUTXO(toMap);
}
return Result.getSuccess();
}
|
#vulnerable code
public Result saveLocalTx(Transaction tx) {
if (tx == null) {
return Result.getFailed(KernelErrorCode.NULL_PARAMETER);
}
byte[] txHashBytes = new byte[0];
try {
txHashBytes = tx.getHash().serialize();
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
CoinData coinData = tx.getCoinData();
if (coinData != null) {
// delete - from
List<Coin> froms = coinData.getFrom();
Set<byte[]> fromsSet = new HashSet<>();
for (Coin from : froms) {
byte[] fromSource = from.getOwner();
byte[] utxoFromSource = new byte[tx.getHash().size()];
byte[] fromIndex = new byte[fromSource.length - utxoFromSource.length];
System.arraycopy(fromSource, 0, utxoFromSource, 0, tx.getHash().size());
System.arraycopy(fromSource, tx.getHash().size(), fromIndex, 0, fromIndex.length);
Transaction sourceTx = null;
try {
sourceTx = ledgerService.getTx(NulsDigestData.fromDigestHex(Hex.encode(fromSource)));
if (sourceTx == null) {
sourceTx = getUnconfirmedTransaction(NulsDigestData.fromDigestHex(Hex.encode(fromSource))).getData();
}
} catch (Exception e) {
throw new NulsRuntimeException(e);
}
if(sourceTx == null){
return Result.getFailed();
}
byte[] address = sourceTx.getCoinData().getTo().get((int) new VarInt(fromIndex, 0).value).getOwner();
fromsSet.add(org.spongycastle.util.Arrays.concatenate(address, from.getOwner()));
}
storageService.batchDeleteUTXO(fromsSet);
// save utxo - to
List<Coin> tos = coinData.getTo();
byte[] indexBytes;
Map<byte[], byte[]> toMap = new HashMap<>();
for (int i = 0, length = tos.size(); i < length; i++) {
try {
byte[] outKey = org.spongycastle.util.Arrays.concatenate(tos.get(i).getOwner(), tx.getHash().serialize(), new VarInt(i).encode());
toMap.put(outKey, tos.get(i).serialize());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
}
storageService.batchSaveUTXO(toMap);
}
return Result.getSuccess();
}
#location 46
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void start() {
List<Peer> peers = discovery.getLocalPeers(10);
if (peers.isEmpty()) {
peers = getSeedPeers();
}
for (Peer peer : peers) {
peer.setType(Peer.OUT);
addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer);
}
boolean isConsensus = NulsContext.MODULES_CONFIG.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false);
if (isConsensus) {
network.maxOutCount(network.maxOutCount() * 5);
network.maxInCount(network.maxInCount() * 5);
}
System.out.println("-----------peerManager start");
//start heart beat thread
ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery);
}
|
#vulnerable code
public void start() {
List<Peer> peers = discovery.getLocalPeers(10);
if (peers.isEmpty()) {
peers = getSeedPeers();
}
for (Peer peer : peers) {
peer.setType(Peer.OUT);
addPeerToGroup(NetworkConstant.NETWORK_PEER_OUT_GROUP, peer);
}
boolean isConsensus = ConfigLoader.getCfgValue(PocConsensusConstant.CFG_CONSENSUS_SECTION, PocConsensusConstant.PROPERTY_DELEGATE_PEER, false);
if (isConsensus) {
network.maxOutCount(network.maxOutCount() * 5);
network.maxInCount(network.maxInCount() * 5);
}
System.out.println("-----------peerManager start");
//start heart beat thread
ThreadManager.createSingleThreadAndRun(NulsConstant.MODULE_ID_NETWORK, "peerDiscovery", this.discovery);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected Block createBlock() {
// new a block header
BlockHeader blockHeader = new BlockHeader();
blockHeader.setHeight(0);
blockHeader.setPreHash(NulsDigestData.calcDigestData("00000000000".getBytes()));
blockHeader.setTime(1L);
blockHeader.setTxCount(1);
blockHeader.setMerkleHash(NulsDigestData.calcDigestData(new byte[20]));
// add a round data
BlockRoundData roundData = new BlockRoundData();
roundData.setConsensusMemberCount(1);
roundData.setPackingIndexOfRound(1);
roundData.setRoundIndex(1);
roundData.setRoundStartTime(1L);
try {
blockHeader.setExtend(roundData.serialize());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
// new a block of height 0
Block block = new Block();
block.setHeader(blockHeader);
List<Transaction> txs = new ArrayList<>();
block.setTxs(txs);
Transaction tx = new TestTransaction();
txs.add(tx);
List<NulsDigestData> txHashList = block.getTxHashList();
blockHeader.setMerkleHash(NulsDigestData.calcMerkleDigestData(txHashList));
NulsSignData signData = signDigest(blockHeader.getHash().getDigestBytes(), ecKey);
P2PKHScriptSig sig = new P2PKHScriptSig();
sig.setSignData(signData);
sig.setPublicKey(ecKey.getPubKey());
blockHeader.setScriptSig(sig);
return block;
}
|
#vulnerable code
protected Block createBlock() {
// new a block header
BlockHeader blockHeader = new BlockHeader();
blockHeader.setHeight(0);
blockHeader.setPreHash(NulsDigestData.calcDigestData("00000000000".getBytes()));
blockHeader.setTime(1L);
blockHeader.setTxCount(1);
blockHeader.setMerkleHash(NulsDigestData.calcDigestData(new byte[20]));
// add a round data
BlockRoundData roundData = new BlockRoundData();
roundData.setConsensusMemberCount(1);
roundData.setPackingIndexOfRound(1);
roundData.setRoundIndex(1);
roundData.setRoundStartTime(1L);
try {
blockHeader.setExtend(roundData.serialize());
} catch (IOException e) {
throw new NulsRuntimeException(e);
}
// new a block of height 0
Block block = new Block();
block.setHeader(blockHeader);
List<Transaction> txs = new ArrayList<>();
block.setTxs(txs);
Transaction tx = new TestTransaction();
txs.add(tx);
List<NulsDigestData> txHashList = block.getTxHashList();
blockHeader.setMerkleHash(NulsDigestData.calcMerkleDigestData(txHashList));
NulsSignData signData = null;
try {
signData = accountService.signData(blockHeader.getHash().getDigestBytes(), ecKey);
} catch (NulsException e) {
e.printStackTrace();
}
P2PKHScriptSig sig = new P2PKHScriptSig();
sig.setSignData(signData);
sig.setPublicKey(ecKey.getPubKey());
blockHeader.setScriptSig(sig);
return block;
}
#location 38
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Transaction getTx(NulsDigestData hash) {
TransactionPo po = txDao.get(hash.getDigestHex());
if (null != po) {
try {
Transaction tx = UtxoTransferTool.toTransaction(po);
return tx;
} catch (Exception e) {
Log.error(e);
}
}
return null;
}
|
#vulnerable code
@Override
public Transaction getTx(NulsDigestData hash) {
TransactionLocalPo localPo = localTxDao.get(hash.getDigestHex());
if (localPo != null) {
try {
Transaction tx = UtxoTransferTool.toTransaction(localPo);
return tx;
} catch (Exception e) {
Log.error(e);
}
}
TransactionPo po = txDao.get(hash.getDigestHex());
if (null == po) {
return null;
}
try {
Transaction tx = UtxoTransferTool.toTransaction(po);
return tx;
} catch (Exception e) {
Log.error(e);
}
return null;
}
#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 Result<Account> importAccount(String prikey, String password) {
if (!ECKey.isValidPrivteHex(prikey)) {
return Result.getFailed(AccountErrorCode.PARAMETER_ERROR);
}
Account account;
try {
account = AccountTool.createAccount(prikey);
} catch (NulsException e) {
return Result.getFailed(AccountErrorCode.FAILED);
}
if (StringUtils.validPassword(password)) {
try {
account.encrypt(password);
} catch (NulsException e) {
Log.error(e);
}
}
AccountPo po = new AccountPo(account);
accountStorageService.saveAccount(po);
LOCAL_ADDRESS_LIST.add(account.getAddress().toString());
accountLedgerService.importAccountLedger(account.getAddress().getBase58());
return Result.getSuccess().setData(account);
}
|
#vulnerable code
@Override
public Result<Account> importAccount(String prikey, String password) {
if (!ECKey.isValidPrivteHex(prikey)) {
return Result.getFailed(AccountErrorCode.PARAMETER_ERROR);
}
Account account;
try {
account = AccountTool.createAccount(prikey);
} catch (NulsException e) {
return Result.getFailed(AccountErrorCode.FAILED);
}
Account accountDB = getAccountByAddress(account.getAddress().toString());
if (null != accountDB) {
return Result.getFailed(AccountErrorCode.ACCOUNT_EXIST);
}
if (StringUtils.validPassword(password)) {
try {
account.encrypt(password);
} catch (NulsException e) {
Log.error(e);
}
}
AccountPo po = new AccountPo(account);
accountStorageService.saveAccount(po);
LOCAL_ADDRESS_LIST.add(account.getAddress().toString());
accountLedgerService.importAccountLedger(account.getAddress().getBase58());
return Result.getSuccess().setData(account);
}
#location 18
#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 = ledgerCacheService.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 = 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);
}
}
#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() {
Log.debug("Start");
notificationController = new NotificationController();
EventBusService eventBusService = NulsContext.getServiceBean(EventBusService.class);
eventBusService.subscribeEvent(BaseEvent.class,notificationController.getNulsEventHandler());
notificationController.setListenPort(port);
notificationController.start();
}
|
#vulnerable code
@Override
public void start() {
Log.debug("Start");
notificationController = new NotificationController();
EventBusService eventBusService = NulsContext.getServiceBean(EventBusService.class);
eventBusService.subscribeEvent(BaseEvent.class,notificationController.getNulsEventHandler());
notificationController.setListenPort(port);
notificationController.start();
NulsEventHandler handler = new NulsEventHandler();
String subscribeId = NulsContext.getServiceBean(EventBusService.class).subscribeEvent(BaseEvent.class,handler);
Log.debug("subscribe base event:"+subscribeId);
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean isLocalHasSeed(List<Account> accountList) {
for (Account account : accountList) {
for (String seedAddress : csManager.getSeedNodeList()) {
if (seedAddress.equals(account.getAddress().getBase58())) {
return true;
}
}
}
return false;
}
|
#vulnerable code
public boolean isLocalHasSeed(List<Account> accountList) {
for (Account account : accountList) {
for (PocMeetingMember seed : this.getDefaultSeedList()) {
if (seed.getAgentAddress().equals(account.getAddress().getBase58())) {
return true;
}
}
}
return false;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void start() {
try {
ChannelFuture future = boot.connect(node.getIp(), node.getSeverPort()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
} else {
Log.info("Client connect to host error: " + future.cause() + ", remove node: " + node.getId());
getNetworkService().removeNode(node.getId());
}
}
});
future.channel().closeFuture().sync();
} catch (Exception e) {
//maybe time out or refused or something
if (socketChannel != null) {
socketChannel.close();
}
Log.error("Client start exception:" + e.getMessage() + ", remove node: " + node.getId());
getNetworkService().removeNode(node.getId());
}
}
|
#vulnerable code
public void start() {
try {
ChannelFuture future = boot.connect(node.getIp(), node.getSeverPort()).sync();
if (future.isSuccess()) {
socketChannel = (SocketChannel) future.channel();
} else {
System.out.println("---------------client start !success remove node-----------------" + node.getId());
getNetworkService().removeNode(node.getId());
}
future.channel().closeFuture().sync();
} catch (Exception e) {
Log.debug("-------------NettyClient start error: " + e.getMessage());
//maybe time out or refused or something
if (socketChannel != null) {
socketChannel.close();
}
System.out.println("---------------client start exception remove node-----------------" + node.getId());
getNetworkService().removeNode(node.getId());
}
}
#location 8
#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 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void handleKey(SelectionKey key) {
ConnectionHandler handler = (ConnectionHandler) key.attachment();
try {
if (!key.isValid()) {
// Key has been cancelled, make sure the socket gets closed
System.out.println("--------------------destory 1" + handler.peer.getIp());
handler.peer.destroy();
return;
}
if (key.isReadable()) {
// Do a socket read and invoke the connection's receiveBytes message
int len = handler.channel.read(handler.readBuffer);
if (len == 0) {
// Was probably waiting on a write
return;
} else if (len == -1) {
// Socket was closed
key.cancel();
System.out.println("--------------------destory 2" + handler.peer.getIp());
handler.peer.destroy();
return;
}
// "flip" the buffer - setting the limit to the current position and setting position to 0
handler.readBuffer.flip();
handler.peer.receiveMessage(handler.readBuffer);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position)
handler.readBuffer.compact();
}
if (key.isWritable()) {
handler.writeBytes();
}
} catch (Exception e) {
// This can happen eg if the channel closes while the thread is about to get killed
// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
e.printStackTrace();
Throwable t = e;
Log.warn("Error handling SelectionKey: {}", t.getMessage() != null ? t.getMessage() : t.getClass().getName());
System.out.println("--------------------destory 3" + handler.peer.getIp());
handler.peer.destroy();
}
}
|
#vulnerable code
public static void handleKey(SelectionKey key) {
ConnectionHandler handler = (ConnectionHandler) key.attachment();
try {
if (!key.isValid()) {
// Key has been cancelled, make sure the socket gets closed
System.out.println("--------------------destory 1");
handler.peer.destroy();
return;
}
if (key.isReadable()) {
// Do a socket read and invoke the connection's receiveBytes message
int len = handler.channel.read(handler.readBuffer);
if (len == 0) {
// Was probably waiting on a write
return;
} else if (len == -1) {
// Socket was closed
key.cancel();
System.out.println(handler.peer.getIp());
System.out.println("--------------------destory 2");
handler.peer.destroy();
return;
}
System.out.println("--------len : " + len);
// "flip" the buffer - setting the limit to the current position and setting position to 0
handler.readBuffer.flip();
handler.peer.receiveMessage(handler.readBuffer);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative position)
handler.readBuffer.compact();
}
if (key.isWritable()) {
handler.writeBytes();
}
} catch (Exception e) {
// This can happen eg if the channel closes while the thread is about to get killed
// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
e.printStackTrace();
Throwable t = e;
Log.warn("Error handling SelectionKey: {}", t.getMessage() != null ? t.getMessage() : t.getClass().getName());
System.out.println("--------------------destory 3");
handler.peer.destroy();
}
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public HeaderDigest getLastHd() {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
if (list.size() > 0) {
return list.get(list.size() - 1);
}
return null;
}
|
#vulnerable code
public HeaderDigest getLastHd() {
if (null == lastHd) {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
if(list.size() > 0) {
this.lastHd = list.get(list.size() - 1);
}
}
return lastHd;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
List<Transaction> txList = getLedgerService().getCacheTxList(TransactionConstant.TX_TYPE_SET_ALIAS);
if (txList != null && tx.size() > 0) {
for (Transaction trx : txList) {
Alias a = ((AliasTransaction) trx).getTxData();
if(alias.getAddress().equals(a.getAlias())) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
if(alias.getAlias().equals(a.getAlias())){
return ValidateResult.getFailedResult("The alias has been occupied");
}
}
}
AliasPo aliasPo = getAliasDataService().get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
}
|
#vulnerable code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length != 23) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
AliasPo aliasPo = getAliasDataService().get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Set<K> keySet(String cacheTitle) {
Cache cache = this.cacheManager.getCache(cacheTitle);
if (null == cache) {
return new HashSet<>();
}
Iterator it = cache.iterator();
Set<K> set = new HashSet<>();
while (it.hasNext()) {
Cache.Entry<K, T> entry = (Cache.Entry<K, T>) it.next();
set.add((K) entry.getKey());
}
return set;
}
|
#vulnerable code
@Override
public Set<K> keySet(String cacheTitle) {
Iterator it = cacheManager.getCache(cacheTitle).iterator();
Set<K> set = new HashSet<>();
while (it.hasNext()) {
Cache.Entry<K, T> entry = (Cache.Entry<K, T>) it.next();
set.add((K) entry.getKey());
}
return set;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static Result createArea(String areaName) {
// prevent too many areas
if(AREAS.size() > (MAX -1)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
if(StringUtils.isBlank(areaName)) {
return Result.getFailed(ErrorCode.NULL_PARAMETER);
}
if (AREAS.containsKey(areaName)) {
return new Result(true, "KV_AREA_EXISTS");
}
if(!checkPathLegal(areaName)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
Result result;
try {
File dir = new File(dataPath + File.separator + areaName);
if(!dir.exists()) {
dir.mkdir();
}
String filePath = dataPath + File.separator + areaName + File.separator + BASE_DB_NAME;
DB db = openDB(filePath, true);
AREAS.put(areaName, db);
result = Result.getSuccess();
} catch (Exception e) {
Log.error("error create area: " + areaName, e);
result = new Result(false, "KV_AREA_CREATE_ERROR");
}
return result;
}
|
#vulnerable code
public static Result createArea(String areaName) {
// prevent too many areas
if(AREAS.size() > (MAX -1)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
if(StringUtils.isBlank(areaName)) {
return Result.getFailed(ErrorCode.NULL_PARAMETER);
}
if (AREAS.containsKey(areaName)) {
return new Result(true, "KV_AREA_EXISTS");
}
//TODO 特殊字符校验
if(!checkPathLegal(areaName)) {
return new Result(false, "KV_AREA_CREATE_ERROR");
}
Result result;
try {
File dir = new File(dataPath + File.separator + areaName);
if(!dir.exists()) {
dir.mkdir();
}
String filePath = dataPath + File.separator + areaName + File.separator + BASE_DB_NAME;
DB db = openDB(filePath, true);
AREAS.put(areaName, db);
result = Result.getSuccess();
} catch (Exception e) {
Log.error("error create area: " + areaName, e);
result = new Result(false, "KV_AREA_CREATE_ERROR");
}
return result;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void nextRound() throws NulsException, IOException {
packingRoundManager.calc(getBestBlock());
PocMeetingRound round = packingRoundManager.getCurrentRound();
while (TimeService.currentTimeMillis() < round.getStartTime()) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
Log.error(e);
}
}
boolean imIn = consensusManager.isPartakePacking() &&round.getLocalPacker() != null;
if (imIn) {
startMeeting(round);
}
}
|
#vulnerable code
private void nextRound() throws NulsException, IOException {
packingRoundManager.calc(getBestBlock());
while (TimeService.currentTimeMillis() < (packingRoundManager.getCurrentRound().getStartTime())) {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
Log.error(e);
}
}
boolean imIn = consensusManager.isPartakePacking() && packingRoundManager.getCurrentRound().getLocalPacker() != null;
if (imIn) {
startMeeting();
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getRoundFirstBlock(bestBlock, i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
|
#vulnerable code
public void init() {
//load five(CACHE_COUNT) round from db on the start time ;
Block bestBlock = NulsContext.getInstance().getBestBlock();
BlockRoundData roundData = new BlockRoundData(bestBlock.getHeader().getExtend());
for (long i = roundData.getRoundIndex(); i >= 1 && i >= roundData.getRoundIndex() - CACHE_COUNT; i--) {
Block firstBlock = getBlockService().getRoundFirstBlock(bestBlock, i - 1);
BlockRoundData thisRoundData = new BlockRoundData(firstBlock.getHeader().getExtend());
PocMeetingRound round = calcRound(firstBlock.getHeader().getHeight(), i, thisRoundData.getRoundStartTime());
ROUND_MAP.put(round.getIndex(), round);
Log.debug("load the round data index:{}", round.getIndex());
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void rollbackAppraval(Block block) {
if (null == block) {
Log.warn("the block is null!");
return;
}
this.rollbackTxList(block.getTxs(), 0, block.getTxs().size());
Block preBlock =this.getBlock(block.getHeader().getPreHash().getDigestHex());
context.setBestBlock(preBlock);
PackingRoundManager.getValidateInstance().calc(preBlock);
List<String> hashList = this.bifurcateProcessor.getHashList(block.getHeader().getHeight() - 1);
if (hashList.size() > 1) {
this.rollbackAppraval(preBlock);
}
}
|
#vulnerable code
private void rollbackAppraval(Block block) {
if (null == block) {
Log.warn("the block is null!");
return;
}
this.rollbackTxList(block.getTxs(), 0, block.getTxs().size());
PackingRoundManager.getValidateInstance().calc(this.getBlock(block.getHeader().getPreHash().getDigestHex()));
List<String> hashList = this.bifurcateProcessor.getHashList(block.getHeader().getHeight() - 1);
if (hashList.size() > 1) {
Block preBlock = confirmingBlockCacheManager.getBlock(block.getHeader().getPreHash().getDigestHex());
context.setBestBlock(preBlock);
this.rollbackAppraval(preBlock);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean processingBifurcation(long height) {
lock.lock();
try {
return this.bifurcateProcessor.processing(height);
} finally {
lock.unlock();
}
}
|
#vulnerable code
public boolean processingBifurcation(long height) {
return this.bifurcateProcessor.processing(height);
}
#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 validate(AbstractCoinTransaction tx) {
UtxoData data = (UtxoData) tx.getCoinData();
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = input.getFrom();
if (output == null && tx.getStatus() == TxStatusEnum.CACHED) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
} else if (output == null) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
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_OUTPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
|
#vulnerable code
@Override
public ValidateResult validate(AbstractCoinTransaction tx) {
UtxoData data = (UtxoData) tx.getCoinData();
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = input.getFrom();
if (output == null && tx.getStatus() == TxStatusEnum.CACHED) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
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_OUTPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public BlockInfo request(long height, List<String> sendList) {
return this.request(height, height, 1, sendList);
}
|
#vulnerable code
public BlockInfo request(long height, List<String> sendList) {
return this.request(height, height, 1,nodeIdList);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void cacheBlockToBuffer(Block block) {
blockCacheBuffer.cacheBlock(block);
BlockLog.info("orphan cache block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
Block preBlock = blockCacheBuffer.getBlock(block.getHeader().getPreHash().getDigestHex());
if (preBlock == null) {
if (this.downloadService.getStatus() != DownloadStatus.DOWNLOADING) {
downloadUtils.getBlockByHash(block.getHeader().getPreHash().getDigestHex());
}
} else {
this.addBlock(preBlock, true, null);
}
}
|
#vulnerable code
private void cacheBlockToBuffer(Block block) {
blockCacheBuffer.cacheBlock(block);
BlockLog.info("orphan cache block height:" + block.getHeader().getHeight() + ", preHash:" + block.getHeader().getPreHash() + " , hash:" + block.getHeader().getHash() + ", address:" + Address.fromHashs(block.getHeader().getPackingAddress()));
Block preBlock = blockCacheBuffer.getBlock(block.getHeader().getPreHash().getDigestHex());
if (preBlock == null) {
if (NulsContext.getServiceBean(DownloadService.class).getStatus() != DownloadStatus.DOWNLOADING) {
downloadUtils.getBlockByHash(block.getHeader().getPreHash().getDigestHex());
}
} else {
this.addBlock(preBlock, true, null);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void addTx(Block block) {
BlockHeader blockHeader = block.getHeader();
List<Transaction> txs = block.getTxs();
Transaction<Agent> agentTx = new CreateAgentTransaction();
Agent agent = new Agent();
agent.setPackingAddress(AddressTool.getAddress(ecKey.getPubKey()));
agent.setAgentAddress(AddressTool.getAddress(ecKey.getPubKey()));
agent.setTime(System.currentTimeMillis());
agent.setDeposit(Na.NA.multiply(20000));
agent.setAgentName("test".getBytes());
agent.setIntroduction("test agent".getBytes());
agent.setCommissionRate(0.3d);
agent.setBlockHeight(blockHeader.getHeight());
agentTx.setTxData(agent);
agentTx.setTime(agent.getTime());
agentTx.setBlockHeight(blockHeader.getHeight());
NulsSignData signData = signDigest(agentTx.getHash().getDigestBytes(), ecKey);
agentTx.setScriptSig(signData.getSignBytes());
// add the agent tx into agent list
txs.add(agentTx);
// new a deposit
Deposit deposit = new Deposit();
deposit.setAddress(AddressTool.getAddress(ecKey.getPubKey()));
deposit.setAgentHash(agentTx.getHash());
deposit.setTime(System.currentTimeMillis());
deposit.setDeposit(Na.NA.multiply(200000));
deposit.setBlockHeight(blockHeader.getHeight());
DepositTransaction depositTx = new DepositTransaction();
depositTx.setTime(deposit.getTime());
depositTx.setTxData(deposit);
depositTx.setBlockHeight(blockHeader.getHeight());
txs.add(depositTx);
}
|
#vulnerable code
protected void addTx(Block block) {
BlockHeader blockHeader = block.getHeader();
List<Transaction> txs = block.getTxs();
Transaction<Agent> agentTx = new CreateAgentTransaction();
Agent agent = new Agent();
agent.setPackingAddress(AddressTool.getAddress(ecKey.getPubKey()));
agent.setAgentAddress(AddressTool.getAddress(ecKey.getPubKey()));
agent.setTime(System.currentTimeMillis());
agent.setDeposit(Na.NA.multiply(20000));
agent.setAgentName("test".getBytes());
agent.setIntroduction("test agent".getBytes());
agent.setCommissionRate(0.3d);
agent.setBlockHeight(blockHeader.getHeight());
agentTx.setTxData(agent);
agentTx.setTime(agent.getTime());
agentTx.setBlockHeight(blockHeader.getHeight());
NulsSignData signData = null;
try {
signData = accountService.signData(agentTx.getHash().getDigestBytes(), ecKey);
} catch (NulsException e) {
e.printStackTrace();
}
agentTx.setScriptSig(signData.getSignBytes());
// add the agent tx into agent list
txs.add(agentTx);
// new a deposit
Deposit deposit = new Deposit();
deposit.setAddress(AddressTool.getAddress(ecKey.getPubKey()));
deposit.setAgentHash(agentTx.getHash());
deposit.setTime(System.currentTimeMillis());
deposit.setDeposit(Na.NA.multiply(200000));
deposit.setBlockHeight(blockHeader.getHeight());
DepositTransaction depositTx = new DepositTransaction();
depositTx.setTime(deposit.getTime());
depositTx.setTxData(deposit);
depositTx.setBlockHeight(blockHeader.getHeight());
txs.add(depositTx);
}
#location 23
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void checkCache() {
// if (null == blockService) {
// blockService = NulsContext.getServiceBean(BlockService.class);
// }
// Block block = blockService.getBlock(blockService.getLocalSavedHeight());
// boolean b = (TimeService.currentTimeMillis() - startTime) > 300000;
// b = b && (TimeService.currentTimeMillis() - block.getHeader().getTime()) > 300000;
// if (b) {
// ConsensusManager consensusManager = ConsensusManager.getInstance();
// consensusManager.destroy();
// this.startTime = TimeService.currentTimeMillis();
// }
}
|
#vulnerable code
private void checkCache() {
if (null == blockService) {
blockService = NulsContext.getServiceBean(BlockService.class);
}
Block block = blockService.getBlock(blockService.getLocalSavedHeight());
boolean b = (TimeService.currentTimeMillis() - startTime) > 300000;
b = b && (TimeService.currentTimeMillis() - block.getHeader().getTime()) > 300000;
if (b) {
ConsensusManager consensusManager = ConsensusManager.getInstance();
consensusManager.destroy();
NulsContext.getInstance().setBestBlock(blockService.getBlock(blockService.getLocalSavedHeight()));
this.startTime = TimeService.currentTimeMillis();
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash().length !=23 ) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
AliasPo aliasPo = aliasDataService.get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
}
|
#vulnerable code
@Override
public ValidateResult validate(AliasTransaction tx) {
Alias alias = tx.getTxData();
if (StringUtils.isBlank(alias.getAddress()) || new Address(alias.getAddress()).getHash160().length > 25) {
return ValidateResult.getFailedResult("The address format error");
}
if (!StringUtils.validAlias(alias.getAlias())) {
return ValidateResult.getFailedResult("The alias is between 3 to 20 characters");
}
AliasPo aliasPo = aliasDataService.get(alias.getAlias());
if (aliasPo != null) {
return ValidateResult.getFailedResult("The alias has been occupied");
}
return ValidateResult.getSuccessResult();
}
#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 init(Map<String, String> initParams) {
String databaseType = null;
if(initParams.get("databaseType") != null) {
databaseType = initParams.get("databaseType");
}
if (!StringUtils.isEmpty(databaseType) && hasType(databaseType)) {
String path = "classpath:/database-" + databaseType + ".xml";
NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext()));
}
}
|
#vulnerable code
@Override
public void init(Map<String, String> initParams) {
String dataBaseType = null;
if(initParams.get("dataBaseType") != null) {
dataBaseType = initParams.get("dataBaseType");
}
if (!StringUtils.isEmpty(dataBaseType) && hasType(dataBaseType)) {
String path = "classpath:/database-" + dataBaseType + ".xml";
NulsContext.setApplicationContext(new ClassPathXmlApplicationContext(new String[]{path}, true, NulsContext.getApplicationContext()));
}
}
#location 7
#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> nodeList = getNetworkStorage().getLocalNodeList(20);
nodeList.addAll(getSeedNodes());
for (Node node : nodeList) {
addNode(node);
}
running = true;
TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this);
nodeDiscoverHandler.start();
}
|
#vulnerable code
public void start() {
getNetworkStorage().init();
List<Node> nodeList = getNetworkStorage().getLocalNodeList(20);
nodeList.addAll(getSeedNodes());
for (Node node : nodeList) {
addNode(node);
}
running = true;
TaskManager.createAndRunThread(NetworkConstant.NETWORK_MODULE_ID, "NetworkNodeManager", this);
nodeDiscoverHandler.start();
}
#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 boolean resetSystem(String reason) {
if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) {
Log.info("system reset interrupt!");
return true;
}
Log.info("---------------reset start----------------");
Log.info("Received a reset system request, reason: 【" + reason + "】");
NetworkService networkService = NulsContext.getServiceBean(NetworkService.class);
networkService.reset();
DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class);
downloadService.reset();
ConsensusManager.getInstance().clearCache();
Log.info("---------------reset end----------------");
this.lastResetTime = TimeService.currentTimeMillis();
return true;
}
|
#vulnerable code
@Override
public boolean resetSystem(String reason) {
if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) {
Log.info("system reset interrupt!");
return true;
}
Log.info("---------------reset start----------------");
Log.info("Received a reset system request, reason: 【" + reason + "】");
NetworkService networkService = NulsContext.getServiceBean(NetworkService.class);
networkService.reset();
DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class);
downloadService.reset();
NulsContext.getServiceBean(LedgerService.class).resetLedgerCache();
ConsensusMeetingRunner consensusMeetingRunner = ConsensusMeetingRunner.getInstance();
consensusMeetingRunner.resetConsensus();
Log.info("---------------reset end----------------");
this.lastResetTime = TimeService.currentTimeMillis();
return true;
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public HeaderDigest getLastHd() {
if (null == lastHd) {
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
this.lastHd = list.get(list.size() - 1);
}
return lastHd;
}
|
#vulnerable code
public HeaderDigest getLastHd() {
if(null==lastHd){
List<HeaderDigest> list = new ArrayList<>(headerDigestList);
this.lastHd = list.get(list.size()-1);
}
return lastHd;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public NetworkEventResult process(BaseEvent event, Node node) {
GetNodeEvent getNodeEvent = (GetNodeEvent) event;
// String key = event.getHeader().getEventType() + "-" + node.getIp();
// if (cacheService.existEvent(key)) {
// getNetworkService().removeNode(node.getId());
// return null;
// }
// cacheService.putEvent(key, event, false);
List<Node> list = getAvailableNodes(getNodeEvent.getLength(), node.getId());
NodeEvent replyEvent = new NodeEvent(list);
return new NetworkEventResult(true, replyEvent);
}
|
#vulnerable code
@Override
public NetworkEventResult process(BaseEvent event, Node node) {
GetNodeEvent getNodeEvent = (GetNodeEvent) event;
String key = event.getHeader().getEventType() + "-" + node.getIp();
if (cacheService.existEvent(key)) {
getNetworkService().removeNode(node.getId());
return null;
}
cacheService.putEvent(key, event, false);
List<Node> list = getAvailableNodes(getNodeEvent.getLength(), node.getId());
NodeEvent replyEvent = new NodeEvent(list);
return new NetworkEventResult(true, replyEvent);
}
#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 start() {
getAccountList();
}
|
#vulnerable code
@Override
public void start() {
List<Account> accounts = getAccountList();
Set<String> addressList = new HashSet<>();
if (accounts != null && !accounts.isEmpty()) {
NulsContext.DEFAULT_ACCOUNT_ID = accounts.get(0).getAddress().getBase58();
for (Account account : accounts) {
addressList.add(account.getAddress().getBase58());
}
NulsContext.LOCAL_ADDRESS_LIST = addressList;
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public ValidateResult validate(AbstractCoinTransaction tx) {
UtxoData data = (UtxoData) tx.getCoinData();
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = input.getFrom();
if (output == null && tx.getStatus() == TxStatusEnum.CACHED) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
} else if (output == null) {
return ValidateResult.getFailedResult(ErrorCode.UTXO_NOT_FOUND);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
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_OUTPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
|
#vulnerable code
@Override
public ValidateResult validate(AbstractCoinTransaction tx) {
UtxoData data = (UtxoData) tx.getCoinData();
for (int i = 0; i < data.getInputs().size(); i++) {
UtxoInput input = data.getInputs().get(i);
UtxoOutput output = input.getFrom();
if (output == null && tx.getStatus() == TxStatusEnum.CACHED) {
return ValidateResult.getFailedResult(ErrorCode.ORPHAN_TX);
}
if (tx.getStatus() == TxStatusEnum.CACHED) {
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_OUTPUT);
}
return ValidateResult.getSuccessResult();
}
return ValidateResult.getSuccessResult();
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@PluginFactory
public static <S extends Serializable> SyslogAppender<S> createAppender(@PluginAttr("host") final String host,
@PluginAttr("port") final String portNum,
@PluginAttr("protocol") final String protocol,
@PluginAttr("reconnectionDelay") final String delay,
@PluginAttr("immediateFail") final String immediateFail,
@PluginAttr("name") final String name,
@PluginAttr("immediateFlush") final String immediateFlush,
@PluginAttr("suppressExceptions") final String suppress,
@PluginAttr("facility") final String facility,
@PluginAttr("id") final String id,
@PluginAttr("enterpriseNumber") final String ein,
@PluginAttr("includeMDC") final String includeMDC,
@PluginAttr("mdcId") final String mdcId,
@PluginAttr("mdcPrefix") final String mdcPrefix,
@PluginAttr("eventPrefix") final String eventPrefix,
@PluginAttr("newLine") final String includeNL,
@PluginAttr("newLineEscape") final String escapeNL,
@PluginAttr("appName") final String appName,
@PluginAttr("messageId") final String msgId,
@PluginAttr("mdcExcludes") final String excludes,
@PluginAttr("mdcIncludes") final String includes,
@PluginAttr("mdcRequired") final String required,
@PluginAttr("format") final String format,
@PluginElement("filters") final Filter filter,
@PluginConfiguration final Configuration config,
@PluginAttr("charset") final String charsetName,
@PluginAttr("exceptionPattern") final String exceptionPattern,
@PluginElement("LoggerFields") final LoggerFields loggerFields,
@PluginAttr("advertise") final String advertise) {
final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush);
final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress);
final int reconnectDelay = Integers.parseInt(delay);
final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail);
final int port = Integers.parseInt(portNum);
final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise);
@SuppressWarnings("unchecked")
final Layout<S> layout = (Layout<S>) (RFC5424.equalsIgnoreCase(format) ?
RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL,
escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) :
SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName));
if (name == null) {
LOGGER.error("No name provided for SyslogAppender");
return null;
}
final String prot = protocol != null ? protocol : Protocol.UDP.name();
final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol);
final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout);
if (manager == null) {
return null;
}
return new SyslogAppender<S>(name, layout, filter, handleExceptions, isFlush, manager,
isAdvertise ? config.getAdvertiser() : null);
}
|
#vulnerable code
@PluginFactory
public static <S extends Serializable> SyslogAppender<S> createAppender(@PluginAttr("host") final String host,
@PluginAttr("port") final String portNum,
@PluginAttr("protocol") final String protocol,
@PluginAttr("reconnectionDelay") final String delay,
@PluginAttr("immediateFail") final String immediateFail,
@PluginAttr("name") final String name,
@PluginAttr("immediateFlush") final String immediateFlush,
@PluginAttr("suppressExceptions") final String suppress,
@PluginAttr("facility") final String facility,
@PluginAttr("id") final String id,
@PluginAttr("enterpriseNumber") final String ein,
@PluginAttr("includeMDC") final String includeMDC,
@PluginAttr("mdcId") final String mdcId,
@PluginAttr("mdcPrefix") final String mdcPrefix,
@PluginAttr("eventPrefix") final String eventPrefix,
@PluginAttr("newLine") final String includeNL,
@PluginAttr("newLineEscape") final String escapeNL,
@PluginAttr("appName") final String appName,
@PluginAttr("messageId") final String msgId,
@PluginAttr("mdcExcludes") final String excludes,
@PluginAttr("mdcIncludes") final String includes,
@PluginAttr("mdcRequired") final String required,
@PluginAttr("format") final String format,
@PluginElement("filters") final Filter filter,
@PluginConfiguration final Configuration config,
@PluginAttr("charset") final String charsetName,
@PluginAttr("exceptionPattern") final String exceptionPattern,
@PluginElement("LoggerFields") final LoggerFields loggerFields,
@PluginAttr("advertise") final String advertise) {
final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush);
final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress);
final int reconnectDelay = delay == null ? 0 : Integer.parseInt(delay);
final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail);
final int port = portNum == null ? 0 : Integer.parseInt(portNum);
final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise);
@SuppressWarnings("unchecked")
final Layout<S> layout = (Layout<S>) (RFC5424.equalsIgnoreCase(format) ?
RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL,
escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) :
SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName));
if (name == null) {
LOGGER.error("No name provided for SyslogAppender");
return null;
}
final String prot = protocol != null ? protocol : Protocol.UDP.name();
final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol);
final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout);
if (manager == null) {
return null;
}
return new SyslogAppender<S>(name, layout, filter, handleExceptions, isFlush, manager,
isAdvertise ? config.getAdvertiser() : null);
}
#location 50
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static OutputStream getOutputStream(final boolean follow, final Target target) {
final PrintStream printStream = target == Target.SYSTEM_OUT ?
follow ? new PrintStream(new SystemOutStream()) : System.out :
follow ? new PrintStream(new SystemErrStream()) : System.err;
PropertiesUtil propsUtil = PropertiesUtil.getProperties();
if (!propsUtil.getStringProperty("os.name").startsWith("Windows") ||
propsUtil.getBooleanProperty("log4j.skipJansi")) {
return printStream;
} else {
try {
final ClassLoader loader = Loader.getClassLoader();
// We type the parameter as a wildcard to avoid a hard reference to Jansi.
final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream");
final Constructor<?> constructor = clazz.getConstructor(OutputStream.class);
return (OutputStream) constructor.newInstance(printStream);
} catch (final ClassNotFoundException cnfe) {
LOGGER.debug("Jansi is not installed");
} catch (final NoSuchMethodException nsme) {
LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor");
} catch (final Exception ex) {
LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream");
}
return printStream;
}
}
|
#vulnerable code
private static OutputStream getOutputStream(final boolean follow, final Target target) {
final PrintStream printStream = target == Target.SYSTEM_OUT ?
follow ? new PrintStream(new SystemOutStream()) : System.out :
follow ? new PrintStream(new SystemErrStream()) : System.err;
if (!System.getProperty("os.name").startsWith("Windows") || Boolean.getBoolean("log4j.skipJansi")) {
return printStream;
} else {
try {
final ClassLoader loader = Loader.getClassLoader();
// We type the parameter as a wildcard to avoid a hard reference to Jansi.
final Class<?> clazz = loader.loadClass("org.fusesource.jansi.WindowsAnsiOutputStream");
final Constructor<?> constructor = clazz.getConstructor(OutputStream.class);
return (OutputStream) constructor.newInstance(printStream);
} catch (final ClassNotFoundException cnfe) {
LOGGER.debug("Jansi is not installed");
} catch (final NoSuchMethodException nsme) {
LOGGER.warn("WindowsAnsiOutputStream is missing the proper constructor");
} catch (final Exception ex) {
LOGGER.warn("Unable to instantiate WindowsAnsiOutputStream");
}
return printStream;
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.