input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
public static ArrayList<String> runNative(String cmdToRun) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRun);
p.waitFor();
} catch (IOException e) {
return null;
} catch (InterruptedException e) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<String>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
} catch (IOException e) {
return null;
}
return sa;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public static ArrayList<String> runNative(String cmdToRun) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRun);
//p.waitFor();
} catch (IOException e) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<String>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
} catch (IOException e) {
return null;
}
p.destroy();
return sa;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public double getCpuVoltage() {
ArrayList<String> hwInfo = ExecutingCommand.runNative("wmic cpu get CurrentVoltage");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentvoltage")) {
continue;
} else {
// If successful this line is in tenths of volts
try {
int decivolts = Integer.parseInt(checkLine.trim());
if (decivolts > 0) {
return decivolts / 10d;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
// Above query failed, try something else
hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get CurrentVoltage");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) {
continue;
} else {
// If successful:
// If the eighth bit is set, bits 0-6 contain the voltage
// multiplied by 10. If the eighth bit is not set, then the bit
// setting in VoltageCaps represents the voltage value.
try {
int decivolts = Integer.parseInt(checkLine.trim());
// Check if 8th bit (of 16 bit number) is set
if ((decivolts & 0x80) > 0 && decivolts > 0) {
return decivolts / 10d;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
// Above query failed, try something else
hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get VoltageCaps");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) {
continue;
} else {
// If successful:
// Bits 0-3 of the field represent specific voltages that the
// processor socket can accept.
try {
int voltagebits = Integer.parseInt(checkLine.trim());
// Return appropriate voltage
if ((voltagebits & 0x1) > 0) {
return 5.0;
} else if ((voltagebits & 0x2) > 0) {
return 3.3;
} else if ((voltagebits & 0x4) > 0) {
return 2.9;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
return 0d;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public double getCpuVoltage() {
// Initialize
double volts = 0d;
// If we couldn't get through normal WMI go directly to OHM
if (this.voltIdentifierStr != null) {
double[] vals = wmiGetValuesForKeys("/namespace:\\\\root\\OpenHardwareMonitor PATH Sensor",
this.voltIdentifierStr, "Voltage", "Identifier,SensorType,Value");
if (vals.length > 0) {
// Return the first voltage reading
volts = vals[0];
}
return volts;
}
// This branch is used the first time and all subsequent times if
// successful (voltIdenifierStr == null)
// Try to get value
// Try to get value using initial or updated successful values
int decivolts = 0;
if (this.wmiVoltPath == null) {
this.wmiVoltPath = "CPU";
this.wmiVoltProperty = "CurrentVoltage";
decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty);
if (decivolts < 0) {
this.wmiVoltPath = "/namespace:\\\\root\\cimv2 PATH Win32_Processor";
decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty);
}
// If the eighth bit is set, bits 0-6 contain the voltage
// multiplied by 10. If the eighth bit is not set, then the bit
// setting in VoltageCaps represents the voltage value.
if ((decivolts & 0x80) == 0 && decivolts > 0) {
this.wmiVoltProperty = "VoltageCaps";
// really a bit setting, not decivolts, test later
decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty);
}
} else {
// We've successfully read a previous time, or failed both here and
// with OHM
decivolts = wmiGetValue(this.wmiVoltPath, this.wmiVoltProperty);
}
// Convert dV to V and return result
if (decivolts > 0) {
if (this.wmiVoltProperty.equals("VoltageCaps")) {
// decivolts are bits
if ((decivolts & 0x1) > 0) {
volts = 5.0;
} else if ((decivolts & 0x2) > 0) {
volts = 3.3;
} else if ((decivolts & 0x4) > 0) {
volts = 2.9;
}
} else {
// Value from bits 0-6
volts = (decivolts & 0x7F) / 10d;
}
}
if (volts <= 0d) {
// Unable to get voltage via WMI. Future attempts will be
// attempted via Open Hardware Monitor WMI if successful
String[] voltIdentifiers = wmiGetStrValuesForKey("/namespace:\\\\root\\OpenHardwareMonitor PATH Hardware",
"Voltage", "SensorType,Identifier");
// Look for identifier containing "cpu"
for (String id : voltIdentifiers) {
if (id.toLowerCase().contains("cpu")) {
this.voltIdentifierStr = id;
break;
}
}
// If none contain cpu just grab the first one
if (voltIdentifiers.length > 0) {
this.voltIdentifierStr = voltIdentifiers[0];
}
// If not null, recurse and get value via OHM
if (this.voltIdentifierStr != null) {
return getCpuVoltage();
}
}
return volts;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populateReadWriteMaps() {
// Although the field names say "PerSec" this is the Raw Data from which
// the associated fields are populated in the Formatted Data class, so
// in fact this is the data we want
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk",
"Name,DiskReadBytesPerSec,DiskWriteBytesPerSec", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
String index = vals.get("Name").get(i).split("\\s+")[0];
readMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskReadBytesPerSec").get(i), 0L));
writeMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskWriteBytesPerSec").get(i), 0L));
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populateReadWriteMaps() {
// Although the field names say "PerSec" this is the Raw Data from which
// the associated fields are populated in the Formatted Data class, so
// in fact this is the data we want
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk",
"Name,DiskReadsPerSec,DiskReadBytesPerSec,DiskWritesPerSec,DiskWriteBytesPerSec,PercentDiskTime", null,
READ_WRITE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
String index = ((String) vals.get("Name").get(i)).split("\\s+")[0];
readMap.put(index, (long) vals.get("DiskReadsPerSec").get(i));
readByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskReadBytesPerSec").get(i), 0L));
writeMap.put(index, (long) vals.get("DiskWritesPerSec").get(i));
writeByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskWriteBytesPerSec").get(i), 0L));
// Units are 100-ns, divide to get ms
xferTimeMap.put(index,
ParseUtil.parseLongOrDefault((String) vals.get("PercentDiskTime").get(i), 0L) / 10000L);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean updateAttributes() {
try {
File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName()));
if (!ifDir.isDirectory()) {
return false;
}
} catch (SecurityException e) {
return false;
}
String ifTypePath = String.format("/sys/class/net/%s/type", getName());
String carrierPath = String.format("/sys/class/net/%s/carrier", getName());
String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName());
String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName());
String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName());
String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName());
String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName());
String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName());
String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName());
String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName());
String ifSpeed = String.format("/sys/class/net/%s/speed", getName());
this.timeStamp = System.currentTimeMillis();
this.ifType = FileUtil.getIntFromFile(ifTypePath);
this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0;
this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath);
this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath);
this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath);
this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath);
this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath);
this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath);
this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath);
this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath);
// speed may be negative from file. Convert to MiB.
this.speed = FileUtil.getUnsignedLongFromFile(ifSpeed);
this.speed = this.speed < 0 ? 0 : this.speed << 20;
return true;
}
#location 35
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public boolean updateAttributes() {
try {
File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName()));
if (!ifDir.isDirectory()) {
return false;
}
} catch (SecurityException e) {
return false;
}
String ifTypePath = String.format("/sys/class/net/%s/type", getName());
String carrierPath = String.format("/sys/class/net/%s/carrier", getName());
String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName());
String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName());
String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName());
String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName());
String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName());
String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName());
String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName());
String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName());
String ifSpeed = String.format("/sys/class/net/%s/speed", getName());
this.timeStamp = System.currentTimeMillis();
this.ifType = FileUtil.getIntFromFile(ifTypePath);
this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0;
this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath);
this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath);
this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath);
this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath);
this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath);
this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath);
this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath);
this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath);
long speedMiB = FileUtil.getUnsignedLongFromFile(ifSpeed);
// speed may be -1 from file.
this.speed = speedMiB < 0 ? 0 : speedMiB << 20;
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populateReadWriteMaps() {
// Although the field names say "PerSec" this is the Raw Data from which
// the associated fields are populated in the Formatted Data class, so
// in fact this is the data we want
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk",
"Name,DiskReadBytesPerSec,DiskWriteBytesPerSec", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
String index = vals.get("Name").get(i).split("\\s+")[0];
readMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskReadBytesPerSec").get(i), 0L));
writeMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskWriteBytesPerSec").get(i), 0L));
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populateReadWriteMaps() {
// Although the field names say "PerSec" this is the Raw Data from which
// the associated fields are populated in the Formatted Data class, so
// in fact this is the data we want
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk",
"Name,DiskReadsPerSec,DiskReadBytesPerSec,DiskWritesPerSec,DiskWriteBytesPerSec,PercentDiskTime", null,
READ_WRITE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
String index = ((String) vals.get("Name").get(i)).split("\\s+")[0];
readMap.put(index, (long) vals.get("DiskReadsPerSec").get(i));
readByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskReadBytesPerSec").get(i), 0L));
writeMap.put(index, (long) vals.get("DiskWritesPerSec").get(i));
writeByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskWriteBytesPerSec").get(i), 0L));
// Units are 100-ns, divide to get ms
xferTimeMap.put(index,
ParseUtil.parseLongOrDefault((String) vals.get("PercentDiskTime").get(i), 0L) / 10000L);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public long[] querySystemCpuLoadTicks() {
long[] ticks = new long[TickType.values().length];
WinBase.FILETIME lpIdleTime = new WinBase.FILETIME();
WinBase.FILETIME lpKernelTime = new WinBase.FILETIME();
WinBase.FILETIME lpUserTime = new WinBase.FILETIME();
if (!Kernel32.INSTANCE.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime)) {
LOG.error("Failed to update system idle/kernel/user times. Error code: {}", Native.getLastError());
return ticks;
}
// IOwait:
// Windows does not measure IOWait.
// IRQ and ticks:
// Percent time raw value is cumulative 100NS-ticks
// Divide by 10_000 to get milliseconds
Map<SystemTickCountProperty, Long> valueMap = ProcessorInformation.querySystemCounters();
ticks[TickType.IRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTINTERRUPTTIME, 0L)
/ 10_000L;
ticks[TickType.SOFTIRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTDPCTIME, 0L)
/ 10_000L;
ticks[TickType.IDLE.getIndex()] = lpIdleTime.toDWordLong().longValue() / 10_000L;
ticks[TickType.SYSTEM.getIndex()] = lpKernelTime.toDWordLong().longValue() / 10_000L
- ticks[TickType.IDLE.getIndex()];
ticks[TickType.USER.getIndex()] = lpUserTime.toDWordLong().longValue() / 10_000L;
// Additional decrement to avoid double counting in the total array
ticks[TickType.SYSTEM.getIndex()] -= ticks[TickType.IRQ.getIndex()] + ticks[TickType.SOFTIRQ.getIndex()];
return ticks;
}
#location 8
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
public long[] querySystemCpuLoadTicks() {
// To get load in processor group scenario, we need perfmon counters, but the
// _Total instance is an average rather than total (scaled) number of ticks
// which matches GetSystemTimes() results. We can just query the per-processor
// ticks and add them up. Calling the get() method gains the benefit of
// synchronizing this output with the memoized result of per-processor ticks as
// well.
long[] ticks = new long[TickType.values().length];
// Sum processor ticks
long[][] procTicks = getProcessorCpuLoadTicks();
for (int i = 0; i < ticks.length; i++) {
for (long[] procTick : procTicks) {
ticks[i] += procTick[i];
}
}
return ticks;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition",
DRIVE_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition",
LOGICAL_DISK_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_PROPERTIES, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap.put(deviceID,
new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid,
ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L),
((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive));
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_STRINGS, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap
.put(deviceID,
new HWPartition(
(String) hwPartitionQueryMap
.get(WmiProperty.NAME.name()).get(
i),
(String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i),
(String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid,
(Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i),
((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(),
logicalDrive));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void removeAllCounters() {
// Remove all counter handles
for (HANDLEByReference href : counterHandleMap.values()) {
PerfDataUtil.removeCounter(href);
}
counterHandleMap.clear();
// Remove all queries
for (HANDLEByReference query : queryHandleMap.values()) {
PerfDataUtil.closeQuery(query);
}
queryHandleMap.clear();
queryCounterMap.clear();
}
#location 9
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public void removeAllCounters() {
// Remove all counters from counterHandle map
for (HANDLEByReference href : counterHandleMap.values()) {
PerfDataUtil.removeCounter(href);
}
counterHandleMap.clear();
// Remove query
if (this.queryHandle != null) {
PerfDataUtil.closeQuery(this.queryHandle);
}
this.queryHandle = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Processor[] getProcessors() {
if (_processors == null) {
List<Processor> processors = new ArrayList<Processor>();
Scanner in = null;
try {
in = new Scanner(new FileReader("/proc/cpuinfo"));
} catch (FileNotFoundException e) {
System.err.println("Problem with: /proc/cpuinfo");
System.err.println(e.getMessage());
return null;
}
in.useDelimiter("\n");
CentralProcessor cpu = null;
while (in.hasNext()) {
String toBeAnalyzed = in.next();
if (toBeAnalyzed.equals("")) {
if (cpu != null) {
processors.add(cpu);
}
cpu = null;
continue;
}
if (cpu == null) {
cpu = new CentralProcessor();
}
if (toBeAnalyzed.startsWith("model name\t")) {
cpu.setName(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("flags\t")) {
String[] flags = toBeAnalyzed.split(SEPARATOR)[1]
.split(" ");
boolean found = false;
for (String flag : flags) {
if (flag.equalsIgnoreCase("LM")) {
found = true;
break;
}
}
cpu.setCpu64(found);
continue;
}
if (toBeAnalyzed.startsWith("cpu family\t")) {
cpu.setFamily(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("model\t")) {
cpu.setModel(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("stepping\t")) {
cpu.setStepping(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("vendor_id")) {
cpu.setVendor(toBeAnalyzed.split(SEPARATOR)[1]); // vendor_id
continue;
}
}
in.close();
if (cpu != null) {
processors.add(cpu);
}
_processors = processors.toArray(new Processor[0]);
}
return _processors;
}
#location 65
#vulnerability type RESOURCE_LEAK | #fixed code
public Processor[] getProcessors() {
if (_processors == null) {
List<Processor> processors = new ArrayList<Processor>();
List<String> cpuInfo = null;
try {
cpuInfo = FileUtil.readFile("/proc/cpuinfo");
} catch (IOException e) {
System.err.println("Problem with: /proc/cpuinfo");
System.err.println(e.getMessage());
return null;
}
CentralProcessor cpu = null;
for (String toBeAnalyzed : cpuInfo) {
if (toBeAnalyzed.equals("")) {
if (cpu != null) {
processors.add(cpu);
}
cpu = null;
continue;
}
if (cpu == null) {
cpu = new CentralProcessor();
}
if (toBeAnalyzed.startsWith("model name\t")) {
cpu.setName(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("flags\t")) {
String[] flags = toBeAnalyzed.split(SEPARATOR)[1]
.split(" ");
boolean found = false;
for (String flag : flags) {
if (flag.equalsIgnoreCase("LM")) {
found = true;
break;
}
}
cpu.setCpu64(found);
continue;
}
if (toBeAnalyzed.startsWith("cpu family\t")) {
cpu.setFamily(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("model\t")) {
cpu.setModel(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("stepping\t")) {
cpu.setStepping(toBeAnalyzed.split(SEPARATOR)[1]); // model
// name
continue;
}
if (toBeAnalyzed.startsWith("vendor_id")) {
cpu.setVendor(toBeAnalyzed.split(SEPARATOR)[1]); // vendor_id
continue;
}
}
if (cpu != null) {
processors.add(cpu);
}
_processors = processors.toArray(new Processor[0]);
}
return _processors;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition",
DRIVE_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition",
LOGICAL_DISK_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_PROPERTIES, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap.put(deviceID,
new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid,
ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L),
((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive));
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_STRINGS, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap
.put(deviceID,
new HWPartition(
(String) hwPartitionQueryMap
.get(WmiProperty.NAME.name()).get(
i),
(String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i),
(String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid,
(Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i),
((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(),
logicalDrive));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public long[] querySystemCpuLoadTicks() {
long[] ticks = new long[TickType.values().length];
WinBase.FILETIME lpIdleTime = new WinBase.FILETIME();
WinBase.FILETIME lpKernelTime = new WinBase.FILETIME();
WinBase.FILETIME lpUserTime = new WinBase.FILETIME();
if (!Kernel32.INSTANCE.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime)) {
LOG.error("Failed to update system idle/kernel/user times. Error code: {}", Native.getLastError());
return ticks;
}
// IOwait:
// Windows does not measure IOWait.
// IRQ and ticks:
// Percent time raw value is cumulative 100NS-ticks
// Divide by 10_000 to get milliseconds
Map<SystemTickCountProperty, Long> valueMap = ProcessorInformation.querySystemCounters();
ticks[TickType.IRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTINTERRUPTTIME, 0L)
/ 10_000L;
ticks[TickType.SOFTIRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTDPCTIME, 0L)
/ 10_000L;
ticks[TickType.IDLE.getIndex()] = lpIdleTime.toDWordLong().longValue() / 10_000L;
ticks[TickType.SYSTEM.getIndex()] = lpKernelTime.toDWordLong().longValue() / 10_000L
- ticks[TickType.IDLE.getIndex()];
ticks[TickType.USER.getIndex()] = lpUserTime.toDWordLong().longValue() / 10_000L;
// Additional decrement to avoid double counting in the total array
ticks[TickType.SYSTEM.getIndex()] -= ticks[TickType.IRQ.getIndex()] + ticks[TickType.SOFTIRQ.getIndex()];
return ticks;
}
#location 7
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
public long[] querySystemCpuLoadTicks() {
// To get load in processor group scenario, we need perfmon counters, but the
// _Total instance is an average rather than total (scaled) number of ticks
// which matches GetSystemTimes() results. We can just query the per-processor
// ticks and add them up. Calling the get() method gains the benefit of
// synchronizing this output with the memoized result of per-processor ticks as
// well.
long[] ticks = new long[TickType.values().length];
// Sum processor ticks
long[][] procTicks = getProcessorCpuLoadTicks();
for (int i = 0; i < ticks.length; i++) {
for (long[] procTick : procTicks) {
ticks[i] += procTick[i];
}
}
return ticks;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public int[] getFanSpeeds() {
int[] fanSpeeds = new int[1];
ArrayList<String> hwInfo = ExecutingCommand
.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Fan get DesiredSpeed");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("desiredspeed")) {
continue;
} else {
// If successful
try {
int rpm = Integer.parseInt(checkLine.trim());
// Check if 8th bit (of 16 bit number) is set
if (rpm > 0) {
fanSpeeds[0] = rpm;
return fanSpeeds;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
return fanSpeeds;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public int[] getFanSpeeds() {
// Initialize
int[] fanSpeeds = new int[1];
// If we couldn't get through normal WMI go directly to OHM
if (!this.fanSpeedWMI) {
double[] vals = wmiGetValuesForKeys("/namespace:\\\\root\\OpenHardwareMonitor PATH Sensor", null, "Fan",
"Parent,SensorType,Value");
if (vals.length > 0) {
fanSpeeds = new int[vals.length];
for (int i = 0; i < vals.length; i++) {
fanSpeeds[i] = (int) vals[i];
}
}
return fanSpeeds;
}
// This branch is used the first time and all subsequent times if
// successful (fanSpeedWMI == true)
// Try to get value
int rpm = wmiGetValue("/namespace:\\\\root\\cimv2 PATH Win32_Fan", "DesiredSpeed");
// Set in array and return
if (rpm > 0) {
fanSpeeds[0] = rpm;
} else {
// Fail, switch to OHM
this.fanSpeedWMI = false;
return getFanSpeeds();
}
return fanSpeeds;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static UsbDevice[] getUsbDevices() {
List<UsbDevice> usbDevices = new ArrayList<UsbDevice>();
// Store map of pnpID to name, Manufacturer, serial
Map<String, String> nameMap = new HashMap<>();
Map<String, String> vendorMap = new HashMap<>();
Map<String, String> serialMap = new HashMap<>();
Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity",
"Name,Manufacturer,PnPDeviceID", null);
for (int i = 0; i < usbMap.get("Name").size(); i++) {
String pnpDeviceID = usbMap.get("PnPDeviceID").get(i);
nameMap.put(pnpDeviceID, usbMap.get("Name").get(i));
if (usbMap.get("Manufacturer").get(i).length() > 0) {
vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i));
}
String serialNumber = "";
// Format: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000
// Split by \ to get bus type (USB), VendorID/ProductID/Model
// Last field contains Serial # in hex as 2nd split by
// ampersands
String[] idSplit = pnpDeviceID.split("\\\\");
if (idSplit.length > 2) {
idSplit = idSplit[2].split("&");
if (idSplit.length > 3) {
serialNumber = idSplit[1];
}
}
if (serialNumber.length() > 0) {
serialMap.put(pnpDeviceID, serialNumber);
}
}
// Get serial # of disk drives (may overwrite previous, that's OK)
usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
// Finally, prepare final list for output
// Start with controllers
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null);
List<String> pnpDeviceIDs = usbMap.get("PNPDeviceID");
// Add any hubs
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null);
pnpDeviceIDs.addAll(usbMap.get("PNPDeviceID"));
// Add any stray USB devices in the list
for (String pnpDeviceID : nameMap.keySet().stream().sorted().collect(Collectors.toList())) {
if (pnpDeviceID.startsWith("USB\\") && !pnpDeviceIDs.contains(pnpDeviceID)) {
pnpDeviceIDs.add(pnpDeviceID);
}
}
for (String pnpDeviceID : pnpDeviceIDs) {
usbDevices.add(
new WindowsUsbDevice(nameMap.getOrDefault(pnpDeviceID, ""), vendorMap.getOrDefault(pnpDeviceID, ""),
serialMap.getOrDefault(pnpDeviceID, ""), new WindowsUsbDevice[0]));
}
return usbDevices.toArray(new UsbDevice[usbDevices.size()]);
}
#location 52
#vulnerability type NULL_DEREFERENCE | #fixed code
public static UsbDevice[] getUsbDevices() {
// Start by collecting information for all PNP devices. While in theory
// these could be individually queried with a WHERE clause, grabbing
// them all up front incurs minimal memory overhead in exchange for
// faster access later
// Clear maps
nameMap.clear();
vendorMap.clear();
serialMap.clear();
// Query Win32_PnPEntity to populate the maps
Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity",
"Name,Manufacturer,PnPDeviceID", null);
for (int i = 0; i < usbMap.get("Name").size(); i++) {
String pnpDeviceID = usbMap.get("PnPDeviceID").get(i);
nameMap.put(pnpDeviceID, usbMap.get("Name").get(i));
if (usbMap.get("Manufacturer").get(i).length() > 0) {
vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i));
}
String serialNumber = "";
// PNPDeviceID: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000
// Split by \ to get bus type (USB), VendorID/ProductID, other info
// As a temporary hack for a serial number, use last \-split field
// using 2nd &-split field if 4 fields
String[] idSplit = pnpDeviceID.split("\\\\");
if (idSplit.length > 2) {
idSplit = idSplit[2].split("&");
if (idSplit.length > 3) {
serialNumber = idSplit[1];
}
}
if (serialNumber.length() > 0) {
serialMap.put(pnpDeviceID, serialNumber);
}
}
// Disk drives or other physical media have a better way of getting
// serial number. Grab these and overwrite the temporary serial number
// assigned above if necessary
usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
// Some USB Devices are hubs to which other devices connect. Knowing
// which ones are hubs will help later when walking the device tree
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null);
List<String> usbHubs = usbMap.get("PNPDeviceID");
// Now build the hub map linking USB devices with their parent hub.
// At the top of the device tree are USB Controllers. All USB hubs and
// devices descend from these. Because this query returns pointers it's
// just not practical to try to query via COM so we use a command line
// in order to get USB devices in a text format
ArrayList<String> links = ExecutingCommand
.runNative("wmic path Win32_USBControllerDevice GET Antecedent,Dependent");
// This iteration actually walks the device tree in order so while the
// antecedent of all USB devices is its controller, we know that if a
// device is not a hub that the last hub listed is its parent
// Devices with PNPDeviceID containing "ROOTHUB" are special and will be
// parents of the next item(s)
// This won't id chained hubs (other than the root hub) but is a quick
// hack rather than walking the entire device tree using the SetupDI API
// and good enough since exactly how a USB device is connected is
// theoretically transparent to the user
hubMap.clear();
String currentHub = null;
String rootHub = null;
for (String s : links) {
String[] split = s.split("\\s+");
if (split.length < 2) {
continue;
}
String antecedent = getId(split[0]);
String dependent = getId(split[1]);
// Ensure initial defaults are sane if something goes wrong
if (currentHub == null || rootHub == null) {
currentHub = antecedent;
rootHub = antecedent;
}
String parent;
if (dependent.contains("ROOT_HUB")) {
// This is a root hub, assign controller as parent;
parent = antecedent;
rootHub = dependent;
currentHub = dependent;
} else if (usbHubs.contains(dependent)) {
// This is a hub, assign parent as root hub
if (rootHub == null) {
rootHub = antecedent;
}
parent = rootHub;
currentHub = dependent;
} else {
// This is not a hub, assign parent as previous hub
if (currentHub == null) {
currentHub = antecedent;
}
parent = currentHub;
}
// Finally add the parent/child linkage to the map
if (!hubMap.containsKey(parent)) {
hubMap.put(parent, new ArrayList<String>());
}
hubMap.get(parent).add(dependent);
}
// Finally we simply get the device IDs of the USB Controllers. These
// will recurse downward to devices as needed
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null);
List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>();
for (String controllerDeviceID : usbMap.get("PNPDeviceID")) {
controllerDevices.add(getDeviceAndChildren(controllerDeviceID));
}
return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property)
.add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
case BOOLEAN: // WinDef.BOOL TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.boolVal.booleanValue());
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
}
#location 31
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
case UINT64:
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property)
.add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
case BOOLEAN: // WinDef.BOOL TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.boolVal.booleanValue());
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public long getSwapUsed() {
long total;
long available;
if (!Kernel32.INSTANCE.GlobalMemoryStatusEx(this._memory)) {
LOG.error("Failed to Initialize MemoryStatusEx. Error code: {}", Kernel32.INSTANCE.GetLastError());
this._memory = null;
return 0L;
}
total = this.getSwapTotal();
available = this._memory.ullAvailPageFile.longValue() - this._memory.ullAvailPhys.longValue();
return total - available;
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public long getSwapUsed() {
PdhFmtCounterValue phPagefileCounterValue = new PdhFmtCounterValue();
int ret = Pdh.INSTANCE.PdhGetFormattedCounterValue(pPagefile.getValue(), Pdh.PDH_FMT_LARGE | Pdh.PDH_FMT_1000,
null, phPagefileCounterValue);
if (ret != 0) {
LOG.warn("Failed to get Pagefile % Usage counter. Error code: {}", String.format("0x%08X", ret));
return 0L;
}
// Returns results in 1000's of percent, e.g. 5% is 5000
// Multiply by page file size and Divide by 100 * 1000
// Putting division at end avoids need to cast division to double
return getSwapTotal() * phPagefileCounterValue.value.largeValue / 100000;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName(vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i)));
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong(vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
readMap.clear();
writeMap.clear();
populateReadWriteMaps();
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName((String) vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i)));
String index = vals.get("Index").get(i).toString();
if (readMap.containsKey(index)) {
ds.setReads(readMap.get(index));
}
if (writeMap.containsKey(index)) {
ds.setWrites(writeMap.get(index));
}
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong((String) vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName(vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i)));
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong(vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
readMap.clear();
writeMap.clear();
populateReadWriteMaps();
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName((String) vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i)));
String index = vals.get("Index").get(i).toString();
if (readMap.containsKey(index)) {
ds.setReads(readMap.get(index));
}
if (writeMap.containsKey(index)) {
ds.setWrites(writeMap.get(index));
}
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong((String) vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public long[] querySystemCpuLoadTicks() {
// convert the Linux Jiffies to Milliseconds.
long[] ticks = CpuStat.getSystemCpuLoadTicks();
long hz = LinuxOperatingSystem.getHz();
for (int i = 0; i < ticks.length; i++) {
ticks[i] = ticks[i] * 1000L / hz;
}
return ticks;
}
#location 4
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
public long[] querySystemCpuLoadTicks() {
// convert the Linux Jiffies to Milliseconds.
long[] ticks = CpuStat.getSystemCpuLoadTicks();
// In rare cases, /proc/stat reading fails. If so, try again.
if (LongStream.of(ticks).sum() == 0) {
ticks = CpuStat.getSystemCpuLoadTicks();
}
long hz = LinuxOperatingSystem.getHz();
for (int i = 0; i < ticks.length; i++) {
ticks[i] = ticks[i] * 1000L / hz;
}
return ticks;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void removeAllCounters() {
// Remove all counter handles
for (HANDLEByReference href : counterHandleMap.values()) {
PerfDataUtil.removeCounter(href);
}
counterHandleMap.clear();
// Remove all queries
for (HANDLEByReference query : queryHandleMap.values()) {
PerfDataUtil.closeQuery(query);
}
queryHandleMap.clear();
queryCounterMap.clear();
}
#location 4
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public void removeAllCounters() {
// Remove all counters from counterHandle map
for (HANDLEByReference href : counterHandleMap.values()) {
PerfDataUtil.removeCounter(href);
}
counterHandleMap.clear();
// Remove query
if (this.queryHandle != null) {
PerfDataUtil.closeQuery(this.queryHandle);
}
this.queryHandle = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static String getCardCodec(File cardDir) {
String cardCodec = "";
for (File file : cardDir.listFiles()) {
if (file.getName().startsWith("codec")) {
cardCodec = FileUtil.getKeyValueMapFromFile(file.getPath(), ":").get("Codec");
}
}
return cardCodec;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
private static String getCardCodec(File cardDir) {
String cardCodec = "";
File[] cardFiles = cardDir.listFiles();
if (cardFiles == null) {
return "";
}
for (File file : cardDir.listFiles()) {
if (file.getName().startsWith("codec")) {
cardCodec = FileUtil.getKeyValueMapFromFile(file.getPath(), ":").get("Codec");
}
}
return cardCodec;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String getSystemSerialNumber() {
if (this.cpuSerialNumber == null) {
ArrayList<String> hwInfo = ExecutingCommand.runNative("system_profiler SPHardwareDataType");
// Mavericks and later
for (String checkLine : hwInfo) {
if (checkLine.contains("Serial Number (system)")) {
String[] snSplit = checkLine.split("\\s+");
this.cpuSerialNumber = snSplit[snSplit.length - 1];
break;
}
}
// Panther and later
if (this.cpuSerialNumber == null) {
for (String checkLine : hwInfo) {
if (checkLine.contains("r (system)")) {
String[] snSplit = checkLine.split("\\s+");
this.cpuSerialNumber = snSplit[snSplit.length - 1];
break;
}
}
}
if (this.cpuSerialNumber == null) {
this.cpuSerialNumber = "unknown";
}
}
return this.cpuSerialNumber;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public String getSystemSerialNumber() {
if (this.cpuSerialNumber == null) {
int service = 0;
MachPort masterPort = new MachPort();
int result = IOKit.INSTANCE.IOMasterPort(0, masterPort);
if (result != 0) {
LOG.error(String.format("Error: IOMasterPort() = %08x", result));
this.cpuSerialNumber = "unknown";
} else {
service = IOKit.INSTANCE.IOServiceGetMatchingService(masterPort.getValue(),
IOKit.INSTANCE.IOServiceMatching("IOPlatformExpertDevice"));
if (service == 0) {
this.cpuSerialNumber = "unknown";
} else {
// Fetch the serial number
CFTypeRef serialNumberAsCFString = IOKit.INSTANCE.IORegistryEntryCreateCFProperty(service,
CFStringRef.toCFString("IOPlatformSerialNumber"),
CoreFoundation.INSTANCE.CFAllocatorGetDefault(), 0);
IOKit.INSTANCE.IOObjectRelease(service);
this.cpuSerialNumber = CfUtil.cfPointerToString(serialNumberAsCFString.getPointer());
}
}
}
return this.cpuSerialNumber;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ArrayList<String> runNative(String cmdToRun) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRun);
p.waitFor();
} catch (IOException e) {
LOG.trace("", e);
return null;
} catch (InterruptedException e) {
LOG.trace("", e);
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
} catch (IOException e) {
LOG.trace("", e);
return null;
}
return sa;
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public static ArrayList<String> runNative(String cmdToRun) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRun);
} catch (IOException e) {
LOG.trace("", e);
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
p.waitFor();
} catch (InterruptedException e) {
LOG.trace("", e);
return null;
} catch (IOException e) {
LOG.trace("", e);
return null;
}
return sa;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
enumerator.Release();
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
}
#location 30
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject,
String perfWmiClass) {
Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject);
if (valueMap.isEmpty()) {
return queryValuesFromWMI(propertyEnum, perfWmiClass);
}
return valueMap;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject,
String perfWmiClass) {
// Check without locking for performance
if (!failedQueryCache.contains(perfObject)) {
failedQueryCacheLock.lock();
try {
// Double check lock
if (!failedQueryCache.contains(perfObject)) {
Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject);
if (!valueMap.isEmpty()) {
return valueMap;
}
// If we are here, query failed
LOG.warn("Disabling further attempts to query {}.", perfObject);
failedQueryCache.add(perfObject);
}
} finally {
failedQueryCacheLock.unlock();
}
}
return queryValuesFromWMI(propertyEnum, perfWmiClass);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName(vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i)));
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong(vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
readMap.clear();
writeMap.clear();
populateReadWriteMaps();
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName((String) vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i)));
String index = vals.get("Index").get(i).toString();
if (readMap.containsKey(index)) {
ds.setReads(readMap.get(index));
}
if (writeMap.containsKey(index)) {
ds.setWrites(writeMap.get(index));
}
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong((String) vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static boolean updateDiskStats(HWDiskStore diskStore, DASessionRef session,
Map<String, String> mountPointMap, Map<String, String> logicalVolumeMap, Map<CFKey, CFStringRef> cfKeyMap) {
// Now look up the device using the BSD Name to get its
// statistics
String bsdName = diskStore.getName();
CFMutableDictionaryRef matchingDict = IOKitUtil.getBSDNameMatchingDict(bsdName);
if (matchingDict != null) {
// search for all IOservices that match the bsd name
IOIterator driveListIter = IOKitUtil.getMatchingServices(matchingDict);
if (driveListIter != null) {
// getMatchingServices releases matchingDict
IORegistryEntry drive = driveListIter.next();
// Should only match one drive
if (drive != null) {
// Should be an IOMedia object with a parent
// IOBlockStorageDriver object
// Get the properties from the parent
if (drive.conformsTo("IOMedia")) {
IORegistryEntry parent = drive.getParentEntry("IOService");
if (parent != null && parent.conformsTo("IOBlockStorageDriver")) {
CFMutableDictionaryRef properties = parent.createCFProperties();
// We now have a properties object with the
// statistics we need on it. Fetch them
Pointer result = properties.getValue(cfKeyMap.get(CFKey.STATISTICS));
CFDictionaryRef statistics = new CFDictionaryRef(result);
diskStore.setTimeStamp(System.currentTimeMillis());
// Now get the stats we want
result = statistics.getValue(cfKeyMap.get(CFKey.READ_OPS));
CFNumberRef stat = new CFNumberRef(result);
diskStore.setReads(stat.longValue());
result = statistics.getValue(cfKeyMap.get(CFKey.READ_BYTES));
stat.setPointer(result);
diskStore.setReadBytes(stat.longValue());
result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_OPS));
stat.setPointer(result);
diskStore.setWrites(stat.longValue());
result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_BYTES));
stat.setPointer(result);
diskStore.setWriteBytes(stat.longValue());
// Total time is in nanoseconds. Add read+write
// and convert total to ms
result = statistics.getValue(cfKeyMap.get(CFKey.READ_TIME));
stat.setPointer(result);
long xferTime = stat.longValue();
result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_TIME));
stat.setPointer(result);
xferTime += stat.longValue();
diskStore.setTransferTime(xferTime / 1_000_000L);
properties.release();
} else {
// This is normal for FileVault drives, Fusion
// drives, and other virtual bsd names
LOG.debug("Unable to find block storage driver properties for {}", bsdName);
}
// Now get partitions for this disk.
List<HWPartition> partitions = new ArrayList<>();
CFMutableDictionaryRef properties = drive.createCFProperties();
// Partitions will match BSD Unit property
Pointer result = properties.getValue(cfKeyMap.get(CFKey.BSD_UNIT));
CFNumberRef bsdUnit = new CFNumberRef(result);
// We need a CFBoolean that's false.
// Whole disk has 'true' for Whole and 'false'
// for leaf; store the boolean false
result = properties.getValue(cfKeyMap.get(CFKey.LEAF));
CFBooleanRef cfFalse = new CFBooleanRef(result);
// create a matching dict for BSD Unit
CFMutableDictionaryRef propertyDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(),
new CFIndex(0), null, null);
propertyDict.setValue(cfKeyMap.get(CFKey.BSD_UNIT), bsdUnit);
propertyDict.setValue(cfKeyMap.get(CFKey.WHOLE), cfFalse);
matchingDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(), new CFIndex(0), null,
null);
matchingDict.setValue(cfKeyMap.get(CFKey.IO_PROPERTY_MATCH), propertyDict);
// search for IOservices that match the BSD Unit
// with whole=false; these are partitions
IOIterator serviceIterator = IOKitUtil.getMatchingServices(matchingDict);
// getMatchingServices releases matchingDict
properties.release();
propertyDict.release();
// Iterate disks
IORegistryEntry sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator);
while (sdService != null) {
// look up the BSD Name
String partBsdName = sdService.getStringProperty("BSD Name");
String name = partBsdName;
String type = "";
// Get the DiskArbitration dictionary for
// this partition
DADiskRef disk = DA.DADiskCreateFromBSDName(CF.CFAllocatorGetDefault(), session,
partBsdName);
if (disk != null) {
CFDictionaryRef diskInfo = DA.DADiskCopyDescription(disk);
if (diskInfo != null) {
// get volume name from its key
result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_MEDIA_NAME));
CFStringRef volumePtr = new CFStringRef(result);
type = volumePtr.stringValue();
if (type == null) {
type = Constants.UNKNOWN;
}
result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_VOLUME_NAME));
if (result == null) {
name = type;
} else {
volumePtr.setPointer(result);
name = volumePtr.stringValue();
}
diskInfo.release();
}
disk.release();
}
String mountPoint;
if (logicalVolumeMap.containsKey(partBsdName)) {
mountPoint = "Logical Volume: " + logicalVolumeMap.get(partBsdName);
} else {
mountPoint = mountPointMap.getOrDefault(partBsdName, "");
}
Long size = sdService.getLongProperty("Size");
Integer bsdMajor = sdService.getIntegerProperty("BSD Major");
Integer bsdMinor = sdService.getIntegerProperty("BSD Minor");
partitions.add(new HWPartition(partBsdName, name, type, sdService.getStringProperty("UUID"),
size == null ? 0L : size, bsdMajor == null ? 0 : bsdMajor,
bsdMinor == null ? 0 : bsdMinor, mountPoint));
// iterate
sdService.release();
sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator);
}
serviceIterator.release();
Collections.sort(partitions);
diskStore.setPartitions(partitions.toArray(new HWPartition[0]));
if (parent != null) {
parent.release();
}
} else {
LOG.error("Unable to find IOMedia device or parent for {}", bsdName);
}
drive.release();
}
driveListIter.release();
return true;
}
}
return false;
}
#location 135
#vulnerability type NULL_DEREFERENCE | #fixed code
private static boolean updateDiskStats(HWDiskStore diskStore, DASessionRef session,
Map<String, String> mountPointMap, Map<String, String> logicalVolumeMap, Map<CFKey, CFStringRef> cfKeyMap) {
// Now look up the device using the BSD Name to get its
// statistics
String bsdName = diskStore.getName();
CFMutableDictionaryRef matchingDict = IOKitUtil.getBSDNameMatchingDict(bsdName);
if (matchingDict != null) {
// search for all IOservices that match the bsd name
IOIterator driveListIter = IOKitUtil.getMatchingServices(matchingDict);
if (driveListIter != null) {
// getMatchingServices releases matchingDict
IORegistryEntry drive = driveListIter.next();
// Should only match one drive
if (drive != null) {
// Should be an IOMedia object with a parent
// IOBlockStorageDriver object
// Get the properties from the parent
if (drive.conformsTo("IOMedia")) {
IORegistryEntry parent = drive.getParentEntry("IOService");
if (parent != null && parent.conformsTo("IOBlockStorageDriver")) {
CFMutableDictionaryRef properties = parent.createCFProperties();
// We now have a properties object with the
// statistics we need on it. Fetch them
Pointer result = properties.getValue(cfKeyMap.get(CFKey.STATISTICS));
CFDictionaryRef statistics = new CFDictionaryRef(result);
diskStore.setTimeStamp(System.currentTimeMillis());
// Now get the stats we want
result = statistics.getValue(cfKeyMap.get(CFKey.READ_OPS));
CFNumberRef stat = new CFNumberRef(result);
diskStore.setReads(stat.longValue());
result = statistics.getValue(cfKeyMap.get(CFKey.READ_BYTES));
stat.setPointer(result);
diskStore.setReadBytes(stat.longValue());
result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_OPS));
stat.setPointer(result);
diskStore.setWrites(stat.longValue());
result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_BYTES));
stat.setPointer(result);
diskStore.setWriteBytes(stat.longValue());
// Total time is in nanoseconds. Add read+write
// and convert total to ms
result = statistics.getValue(cfKeyMap.get(CFKey.READ_TIME));
stat.setPointer(result);
long xferTime = stat.longValue();
result = statistics.getValue(cfKeyMap.get(CFKey.WRITE_TIME));
stat.setPointer(result);
xferTime += stat.longValue();
diskStore.setTransferTime(xferTime / 1_000_000L);
properties.release();
} else {
// This is normal for FileVault drives, Fusion
// drives, and other virtual bsd names
LOG.debug("Unable to find block storage driver properties for {}", bsdName);
}
// Now get partitions for this disk.
List<HWPartition> partitions = new ArrayList<>();
CFMutableDictionaryRef properties = drive.createCFProperties();
// Partitions will match BSD Unit property
Pointer result = properties.getValue(cfKeyMap.get(CFKey.BSD_UNIT));
CFNumberRef bsdUnit = new CFNumberRef(result);
// We need a CFBoolean that's false.
// Whole disk has 'true' for Whole and 'false'
// for leaf; store the boolean false
result = properties.getValue(cfKeyMap.get(CFKey.LEAF));
CFBooleanRef cfFalse = new CFBooleanRef(result);
// create a matching dict for BSD Unit
CFMutableDictionaryRef propertyDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(),
new CFIndex(0), null, null);
propertyDict.setValue(cfKeyMap.get(CFKey.BSD_UNIT), bsdUnit);
propertyDict.setValue(cfKeyMap.get(CFKey.WHOLE), cfFalse);
matchingDict = CF.CFDictionaryCreateMutable(CF.CFAllocatorGetDefault(), new CFIndex(0), null,
null);
matchingDict.setValue(cfKeyMap.get(CFKey.IO_PROPERTY_MATCH), propertyDict);
// search for IOservices that match the BSD Unit
// with whole=false; these are partitions
IOIterator serviceIterator = IOKitUtil.getMatchingServices(matchingDict);
// getMatchingServices releases matchingDict
properties.release();
propertyDict.release();
if (serviceIterator != null) {
// Iterate disks
IORegistryEntry sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator);
while (sdService != null) {
// look up the BSD Name
String partBsdName = sdService.getStringProperty("BSD Name");
String name = partBsdName;
String type = "";
// Get the DiskArbitration dictionary for
// this partition
DADiskRef disk = DA.DADiskCreateFromBSDName(CF.CFAllocatorGetDefault(), session,
partBsdName);
if (disk != null) {
CFDictionaryRef diskInfo = DA.DADiskCopyDescription(disk);
if (diskInfo != null) {
// get volume name from its key
result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_MEDIA_NAME));
CFStringRef volumePtr = new CFStringRef(result);
type = volumePtr.stringValue();
if (type == null) {
type = Constants.UNKNOWN;
}
result = diskInfo.getValue(cfKeyMap.get(CFKey.DA_VOLUME_NAME));
if (result == null) {
name = type;
} else {
volumePtr.setPointer(result);
name = volumePtr.stringValue();
}
diskInfo.release();
}
disk.release();
}
String mountPoint;
if (logicalVolumeMap.containsKey(partBsdName)) {
mountPoint = "Logical Volume: " + logicalVolumeMap.get(partBsdName);
} else {
mountPoint = mountPointMap.getOrDefault(partBsdName, "");
}
Long size = sdService.getLongProperty("Size");
Integer bsdMajor = sdService.getIntegerProperty("BSD Major");
Integer bsdMinor = sdService.getIntegerProperty("BSD Minor");
partitions.add(new HWPartition(partBsdName, name, type,
sdService.getStringProperty("UUID"), size == null ? 0L : size,
bsdMajor == null ? 0 : bsdMajor, bsdMinor == null ? 0 : bsdMinor, mountPoint));
// iterate
sdService.release();
sdService = IOKit.INSTANCE.IOIteratorNext(serviceIterator);
}
serviceIterator.release();
}
Collections.sort(partitions);
diskStore.setPartitions(partitions.toArray(new HWPartition[0]));
if (parent != null) {
parent.release();
}
} else {
LOG.error("Unable to find IOMedia device or parent for {}", bsdName);
}
drive.release();
}
driveListIter.release();
return true;
}
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues(
Class<T> propertyEnum, String perfObject, String perfWmiClass) {
Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(propertyEnum,
perfObject);
if (instancesAndValuesMap.getA().isEmpty()) {
return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass);
}
return instancesAndValuesMap;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues(
Class<T> propertyEnum, String perfObject, String perfWmiClass) {
// Check without locking for performance
if (!failedQueryCache.contains(perfObject)) {
failedQueryCacheLock.lock();
try {
// Double check lock
if (!failedQueryCache.contains(perfObject)) {
Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(
propertyEnum, perfObject);
if (!instancesAndValuesMap.getA().isEmpty()) {
return instancesAndValuesMap;
}
// If we are here, query failed
LOG.warn("Disabling further attempts to query {}.", perfObject);
failedQueryCache.add(perfObject);
}
} finally {
failedQueryCacheLock.unlock();
}
}
return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void updateMeminfo() {
long now = System.currentTimeMillis();
if (now - this.lastUpdate > 100) {
if (!Psapi.INSTANCE.GetPerformanceInfo(perfInfo, perfInfo.size())) {
LOG.error("Failed to get Performance Info. Error code: {}", Kernel32.INSTANCE.GetLastError());
this.perfInfo = null;
}
this.memAvailable = perfInfo.PageSize.longValue() * perfInfo.PhysicalAvailable.longValue();
this.memTotal = perfInfo.PageSize.longValue() * perfInfo.PhysicalTotal.longValue();
this.swapTotal = perfInfo.PageSize.longValue()
* (perfInfo.CommitLimit.longValue() - perfInfo.PhysicalTotal.longValue());
this.lastUpdate = now;
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void updateMeminfo() {
long now = System.currentTimeMillis();
if (now - this.lastUpdate > 100) {
if (!Psapi.INSTANCE.GetPerformanceInfo(perfInfo, perfInfo.size())) {
LOG.error("Failed to get Performance Info. Error code: {}", Kernel32.INSTANCE.GetLastError());
return;
}
this.memAvailable = perfInfo.PageSize.longValue() * perfInfo.PhysicalAvailable.longValue();
this.memTotal = perfInfo.PageSize.longValue() * perfInfo.PhysicalTotal.longValue();
this.swapTotal = perfInfo.PageSize.longValue()
* (perfInfo.CommitLimit.longValue() - perfInfo.PhysicalTotal.longValue());
this.lastUpdate = now;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
}
#location 39
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property)
.add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Memory sysctl(String name) {
IntByReference size = new IntByReference();
if (0 != SystemB.INSTANCE.sysctlbyname(name, null, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
Memory m = new Memory(size.getValue());
if (0 != SystemB.INSTANCE.sysctlbyname(name, m, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
return m;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static Memory sysctl(String name) {
IntByReference size = new IntByReference();
if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, null, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
Memory m = new Memory(size.getValue());
if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, m, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
return m;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGetChildProcesses() {
// Get list of PIDS
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
OSProcess[] processes = os.getProcesses(0, null);
Map<Integer, Integer> childMap = new HashMap<>();
// First iteration to set all 0's
for (OSProcess p : processes) {
childMap.put(p.getProcessID(), 0);
childMap.put(p.getParentProcessID(), 0);
}
// Second iteration to count children
for (OSProcess p : processes) {
childMap.put(p.getParentProcessID(), childMap.get(p.getParentProcessID()) + 1);
}
// Find a PID with 0, 1, and N>1 children
int zeroPid = -1;
int onePid = -1;
int nPid = -1;
int nNum = 0;
int mPid = -1;
int mNum = 0;
for (Integer i : childMap.keySet()) {
if (zeroPid < 0 && childMap.get(i) == 0) {
zeroPid = i;
} else if (onePid < 0 && childMap.get(i) == 1) {
onePid = i;
} else if (nPid < 0 && childMap.get(i) > 1) {
// nPid is probably PID=1 with all PIDs with no other parent
nPid = i;
nNum = childMap.get(i);
} else if (mPid < 0 && childMap.get(i) > 1) {
mPid = i;
mNum = childMap.get(i);
}
if (zeroPid >= 0 && onePid >= 0 && nPid >= 0 && mPid >= 0) {
break;
}
}
if (zeroPid >= 0) {
assertEquals(0, os.getChildProcesses(zeroPid, 0, null).length);
}
if (SystemInfo.getCurrentPlatformEnum() != PlatformEnum.SOLARIS) {
// Due to race condition, a process may terminate before we count
// its children. Play the odds.
// At least one of these tests should work.
if (onePid >= 0 && nPid >= 0 && mPid >= 0) {
assertTrue(os.getChildProcesses(onePid, 0, null).length == 1
|| os.getChildProcesses(nPid, 0, null).length == nNum
|| os.getChildProcesses(mPid, 0, null).length == mNum);
}
}
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testGetChildProcesses() {
// Testing child processes is tricky because we don't really know a
// priori what processes might have children, and if we do test the full
// list vs. individual processes, we run into a race condition where
// child processes can start or stop before we measure a second time. So
// we can't really test for one-to-one correspondence of child process
// lists.
//
// We can expect code logic failures to occur all/most of the time for
// categories of processes, however, and allow occasional differences
// due to race conditions. So we will test three categories of
// processes: Those with 0 children, those with exactly 1 child process,
// and those with multiple child processes. On the second poll, we
// expect at least half of those categories to still be in the same
// category.
//
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
OSProcess[] processes = os.getProcesses(0, null);
Set<Integer> zeroChildSet = new HashSet<>();
Set<Integer> oneChildSet = new HashSet<>();
Set<Integer> manyChildSet = new HashSet<>();
// Initialize all processes with no children
for (OSProcess p : processes) {
zeroChildSet.add(p.getProcessID());
}
// Move parents with 1 or more children to other set
for (OSProcess p : processes) {
if (zeroChildSet.contains(p.getParentProcessID())) {
// Zero to One
zeroChildSet.remove(p.getParentProcessID());
oneChildSet.add(p.getParentProcessID());
} else if (oneChildSet.contains(p.getParentProcessID())) {
// One to many
oneChildSet.remove(p.getParentProcessID());
manyChildSet.add(p.getParentProcessID());
}
}
// Now test that majority of each set is in same category
int matched = 0;
int total = 0;
for (Integer i : zeroChildSet) {
if (os.getChildProcesses(i, 0, null).length == 0) {
matched++;
}
// Quit if enough to test
if (++total > 9) {
break;
}
}
if (total > 4) {
assertTrue("Most processes with no children should not suddenly have them.", matched > total / 2);
}
matched = 0;
total = 0;
for (Integer i : oneChildSet) {
if (os.getChildProcesses(i, 0, null).length == 1) {
matched++;
}
// Quit if enough to test
if (++total > 9) {
break;
}
}
if (total > 4) {
assertTrue("Most processes with one child should not suddenly have zero or more than one.",
matched > total / 2);
}
matched = 0;
total = 0;
for (Integer i : manyChildSet) {
if (os.getChildProcesses(i, 0, null).length > 1) {
matched++;
}
// Quit if enough to test
if (++total > 9) {
break;
}
}
if (total > 4) {
assertTrue("Most processes with more than one child should not suddenly have one or less.",
matched > total / 2);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject,
String perfWmiClass) {
Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject);
if (valueMap.isEmpty()) {
return queryValuesFromWMI(propertyEnum, perfWmiClass);
}
return valueMap;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static <T extends Enum<T>> Map<T, Long> queryValues(Class<T> propertyEnum, String perfObject,
String perfWmiClass) {
// Check without locking for performance
if (!failedQueryCache.contains(perfObject)) {
failedQueryCacheLock.lock();
try {
// Double check lock
if (!failedQueryCache.contains(perfObject)) {
Map<T, Long> valueMap = queryValuesFromPDH(propertyEnum, perfObject);
if (!valueMap.isEmpty()) {
return valueMap;
}
// If we are here, query failed
LOG.warn("Disabling further attempts to query {}.", perfObject);
failedQueryCache.add(perfObject);
}
} finally {
failedQueryCacheLock.unlock();
}
}
return queryValuesFromWMI(propertyEnum, perfWmiClass);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public long[][] queryProcessorCpuLoadTicks() {
long[][] ticks = CpuStat.getProcessorCpuLoadTicks(getLogicalProcessorCount());
// convert the Linux Jiffies to Milliseconds.
long hz = LinuxOperatingSystem.getHz();
for (int i = 0; i < ticks.length; i++) {
for (int j = 0; j < ticks[i].length; j++) {
ticks[i][j] = ticks[i][j] * 1000L / hz;
}
}
return ticks;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
public long[][] queryProcessorCpuLoadTicks() {
long[][] ticks = CpuStat.getProcessorCpuLoadTicks(getLogicalProcessorCount());
// In rare cases, /proc/stat reading fails. If so, try again.
// In theory we should check all of them, but on failure we can expect all 0's
// so we only need to check for processor 0
if (LongStream.of(ticks[0]).sum() == 0) {
ticks = CpuStat.getProcessorCpuLoadTicks(getLogicalProcessorCount());
}
// convert the Linux Jiffies to Milliseconds.
long hz = LinuxOperatingSystem.getHz();
for (int i = 0; i < ticks.length; i++) {
for (int j = 0; j < ticks[i].length; j++) {
ticks[i][j] = ticks[i][j] * 1000L / hz;
}
}
return ticks;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public OSFileStore[] getFileStores() {
// Use getfsstat to map filesystem paths to types
Map<String, String> fstype = new HashMap<>();
// Query with null to get total # required
int numfs = SystemB.INSTANCE.getfsstat64(null, 0, 0);
if (numfs > 0) {
// Create array to hold results
Statfs[] fs = new Statfs[numfs];
// Fill array with results
numfs = SystemB.INSTANCE.getfsstat64(fs, numfs * (new Statfs()).size(), SystemB.MNT_NOWAIT);
for (int f = 0; f < numfs; f++) {
// Mount to name will match canonical path.
// Byte arrays are null-terminated strings
fstype.put(new String(fs[f].f_mntonname).trim(), new String(fs[f].f_fstypename).trim());
}
}
// Now list file systems
List<OSFileStore> fsList = new ArrayList<>();
FileSystemView fsv = FileSystemView.getFileSystemView();
// Mac file systems are mounted in /Volumes
File volumes = new File("/Volumes");
if (volumes != null) {
for (File f : volumes.listFiles()) {
// Everyone hates DS Store
if (f.getName().endsWith(".DS_Store")) {
continue;
}
String name = fsv.getSystemDisplayName(f);
String description = "Volume";
String type = "unknown";
try {
String cp = f.getCanonicalPath();
if (cp.equals("/"))
name = name + " (/)";
FileStore fs = Files.getFileStore(f.toPath());
if (localDisk.matcher(fs.name()).matches()) {
description = "Local Disk";
}
if (fs.name().startsWith("localhost:") || fs.name().startsWith("//")) {
description = "Network Drive";
}
if (fstype.containsKey(cp)) {
type = fstype.get(cp);
}
} catch (IOException e) {
LOG.trace("", e);
continue;
}
fsList.add(new OSFileStore(name, description, type, f.getUsableSpace(), f.getTotalSpace()));
}
}
return fsList.toArray(new OSFileStore[fsList.size()]);
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
public OSFileStore[] getFileStores() {
// Use getfsstat to map filesystem paths to types
Map<String, String> fstype = new HashMap<>();
// Query with null to get total # required
int numfs = SystemB.INSTANCE.getfsstat64(null, 0, 0);
if (numfs > 0) {
// Create array to hold results
Statfs[] fs = new Statfs[numfs];
// Fill array with results
numfs = SystemB.INSTANCE.getfsstat64(fs, numfs * (new Statfs()).size(), SystemB.MNT_NOWAIT);
for (int f = 0; f < numfs; f++) {
// Mount to name will match canonical path.
// Byte arrays are null-terminated strings
fstype.put(new String(fs[f].f_mntonname).trim(), new String(fs[f].f_fstypename).trim());
}
}
// Now list file systems
List<OSFileStore> fsList = new ArrayList<>();
FileSystemView fsv = FileSystemView.getFileSystemView();
// Mac file systems are mounted in /Volumes
File volumes = new File("/Volumes");
if (volumes != null && volumes.listFiles() != null) {
for (File f : volumes.listFiles()) {
// Everyone hates DS Store
if (f.getName().endsWith(".DS_Store")) {
continue;
}
String name = fsv.getSystemDisplayName(f);
String description = "Volume";
String type = "unknown";
try {
String cp = f.getCanonicalPath();
if (cp.equals("/"))
name = name + " (/)";
FileStore fs = Files.getFileStore(f.toPath());
if (localDisk.matcher(fs.name()).matches()) {
description = "Local Disk";
}
if (fs.name().startsWith("localhost:") || fs.name().startsWith("//")) {
description = "Network Drive";
}
if (fstype.containsKey(cp)) {
type = fstype.get(cp);
}
} catch (IOException e) {
LOG.trace("", e);
continue;
}
fsList.add(new OSFileStore(name, description, type, f.getUsableSpace(), f.getTotalSpace()));
}
}
return fsList.toArray(new OSFileStore[fsList.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public double getCpuTemperature() {
ArrayList<String> hwInfo = ExecutingCommand.runNative("wmic Temperature get CurrentReading");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) {
continue;
} else {
// If successful this line is in tenths of degrees Kelvin
try {
int tempK = Integer.parseInt(checkLine.trim());
if (tempK > 0) {
return (tempK - 2715) / 10d;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
// Above query failed, try something else
hwInfo = ExecutingCommand
.runNative("wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currenttemperature")) {
continue;
} else {
// If successful this line is in tenths of degrees Kelvin
try {
int tempK = Integer.parseInt(checkLine.trim());
if (tempK > 0) {
return (tempK - 2715) / 10d;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
// Above query failed, try something else
hwInfo = ExecutingCommand
.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe get CurrentReading");
for (String checkLine : hwInfo) {
if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) {
continue;
} else {
// If successful this line is in tenths of degrees Kelvin
try {
int tempK = Integer.parseInt(checkLine.trim());
if (tempK > 0) {
return (tempK - 2715) / 10d;
}
} catch (NumberFormatException e) {
// If we failed to parse, give up
}
break;
}
}
return 0d;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public double getCpuTemperature() {
// Initialize
double tempC = 0d;
// If Open Hardware Monitor identifier is set, we couldn't get through
// normal WMI, and got ID from OHM at least once so go directly to OHM
if (this.tempIdentifierStr != null) {
double[] vals = wmiGetValuesForKeys("/namespace:\\\\root\\OpenHardwareMonitor PATH Sensor",
this.tempIdentifierStr, "Temperature", "Parent,SensorType,Value");
if (vals.length > 0) {
double sum = 0;
for (double val : vals) {
sum += val;
}
tempC = sum / vals.length;
}
return tempC;
}
// This branch is used the first time and all subsequent times if
// successful (tempIdenifierStr == null)
// Try to get value using initial or updated successful values
int tempK = 0;
if (this.wmiTempPath == null) {
this.wmiTempPath = "Temperature";
this.wmiTempProperty = "CurrentReading";
tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty);
if (tempK < 0) {
this.wmiTempPath = "/namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe";
tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty);
}
if (tempK < 0) {
this.wmiTempPath = "/namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature";
this.wmiTempProperty = "CurrentTemperature";
tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty);
}
} else {
// We've successfully read a previous time, or failed both here and
// with OHM
tempK = wmiGetValue(this.wmiTempPath, this.wmiTempProperty);
}
// Convert K to C and return result
if (tempK > 0) {
tempC = (tempK / 10d) - 273.15;
}
if (tempC <= 0d) {
// Unable to get temperature via WMI. Future attempts will be
// attempted via Open Hardware Monitor WMI if successful
String[] cpuIdentifiers = wmiGetStrValuesForKey("/namespace:\\\\root\\OpenHardwareMonitor PATH Hardware",
"CPU", "HardwareType,Identifier");
if (cpuIdentifiers.length > 0) {
this.tempIdentifierStr = cpuIdentifiers[0];
}
// If not null, recurse and get value via OHM
if (this.tempIdentifierStr != null) {
return getCpuTemperature();
}
}
return tempC;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public long[] querySystemCpuLoadTicks() {
long[] ticks = new long[TickType.values().length];
WinBase.FILETIME lpIdleTime = new WinBase.FILETIME();
WinBase.FILETIME lpKernelTime = new WinBase.FILETIME();
WinBase.FILETIME lpUserTime = new WinBase.FILETIME();
if (!Kernel32.INSTANCE.GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime)) {
LOG.error("Failed to update system idle/kernel/user times. Error code: {}", Native.getLastError());
return ticks;
}
// IOwait:
// Windows does not measure IOWait.
// IRQ and ticks:
// Percent time raw value is cumulative 100NS-ticks
// Divide by 10_000 to get milliseconds
Map<SystemTickCountProperty, Long> valueMap = ProcessorInformation.querySystemCounters();
ticks[TickType.IRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTINTERRUPTTIME, 0L)
/ 10_000L;
ticks[TickType.SOFTIRQ.getIndex()] = valueMap.getOrDefault(SystemTickCountProperty.PERCENTDPCTIME, 0L)
/ 10_000L;
ticks[TickType.IDLE.getIndex()] = lpIdleTime.toDWordLong().longValue() / 10_000L;
ticks[TickType.SYSTEM.getIndex()] = lpKernelTime.toDWordLong().longValue() / 10_000L
- ticks[TickType.IDLE.getIndex()];
ticks[TickType.USER.getIndex()] = lpUserTime.toDWordLong().longValue() / 10_000L;
// Additional decrement to avoid double counting in the total array
ticks[TickType.SYSTEM.getIndex()] -= ticks[TickType.IRQ.getIndex()] + ticks[TickType.SOFTIRQ.getIndex()];
return ticks;
}
#location 18
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
public long[] querySystemCpuLoadTicks() {
// To get load in processor group scenario, we need perfmon counters, but the
// _Total instance is an average rather than total (scaled) number of ticks
// which matches GetSystemTimes() results. We can just query the per-processor
// ticks and add them up. Calling the get() method gains the benefit of
// synchronizing this output with the memoized result of per-processor ticks as
// well.
long[] ticks = new long[TickType.values().length];
// Sum processor ticks
long[][] procTicks = getProcessorCpuLoadTicks();
for (int i = 0; i < ticks.length; i++) {
for (long[] procTick : procTicks) {
ticks[i] += procTick[i];
}
}
return ticks;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populateReadWriteMaps() {
// Although the field names say "PerSec" this is the Raw Data from which
// the associated fields are populated in the Formatted Data class, so
// in fact this is the data we want
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk",
"Name,DiskReadBytesPerSec,DiskWriteBytesPerSec", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
String index = vals.get("Name").get(i).split("\\s+")[0];
readMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskReadBytesPerSec").get(i), 0L));
writeMap.put(index, ParseUtil.parseLongOrDefault(vals.get("DiskWriteBytesPerSec").get(i), 0L));
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populateReadWriteMaps() {
// Although the field names say "PerSec" this is the Raw Data from which
// the associated fields are populated in the Formatted Data class, so
// in fact this is the data we want
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_PerfRawData_PerfDisk_PhysicalDisk",
"Name,DiskReadsPerSec,DiskReadBytesPerSec,DiskWritesPerSec,DiskWriteBytesPerSec,PercentDiskTime", null,
READ_WRITE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
String index = ((String) vals.get("Name").get(i)).split("\\s+")[0];
readMap.put(index, (long) vals.get("DiskReadsPerSec").get(i));
readByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskReadBytesPerSec").get(i), 0L));
writeMap.put(index, (long) vals.get("DiskWritesPerSec").get(i));
writeByteMap.put(index, ParseUtil.parseLongOrDefault((String) vals.get("DiskWriteBytesPerSec").get(i), 0L));
// Units are 100-ns, divide to get ms
xferTimeMap.put(index,
ParseUtil.parseLongOrDefault((String) vals.get("PercentDiskTime").get(i), 0L) / 10000L);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private DmidecodeStrings readDmiDecode() {
String manufacturer = null;
String version = null;
String releaseDate = null;
// $ sudo dmidecode -t bios
// # dmidecode 3.0
// Scanning /dev/mem for entry point.
// SMBIOS 2.7 present.
//
// Handle 0x0000, DMI type 0, 24 bytes
// BIOS Information
// Vendor: Parallels Software International Inc.
// Version: 11.2.1 (32626)
// Release Date: 07/15/2016
// ... <snip> ...
// BIOS Revision: 11.2
// Firmware Revision: 11.2
final String manufacturerMarker = "Vendor:";
final String versionMarker = "Version:";
final String releaseDateMarker = "Release Date:";
// Only works with root permissions but it's all we've got
for (final String checkLine : ExecutingCommand.runNative("dmidecode -t bios")) {
if (checkLine.contains(manufacturerMarker)) {
manufacturer = checkLine.split(manufacturerMarker)[1].trim();
} else if (checkLine.contains(versionMarker)) {
version = checkLine.split(versionMarker)[1].trim();
} else if (checkLine.contains(releaseDateMarker)) {
releaseDate = checkLine.split(releaseDateMarker)[1].trim();
}
}
releaseDate = ParseUtil.parseMmDdYyyyToYyyyMmDD(releaseDate);
return new DmidecodeStrings(manufacturer, version, releaseDate);
}
#location 34
#vulnerability type NULL_DEREFERENCE | #fixed code
private DmidecodeStrings readDmiDecode() {
String manufacturer = null;
String version = null;
String releaseDate = "";
// $ sudo dmidecode -t bios
// # dmidecode 3.0
// Scanning /dev/mem for entry point.
// SMBIOS 2.7 present.
//
// Handle 0x0000, DMI type 0, 24 bytes
// BIOS Information
// Vendor: Parallels Software International Inc.
// Version: 11.2.1 (32626)
// Release Date: 07/15/2016
// ... <snip> ...
// BIOS Revision: 11.2
// Firmware Revision: 11.2
final String manufacturerMarker = "Vendor:";
final String versionMarker = "Version:";
final String releaseDateMarker = "Release Date:";
// Only works with root permissions but it's all we've got
for (final String checkLine : ExecutingCommand.runNative("dmidecode -t bios")) {
if (checkLine.contains(manufacturerMarker)) {
manufacturer = checkLine.split(manufacturerMarker)[1].trim();
} else if (checkLine.contains(versionMarker)) {
version = checkLine.split(versionMarker)[1].trim();
} else if (checkLine.contains(releaseDateMarker)) {
releaseDate = checkLine.split(releaseDateMarker)[1].trim();
}
}
releaseDate = ParseUtil.parseMmDdYyyyToYyyyMmDD(releaseDate);
return new DmidecodeStrings(manufacturer, version, releaseDate);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must equal properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
enumerator.Release();
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
switch (propertyTypes[p]) {
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
case LONG: // WinDef.LONG
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here!
LOG.error("Unimplemented enum type.");
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
enumerator.Release();
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
case LONG: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here!
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void updateSwap() {
updateMeminfo();
Map<String, List<Long>> usage = WmiUtil.selectUint32sFrom(null, "Win32_PerfRawData_PerfOS_PagingFile",
"PercentUsage,PercentUsage_Base", "WHERE Name=\"_Total\"");
if (!usage.get("PercentUsage").isEmpty()) {
this.swapUsed = this.swapTotal * usage.get("PercentUsage").get(0) / usage.get("PercentUsage_Base").get(0);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void updateSwap() {
updateMeminfo();
this.swapUsed = PdhUtil.queryCounter(pdhPagingPercentUsageCounter) * this.pageSize;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public long getTotal() {
if (totalMemory == 0) {
Scanner in = null;
try {
in = new Scanner(new FileReader("/proc/meminfo"));
} catch (FileNotFoundException e) {
totalMemory = 0;
return totalMemory;
}
in.useDelimiter("\n");
while (in.hasNext()) {
String checkLine = in.next();
if (checkLine.startsWith("MemTotal:")) {
String[] memorySplit = checkLine.split("\\s+");
totalMemory = parseMeminfo(memorySplit);
break;
}
}
in.close();
}
return totalMemory;
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public long getTotal() {
if (totalMemory == 0) {
Sysinfo info = new Sysinfo();
if (0 != Libc.INSTANCE.sysinfo(info))
throw new LastErrorException("Error code: "
+ Native.getLastError());
totalMemory = info.totalram.longValue() * info.mem_unit;
}
return totalMemory;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static UsbDevice[] getUsbDevices() {
// Get heirarchical list of USB devices
List<String> xml = ExecutingCommand.runNative("system_profiler SPUSBDataType -xml");
// Look for <key>_items</key> which prcedes <array> ... </array>
// Each pair of <dict> ... </dict> following is a USB device/hub
List<String> items = new ArrayList<>();
boolean copy = false;
int indent = 0;
for (String s : xml) {
s = s.trim();
// Read until <key>_items</key>
if (!copy && s.equals("<key>_items</key>")) {
copy = true;
continue;
}
// If we've fond items indent with each <array> tag and copy over
// everything with indent > 0.
if (copy) {
if (s.equals("</array>")) {
if (--indent == 0) {
copy = false;
continue;
}
}
if (indent > 0) {
items.add(s);
}
if (s.equals("<array>")) {
indent++;
}
}
}
// Items now contains 0 or more sets of <dict>...</dict>
return getUsbDevices(items);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static UsbDevice[] getUsbDevices() {
// Reusable buffer for getting IO name strings
Pointer buffer = new Memory(128); // io_name_t is char[128]
// Build a list of devices with no parent; these will be the roots
List<Long> usbControllers = new ArrayList<>();
// Empty out maps
nameMap.clear();
vendorMap.clear();
serialMap.clear();
hubMap.clear();
// Iterate over USB Controllers. All devices are children of one of
// these controllers in the "IOService" plane
IntByReference iter = new IntByReference();
IOKitUtil.getMatchingServices("IOUSBController", iter);
int device = IOKit.INSTANCE.IOIteratorNext(iter.getValue());
while (device != 0) {
// Unique global identifier for this device
LongByReference id = new LongByReference();
IOKit.INSTANCE.IORegistryEntryGetRegistryEntryID(device, id);
usbControllers.add(id.getValue());
// Get device name and store in map
IOKit.INSTANCE.IORegistryEntryGetName(device, buffer);
nameMap.put(id.getValue(), buffer.getString(0));
// Controllers don't have vendor and serial so ignore at this level
// Now iterate the children of this device in the "IOService" plane.
// If devices have a parent, link to that parent, otherwise link to
// the controller as parent
IntByReference childIter = new IntByReference();
IOKit.INSTANCE.IORegistryEntryGetChildIterator(device, "IOService", childIter);
int childDevice = IOKit.INSTANCE.IOIteratorNext(childIter.getValue());
while (childDevice != 0) {
// Unique global identifier for this device
LongByReference childId = new LongByReference();
IOKit.INSTANCE.IORegistryEntryGetRegistryEntryID(childDevice, childId);
// Get this device's parent in the "IOUSB" plane
IntByReference parent = new IntByReference();
IOKit.INSTANCE.IORegistryEntryGetParentEntry(childDevice, "IOUSB", parent);
// If parent is named "Root" ignore that id and use the
// controller's id
LongByReference parentId = id;
IOKit.INSTANCE.IORegistryEntryGetName(parent.getValue(), buffer);
if (!buffer.getString(0).equals("Root")) {
// Unique global identifier for the parent
parentId = new LongByReference();
IOKit.INSTANCE.IORegistryEntryGetRegistryEntryID(parent.getValue(), parentId);
}
// Store parent in map
if (!hubMap.containsKey(parentId.getValue())) {
hubMap.put(parentId.getValue(), new ArrayList<Long>());
}
hubMap.get(parentId.getValue()).add(childId.getValue());
// Get device name and store in map
IOKit.INSTANCE.IORegistryEntryGetName(childDevice, buffer);
nameMap.put(childId.getValue(), buffer.getString(0));
// Get vendor and store in map
CFTypeRef vendorRef = IOKit.INSTANCE.IORegistryEntryCreateCFProperty(childDevice, cfVendor,
CfUtil.ALLOCATOR, 0);
if (vendorRef != null && vendorRef.getPointer() != null) {
vendorMap.put(childId.getValue(), CfUtil.cfPointerToString(vendorRef.getPointer()));
}
CfUtil.release(vendorRef);
// Get serial and store in map
CFTypeRef serialRef = IOKit.INSTANCE.IORegistryEntryCreateCFProperty(childDevice, cfSerial,
CfUtil.ALLOCATOR, 0);
if (serialRef != null && serialRef.getPointer() != null) {
serialMap.put(childId.getValue(), CfUtil.cfPointerToString(serialRef.getPointer()));
}
CfUtil.release(serialRef);
IOKit.INSTANCE.IOObjectRelease(childDevice);
childDevice = IOKit.INSTANCE.IOIteratorNext(childIter.getValue());
}
IOKit.INSTANCE.IOObjectRelease(childIter.getValue());
IOKit.INSTANCE.IOObjectRelease(device);
device = IOKit.INSTANCE.IOIteratorNext(iter.getValue());
}
IOKit.INSTANCE.IOObjectRelease(iter.getValue());
// Build tree and return
List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>();
for (Long controller : usbControllers) {
controllerDevices.add(getDeviceAndChildren(controller));
}
return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ArrayList<String> runNative(String[] cmdToRunWithArgs) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRunWithArgs);
} catch (IOException e) {
LOG.trace("", e);
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
p.waitFor();
} catch (InterruptedException e) {
LOG.trace("", e);
return null;
} catch (IOException e) {
LOG.trace("", e);
return null;
}
return sa;
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public static ArrayList<String> runNative(String[] cmdToRunWithArgs) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRunWithArgs);
} catch (IOException e) {
LOG.trace("", e);
return null;
}
ArrayList<String> sa = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
sa.add(line);
}
p.waitFor();
} catch (InterruptedException e) {
LOG.trace("", e);
return null;
} catch (IOException e) {
LOG.trace("", e);
return null;
}
return sa;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String getFamily() {
if (this._family == null) {
try (final Scanner in = new Scanner(new FileReader("/etc/os-release"))) {
in.useDelimiter("\n");
while (in.hasNext()) {
String[] splittedLine = in.next().split("=");
if (splittedLine[0].equals("NAME")) {
// remove beginning and ending '"' characters, etc from
// NAME="Ubuntu"
this._family = splittedLine[1].replaceAll("^\"|\"$", "");
break;
}
}
} catch (FileNotFoundException e) {
LOG.trace("", e);
return "";
}
}
return this._family;
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public String getFamily() {
if (this._family == null) {
String etcOsRelease = getReleaseFilename();
try {
this.osRelease = FileUtil.readFile(etcOsRelease);
for (String line : this.osRelease) {
String[] splittedLine = line.split("=");
if ((splittedLine[0].equals("NAME") || splittedLine[0].equals("DISTRIB_ID"))
&& splittedLine.length > 1) {
// remove beginning and ending '"' characters, etc from
// NAME="Ubuntu"
this._family = splittedLine[1].replaceAll("^\"|\"$", "");
break;
}
}
// If we've gotten to the end without matching, use the filename
if (this._family == null) {
this._family = etcOsRelease.replace("/etc/", "").replace("release", "").replace("version", "")
.replace("-", "");
}
} catch (IOException e) {
LOG.trace("", e);
return "";
}
}
return this._family;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 26
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean updateAttributes() {
try {
File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName()));
if (!ifDir.isDirectory()) {
return false;
}
} catch (SecurityException e) {
return false;
}
String ifTypePath = String.format("/sys/class/net/%s/type", getName());
String carrierPath = String.format("/sys/class/net/%s/carrier", getName());
String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName());
String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName());
String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName());
String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName());
String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName());
String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName());
String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName());
String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName());
String ifSpeed = String.format("/sys/class/net/%s/speed", getName());
this.timeStamp = System.currentTimeMillis();
this.ifType = FileUtil.getIntFromFile(ifTypePath);
this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0;
this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath);
this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath);
this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath);
this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath);
this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath);
this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath);
this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath);
this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath);
// speed may be negative from file. Convert to MiB.
this.speed = FileUtil.getUnsignedLongFromFile(ifSpeed);
this.speed = this.speed < 0 ? 0 : this.speed << 20;
return true;
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public boolean updateAttributes() {
try {
File ifDir = new File(String.format("/sys/class/net/%s/statistics", getName()));
if (!ifDir.isDirectory()) {
return false;
}
} catch (SecurityException e) {
return false;
}
String ifTypePath = String.format("/sys/class/net/%s/type", getName());
String carrierPath = String.format("/sys/class/net/%s/carrier", getName());
String txBytesPath = String.format("/sys/class/net/%s/statistics/tx_bytes", getName());
String rxBytesPath = String.format("/sys/class/net/%s/statistics/rx_bytes", getName());
String txPacketsPath = String.format("/sys/class/net/%s/statistics/tx_packets", getName());
String rxPacketsPath = String.format("/sys/class/net/%s/statistics/rx_packets", getName());
String txErrorsPath = String.format("/sys/class/net/%s/statistics/tx_errors", getName());
String rxErrorsPath = String.format("/sys/class/net/%s/statistics/rx_errors", getName());
String collisionsPath = String.format("/sys/class/net/%s/statistics/collisions", getName());
String rxDropsPath = String.format("/sys/class/net/%s/statistics/rx_dropped", getName());
String ifSpeed = String.format("/sys/class/net/%s/speed", getName());
this.timeStamp = System.currentTimeMillis();
this.ifType = FileUtil.getIntFromFile(ifTypePath);
this.connectorPresent = FileUtil.getIntFromFile(carrierPath) > 0;
this.bytesSent = FileUtil.getUnsignedLongFromFile(txBytesPath);
this.bytesRecv = FileUtil.getUnsignedLongFromFile(rxBytesPath);
this.packetsSent = FileUtil.getUnsignedLongFromFile(txPacketsPath);
this.packetsRecv = FileUtil.getUnsignedLongFromFile(rxPacketsPath);
this.outErrors = FileUtil.getUnsignedLongFromFile(txErrorsPath);
this.inErrors = FileUtil.getUnsignedLongFromFile(rxErrorsPath);
this.collisions = FileUtil.getUnsignedLongFromFile(collisionsPath);
this.inDrops = FileUtil.getUnsignedLongFromFile(rxDropsPath);
long speedMiB = FileUtil.getUnsignedLongFromFile(ifSpeed);
// speed may be -1 from file.
this.speed = speedMiB < 0 ? 0 : speedMiB << 20;
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 35
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Memory sysctl(String name) {
IntByReference size = new IntByReference();
if (0 != SystemB.INSTANCE.sysctlbyname(name, null, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
Memory m = new Memory(size.getValue());
if (0 != SystemB.INSTANCE.sysctlbyname(name, m, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
return m;
}
#location 8
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static Memory sysctl(String name) {
IntByReference size = new IntByReference();
if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, null, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
Memory m = new Memory(size.getValue());
if (0 != FreeBsdLibc.INSTANCE.sysctlbyname(name, m, size, null, 0)) {
LOG.error(SYSCTL_FAIL, name, Native.getLastError());
return null;
}
return m;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues(
Class<T> propertyEnum, String perfObject, String perfWmiClass) {
Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(propertyEnum,
perfObject);
if (instancesAndValuesMap.getA().isEmpty()) {
return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass);
}
return instancesAndValuesMap;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues(
Class<T> propertyEnum, String perfObject, String perfWmiClass) {
// Check without locking for performance
if (!failedQueryCache.contains(perfObject)) {
failedQueryCacheLock.lock();
try {
// Double check lock
if (!failedQueryCache.contains(perfObject)) {
Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(
propertyEnum, perfObject);
if (!instancesAndValuesMap.getA().isEmpty()) {
return instancesAndValuesMap;
}
// If we are here, query failed
LOG.warn("Disabling further attempts to query {}.", perfObject);
failedQueryCache.add(perfObject);
}
} finally {
failedQueryCacheLock.unlock();
}
}
return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public OSService[] getServices() {
// Get running services
List<OSService> services = new ArrayList<>();
Set<String> running = new HashSet<>();
for (OSProcess p : getChildProcesses(1, 0, ProcessSort.PID)) {
OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING);
services.add(s);
running.add(p.getName());
}
// Get Directories for stopped services
File dir = new File("/etc/rc.d");
if (dir.exists() && dir.isDirectory()) {
for (File f : dir.listFiles()) {
String name = f.getName();
if (!running.contains(name)) {
OSService s = new OSService(name, 0, STOPPED);
services.add(s);
}
}
} else {
LOG.error("Directory: /etc/init does not exist");
}
return services.toArray(new OSService[0]);
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public OSService[] getServices() {
// Get running services
List<OSService> services = new ArrayList<>();
Set<String> running = new HashSet<>();
for (OSProcess p : getChildProcesses(1, 0, ProcessSort.PID)) {
OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING);
services.add(s);
running.add(p.getName());
}
// Get Directories for stopped services
File dir = new File("/etc/rc.d");
File[] listFiles;
if (dir.exists() && dir.isDirectory() && (listFiles = dir.listFiles()) != null) {
for (File f : listFiles) {
String name = f.getName();
if (!running.contains(name)) {
OSService s = new OSService(name, 0, STOPPED);
services.add(s);
}
}
} else {
LOG.error("Directory: /etc/init does not exist");
}
return services.toArray(new OSService[0]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<String>> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition",
DRIVE_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition",
LOGICAL_DISK_TO_PARTITION_PROPERTIES, null);
for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) {
mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i));
mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_PROPERTIES, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap.put(deviceID,
new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i),
(String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid,
ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L),
((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive));
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
private void populatePartitionMaps() {
driveToPartitionMap.clear();
partitionToLogicalDriveMap.clear();
partitionMap.clear();
// For Regexp matching DeviceIDs
Matcher mAnt;
Matcher mDep;
// Map drives to partitions
Map<String, List<Object>> partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskDriveToDiskPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\"))
.add(mDep.group(1));
}
}
// Map partitions to logical disks
partitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDiskToPartition",
DISK_TO_PARTITION_STRINGS, null, DISK_TO_PARTITION_TYPES);
for (int i = 0; i < partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).size(); i++) {
mAnt = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.ANTECEDENT.name()).get(i));
mDep = DEVICE_ID.matcher((String) partitionQueryMap.get(WmiProperty.DEPENDENT.name()).get(i));
if (mAnt.matches() && mDep.matches()) {
partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\");
}
}
// Next, get all partitions and create objects
final Map<String, List<Object>> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition",
PARTITION_STRINGS, null, PARTITION_TYPES);
for (int i = 0; i < hwPartitionQueryMap.get(WmiProperty.NAME.name()).size(); i++) {
String deviceID = (String) hwPartitionQueryMap.get(WmiProperty.DEVICEID.name()).get(i);
String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, "");
String uuid = "";
if (!logicalDrive.isEmpty()) {
// Get matching volume for UUID
char[] volumeChr = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE);
uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), "");
}
partitionMap
.put(deviceID,
new HWPartition(
(String) hwPartitionQueryMap
.get(WmiProperty.NAME.name()).get(
i),
(String) hwPartitionQueryMap.get(WmiProperty.TYPE.name()).get(i),
(String) hwPartitionQueryMap.get(WmiProperty.DESCRIPTION.name()).get(i), uuid,
(Long) hwPartitionQueryMap.get(WmiProperty.SIZE.name()).get(i),
((Long) hwPartitionQueryMap.get(WmiProperty.DISKINDEX.name()).get(i)).intValue(),
((Long) hwPartitionQueryMap.get(WmiProperty.INDEX.name()).get(i)).intValue(),
logicalDrive));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes, WbemServices svc) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// uint16 == VT_I4, a 32-bit number
case UINT16:
values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.intValue());
break;
// WMI Uint32s will return as longs
case UINT32:
values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.longValue());
break;
// WMI Longs will return as strings so we have the option of
// calling a string and parsing later, or calling UINT64 and
// letting this method do the parsing
case UINT64:
values.get(property).add(
vtProp.getValue() == null ? 0L : ParseUtil.parseLongOrDefault(vtProp.stringValue(), 0L));
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property)
.add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
case BOOLEAN:
values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.booleanValue());
break;
case PROCESS_GETOWNER:
// Win32_Process object GetOwner method
String owner = FormatUtil.join("\\",
execMethod(svc, vtProp.stringValue(), "GetOwner", "Domain", "User"));
values.get(propertyType.name()).add("\\".equals(owner) ? "N/A" : owner);
break;
case PROCESS_GETOWNERSID:
// Win32_Process object GetOwnerSid method
String[] ownerSid = execMethod(svc, vtProp.stringValue(), "GetOwnerSid", "Sid");
values.get(propertyType.name()).add(ownerSid.length < 1 ? "" : ownerSid[0]);
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp);
}
clsObj.Release();
}
}
#location 30
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes, WbemServices svc) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
int resultCount = 0;
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
LOG.debug(String.format("Returned %d results.", resultCount));
return;
}
resultCount++;
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
// hres =
clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// uint16 == VT_I4, a 32-bit number
case UINT16:
values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.intValue());
break;
// WMI Uint32s will return as longs
case UINT32:
values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.longValue());
break;
// WMI Longs will return as strings so we have the option of
// calling a string and parsing later, or calling UINT64 and
// letting this method do the parsing
case UINT64:
values.get(property).add(
vtProp.getValue() == null ? 0L : ParseUtil.parseLongOrDefault(vtProp.stringValue(), 0L));
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property)
.add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
case BOOLEAN:
values.get(property).add(vtProp.getValue() == null ? 0L : vtProp.booleanValue());
break;
case PROCESS_GETOWNER:
// Win32_Process object GetOwner method
String owner = FormatUtil.join("\\",
execMethod(svc, vtProp.stringValue(), "GetOwner", "Domain", "User"));
values.get(propertyType.name()).add("\\".equals(owner) ? "N/A" : owner);
break;
case PROCESS_GETOWNERSID:
// Win32_Process object GetOwnerSid method
String[] ownerSid = execMethod(svc, vtProp.stringValue(), "GetOwnerSid", "Sid");
values.get(propertyType.name()).add(ownerSid.length < 1 ? "" : ownerSid[0]);
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp);
}
clsObj.Release();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<String>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectStringsFrom(null, "Win32_LogicalDisk",
"Name,Description,ProviderName,FileSystem,Freespace,Size", null);
for (int i = 0; i < drives.get("Name").size(); i++) {
free = ParseUtil.parseLongOrDefault(drives.get("Freespace").get(i), 0L);
total = ParseUtil.parseLongOrDefault(drives.get("Size").get(i), 0L);
String description = drives.get("Description").get(i);
long type = WmiUtil.selectUint32From(null, "Win32_LogicalDisk", "DriveType",
"WHERE Name = '" + drives.get("Name").get(i) + "'");
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(drives.get("Name").get(i) + "\\", chrVolume,
BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = drives.get("ProviderName").get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, drives.get("Name").get(i)), volume,
drives.get("Name").get(i) + "\\", getDriveType(drives.get("Name").get(i)),
drives.get("FileSystem").get(i), "", free, total));
}
return fs;
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<OSFileStore> getWmiVolumes() {
Map<String, List<Object>> drives;
List<OSFileStore> fs;
String volume;
long free;
long total;
fs = new ArrayList<>();
drives = WmiUtil.selectObjectsFrom(null, "Win32_LogicalDisk", FS_PROPERTIES, null, FS_TYPES);
for (int i = 0; i < drives.get(NAME_PROPERTY).size(); i++) {
free = (Long) drives.get(FREESPACE_PROPERTY).get(i);
total = (Long) drives.get(SIZE_PROPERTY).get(i);
String description = (String) drives.get(DESCRIPTION_PROPERTY).get(i);
String name = (String) drives.get(NAME_PROPERTY).get(i);
long type = (Long) drives.get(DRIVE_TYPE_PROPERTY).get(i);
if (type != 4) {
char[] chrVolume = new char[BUFSIZE];
Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(name + "\\", chrVolume, BUFSIZE);
volume = new String(chrVolume).trim();
} else {
volume = (String) drives.get(PROVIDER_NAME_PROPERTY).get(i);
String[] split = volume.split("\\\\");
if (split.length > 1 && split[split.length - 1].length() > 0) {
description = split[split.length - 1];
}
}
fs.add(new OSFileStore(String.format("%s (%s)", description, name), volume, name + "\\", getDriveType(name),
(String) drives.get(FILESYSTEM_PROPERTY).get(i), "", free, total));
}
return fs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues(
Class<T> propertyEnum, String perfObject, String perfWmiClass) {
Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(propertyEnum,
perfObject);
if (instancesAndValuesMap.getA().isEmpty()) {
return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass);
}
return instancesAndValuesMap;
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public static <T extends Enum<T>> Pair<List<String>, Map<T, List<Long>>> queryInstancesAndValues(
Class<T> propertyEnum, String perfObject, String perfWmiClass) {
// Check without locking for performance
if (!failedQueryCache.contains(perfObject)) {
failedQueryCacheLock.lock();
try {
// Double check lock
if (!failedQueryCache.contains(perfObject)) {
Pair<List<String>, Map<T, List<Long>>> instancesAndValuesMap = queryInstancesAndValuesFromPDH(
propertyEnum, perfObject);
if (!instancesAndValuesMap.getA().isEmpty()) {
return instancesAndValuesMap;
}
// If we are here, query failed
LOG.warn("Disabling further attempts to query {}.", perfObject);
failedQueryCache.add(perfObject);
}
} finally {
failedQueryCacheLock.unlock();
}
}
return queryInstancesAndValuesFromWMI(propertyEnum, perfWmiClass);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static UsbDevice[] getUsbDevices() {
// Start by collecting information for all PNP devices. While in theory
// these could be individually queried with a WHERE clause, grabbing
// them all up front incurs minimal memory overhead in exchange for
// faster access later
// Clear maps
nameMap.clear();
vendorMap.clear();
serialMap.clear();
// Query Win32_PnPEntity to populate the maps
Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity",
"Name,Manufacturer,PnPDeviceID", null);
for (int i = 0; i < usbMap.get("Name").size(); i++) {
String pnpDeviceID = usbMap.get("PnPDeviceID").get(i);
nameMap.put(pnpDeviceID, usbMap.get("Name").get(i));
if (usbMap.get("Manufacturer").get(i).length() > 0) {
vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i));
}
String serialNumber = "";
// PNPDeviceID: USB\VID_203A&PID_FFF9&MI_00\6&18C4CF61&0&0000
// Split by \ to get bus type (USB), VendorID/ProductID, other info
// As a temporary hack for a serial number, use last \-split field
// using 2nd &-split field if 4 fields
String[] idSplit = pnpDeviceID.split("\\\\");
if (idSplit.length > 2) {
idSplit = idSplit[2].split("&");
if (idSplit.length > 3) {
serialNumber = idSplit[1];
}
}
if (serialNumber.length() > 0) {
serialMap.put(pnpDeviceID, serialNumber);
}
}
// Disk drives or other physical media have a better way of getting
// serial number. Grab these and overwrite the temporary serial number
// assigned above if necessary
usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
// Some USB Devices are hubs to which other devices connect. Knowing
// which ones are hubs will help later when walking the device tree
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBHub", "PNPDeviceID", null);
List<String> usbHubs = usbMap.get("PNPDeviceID");
// Now build the hub map linking USB devices with their parent hub.
// At the top of the device tree are USB Controllers. All USB hubs and
// devices descend from these. Because this query returns pointers it's
// just not practical to try to query via COM so we use a command line
// in order to get USB devices in a text format
ArrayList<String> links = ExecutingCommand
.runNative("wmic path Win32_USBControllerDevice GET Antecedent,Dependent");
// This iteration actually walks the device tree in order so while the
// antecedent of all USB devices is its controller, we know that if a
// device is not a hub that the last hub listed is its parent
// Devices with PNPDeviceID containing "ROOTHUB" are special and will be
// parents of the next item(s)
// This won't id chained hubs (other than the root hub) but is a quick
// hack rather than walking the entire device tree using the SetupDI API
// and good enough since exactly how a USB device is connected is
// theoretically transparent to the user
hubMap.clear();
String currentHub = null;
String rootHub = null;
for (String s : links) {
String[] split = s.split("\\s+");
if (split.length < 2) {
continue;
}
String antecedent = getId(split[0]);
String dependent = getId(split[1]);
// Ensure initial defaults are sane if something goes wrong
if (currentHub == null || rootHub == null) {
currentHub = antecedent;
rootHub = antecedent;
}
String parent;
if (dependent.contains("ROOT_HUB")) {
// This is a root hub, assign controller as parent;
parent = antecedent;
rootHub = dependent;
currentHub = dependent;
} else if (usbHubs.contains(dependent)) {
// This is a hub, assign parent as root hub
if (rootHub == null) {
rootHub = antecedent;
}
parent = rootHub;
currentHub = dependent;
} else {
// This is not a hub, assign parent as previous hub
if (currentHub == null) {
currentHub = antecedent;
}
parent = currentHub;
}
// Finally add the parent/child linkage to the map
if (!hubMap.containsKey(parent)) {
hubMap.put(parent, new ArrayList<String>());
}
hubMap.get(parent).add(dependent);
}
// Finally we simply get the device IDs of the USB Controllers. These
// will recurse downward to devices as needed
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null);
List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>();
for (String controllerDeviceID : usbMap.get("PNPDeviceID")) {
controllerDevices.add(getDeviceAndChildren(controllerDeviceID));
}
return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]);
}
#location 76
#vulnerability type NULL_DEREFERENCE | #fixed code
public static UsbDevice[] getUsbDevices() {
// Start by collecting information for all PNP devices. While in theory
// these could be individually queried with a WHERE clause, grabbing
// them all up front incurs minimal memory overhead in exchange for
// faster access later
// Clear maps
nameMap.clear();
vendorMap.clear();
serialMap.clear();
// Query Win32_PnPEntity to populate the maps
Map<String, List<String>> usbMap = WmiUtil.selectStringsFrom(null, "Win32_PnPEntity",
"Name,Manufacturer,PnPDeviceID", null);
for (int i = 0; i < usbMap.get("Name").size(); i++) {
String pnpDeviceID = usbMap.get("PnPDeviceID").get(i);
nameMap.put(pnpDeviceID, usbMap.get("Name").get(i));
if (usbMap.get("Manufacturer").get(i).length() > 0) {
vendorMap.put(pnpDeviceID, usbMap.get("Manufacturer").get(i));
}
}
// Get serial # for disk drives or other physical media
usbMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
usbMap = WmiUtil.selectStringsFrom(null, "Win32_PhysicalMedia", "PNPDeviceID,SerialNumber", null);
for (int i = 0; i < usbMap.get("PNPDeviceID").size(); i++) {
serialMap.put(usbMap.get("PNPDeviceID").get(i),
ParseUtil.hexStringToString(usbMap.get("PNPDeviceID").get(i)));
}
// Build the device tree. Start with the USB Controllers
// and recurse downward to devices as needed
usbMap = WmiUtil.selectStringsFrom(null, "Win32_USBController", "PNPDeviceID", null);
List<UsbDevice> controllerDevices = new ArrayList<UsbDevice>();
for (String controllerDeviceId : usbMap.get("PNPDeviceID")) {
putChildrenInDeviceTree(controllerDeviceId, 0);
controllerDevices.add(getDeviceAndChildren(controllerDeviceId));
}
return controllerDevices.toArray(new UsbDevice[controllerDevices.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
Map<String, List<String>> vals = WmiUtil.selectStringsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size", null);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName(vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString(vals.get("SerialNumber").get(i)));
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong(vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public HWDiskStore[] getDisks() {
List<HWDiskStore> result;
result = new ArrayList<>();
readMap.clear();
writeMap.clear();
populateReadWriteMaps();
Map<String, List<Object>> vals = WmiUtil.selectObjectsFrom(null, "Win32_DiskDrive",
"Name,Manufacturer,Model,SerialNumber,Size,Index", null, DRIVE_TYPES);
for (int i = 0; i < vals.get("Name").size(); i++) {
HWDiskStore ds = new HWDiskStore();
ds.setName((String) vals.get("Name").get(i));
ds.setModel(String.format("%s %s", vals.get("Model").get(i), vals.get("Manufacturer").get(i)).trim());
// Most vendors store serial # as a hex string; convert
ds.setSerial(ParseUtil.hexStringToString((String) vals.get("SerialNumber").get(i)));
String index = vals.get("Index").get(i).toString();
if (readMap.containsKey(index)) {
ds.setReads(readMap.get(index));
}
if (writeMap.containsKey(index)) {
ds.setWrites(writeMap.get(index));
}
// If successful this line is the desired value
try {
ds.setSize(Long.parseLong((String) vals.get("Size").get(i)));
} catch (NumberFormatException e) {
// If we failed to parse, give up
// This is expected for an empty string on some drives
ds.setSize(0L);
}
result.add(ds);
}
return result.toArray(new HWDiskStore[result.size()]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ArrayList<String> runNative(String cmdToRun) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRun);
//p.waitFor();
} catch (IOException e) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<String>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
} catch (IOException e) {
return null;
}
p.destroy();
return sa;
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static ArrayList<String> runNative(String cmdToRun) {
Process p = null;
try {
p = Runtime.getRuntime().exec(cmdToRun);
p.waitFor();
} catch (IOException e) {
return null;
} catch (InterruptedException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = "";
ArrayList<String> sa = new ArrayList<String>();
try {
while ((line = reader.readLine()) != null) {
sa.add(line);
}
} catch (IOException e) {
return null;
}
return sa;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
}
#location 36
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void enumerateProperties(Map<String, List<Object>> values, EnumWbemClassObject enumerator,
String[] properties, ValueType[] propertyTypes) {
if (propertyTypes.length > 1 && properties.length != propertyTypes.length) {
throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size.");
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
PointerByReference pclsObj = new PointerByReference();
LongByReference uReturn = new LongByReference(0L);
while (enumerator.getPointer() != Pointer.NULL) {
HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1),
pclsObj, uReturn);
// Requested 1; if 0 objects returned, we're done
if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) {
// Enumerator will be released by calling method so no need to
// release it here.
return;
}
VARIANT.ByReference vtProp = new VARIANT.ByReference();
// Get the value of the properties
WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue());
for (int p = 0; p < properties.length; p++) {
String property = properties[p];
hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null);
ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0];
switch (propertyType) {
// WMI Longs will return as strings
case STRING:
values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue());
break;
// WMI Uint32s will return as longs
case UINT32: // WinDef.LONG TODO improve in JNA 4.3
values.get(property)
.add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue());
break;
case FLOAT:
values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue());
break;
case DATETIME:
// Read a string in format 20160513072950.782000-420 and
// parse to a long representing ms since eopch
values.get(property)
.add(vtProp.getValue() == null ? 0L : ParseUtil.cimDateTimeToMillis(vtProp.stringValue()));
break;
default:
// Should never get here! If you get this exception you've
// added something to the enum without adding it here. Tsk.
throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString());
}
OleAuto.INSTANCE.VariantClear(vtProp.getPointer());
}
clsObj.Release();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void updateSwap() {
updateMeminfo();
Map<String, List<Long>> usage = WmiUtil.selectUint32sFrom(null, "Win32_PerfRawData_PerfOS_PagingFile",
"PercentUsage,PercentUsage_Base", "WHERE Name=\"_Total\"");
if (!usage.get("PercentUsage").isEmpty()) {
this.swapUsed = this.swapTotal * usage.get("PercentUsage").get(0) / usage.get("PercentUsage_Base").get(0);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void updateSwap() {
updateMeminfo();
this.swapUsed = PdhUtil.queryCounter(pdhPagingPercentUsageCounter) * this.pageSize;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void findWhere() {
class Book {
public final String title;
public final String author;
public final Integer year;
public Book(final String title, final String author, final Integer year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "title: " + title + ", author: " + author + ", year: " + year;
}
};
List<Book> listOfPlays =
new ArrayList<Book>() {{
add(new Book("Cymbeline2", "Shakespeare", 1614));
add(new Book("Cymbeline", "Shakespeare", 1611));
add(new Book("The Tempest", "Shakespeare", 1611));
}};
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void findWhere() {
class Book {
public final String title;
public final String author;
public final Integer year;
public Book(final String title, final String author, final Integer year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "title: " + title + ", author: " + author + ", year: " + year;
}
};
List<Book> listOfPlays =
new ArrayList<Book>() {{
add(new Book("Cymbeline2", "Shakespeare", 1614));
add(new Book("Cymbeline", "Shakespeare", 1611));
add(new Book("The Tempest", "Shakespeare", 1611));
}};
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).get().toString());
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).get().toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@SuppressWarnings("unchecked")
public void chainArray() {
final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() { {
add(new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } });
add(new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } });
add(new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } });
} };
final String youngest = $.chain(stooges.toArray())
.sortBy(
new Function1<Map<String, Object>, Integer>() {
public Integer apply(Map<String, Object> item) {
return (Integer) item.get("age");
}
})
.map(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("name") + " is " + item.get("age");
}
})
.first().item().toString();
assertEquals("moe is 21", youngest);
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
@SuppressWarnings("unchecked")
public void chainArray() {
final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() { {
add(new LinkedHashMap<String, Object>() { { put("name", "curly"); put("age", 25); } });
add(new LinkedHashMap<String, Object>() { { put("name", "moe"); put("age", 21); } });
add(new LinkedHashMap<String, Object>() { { put("name", "larry"); put("age", 23); } });
} };
final String youngest = $.chain($.toArray(stooges))
.sortBy(
new Function1<Map<String, Object>, Integer>() {
public Integer apply(Map<String, Object> item) {
return (Integer) item.get("age");
}
})
.map(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("name") + " is " + item.get("age");
}
})
.first().item().toString();
assertEquals("moe is 21", youngest);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void find() {
final Integer result = _.find(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("2", result.toString());
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void find() {
final Optional<Integer> result = _.find(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("Optional.of(2)", result.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void findWhere() {
class Book {
public final String title;
public final String author;
public final Integer year;
public Book(final String title, final String author, final Integer year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "title: " + title + ", author: " + author + ", year: " + year;
}
};
List<Book> listOfPlays =
new ArrayList<Book>() {{
add(new Book("Cymbeline2", "Shakespeare", 1614));
add(new Book("Cymbeline", "Shakespeare", 1611));
add(new Book("The Tempest", "Shakespeare", 1611));
}};
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void findWhere() {
class Book {
public final String title;
public final String author;
public final Integer year;
public Book(final String title, final String author, final Integer year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "title: " + title + ", author: " + author + ", year: " + year;
}
};
List<Book> listOfPlays =
new ArrayList<Book>() {{
add(new Book("Cymbeline2", "Shakespeare", 1614));
add(new Book("Cymbeline", "Shakespeare", 1611));
add(new Book("The Tempest", "Shakespeare", 1611));
}};
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).get().toString());
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).get().toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void singleOrNull() {
U<Integer> uWithMoreElement = new U<>(asList(1, 2, 3));
U<Integer> uWithOneElement = new U<>(asList(1));
final Integer result1 = U.singleOrNull(asList(1, 2, 3));
assertNull(result1);
final int result2 = U.singleOrNull(asList(1));
assertEquals(1, result2);
final Integer result3 = U.singleOrNull(new ArrayList<>());
assertNull(result3);
final Integer result4 = U.singleOrNull(asList(1, 2, 3), item -> item % 2 == 1);
assertNull(result4);
final int result5 = U.singleOrNull(asList(1, 2, 3), item -> item % 2 == 0);
assertEquals(2, result5);
final Integer result6 = U.singleOrNull(asList(1, 2, 3), item -> item == 5);
assertNull(result6);
final Integer result7 = uWithMoreElement.singleOrNull();
assertNull(result7);
final Integer result8 = uWithOneElement.singleOrNull();
assertEquals(result8, Integer.valueOf(1));
final Integer result9 = uWithMoreElement.singleOrNull(item -> item % 2 == 0);
assertEquals(result9, Integer.valueOf(2));
final Integer result10 = uWithMoreElement.singleOrNull(item -> item % 2 == 1);
assertNull(result10);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void singleOrNull() {
U<Integer> uWithMoreElement = new U<>(asList(1, 2, 3));
U<Integer> uWithOneElement = new U<>(singletonList(1));
final Integer result1 = U.singleOrNull(asList(1, 2, 3));
assertNull(result1);
final int result2 = U.singleOrNull(singletonList(1));
assertEquals(1, result2);
final Integer result3 = U.singleOrNull(new ArrayList<>());
assertNull(result3);
final Integer result4 = U.singleOrNull(asList(1, 2, 3), item -> item % 2 == 1);
assertNull(result4);
final int result5 = U.singleOrNull(asList(1, 2, 3), item -> item % 2 == 0);
assertEquals(2, result5);
final Integer result6 = U.singleOrNull(asList(1, 2, 3), item -> item == 5);
assertNull(result6);
final Integer result7 = uWithMoreElement.singleOrNull();
assertNull(result7);
final Integer result8 = uWithOneElement.singleOrNull();
assertEquals(result8, Integer.valueOf(1));
final Integer result9 = uWithMoreElement.singleOrNull(item -> item % 2 == 0);
assertEquals(result9, Integer.valueOf(2));
final Integer result10 = uWithMoreElement.singleOrNull(item -> item % 2 == 1);
assertNull(result10);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void lastOrNull() {
final Integer result = $.lastOrNull(asList(5, 4, 3, 2, 1));
assertEquals("1", result.toString());
final Integer resultObj = new $<Integer>(asList(5, 4, 3, 2, 1)).lastOrNull();
assertEquals("1", resultObj.toString());
assertNull($.lastOrNull(Collections.emptyList()));
assertNull(new $<Integer>(Collections.<Integer>emptyList()).lastOrNull());
final int resultPred = $.lastOrNull(asList(5, 4, 3, 2, 1), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(2, resultPred);
assertNull($.lastOrNull(Collections.<Integer>emptyList(), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
final int resultPredObj = new $<Integer>(asList(5, 4, 3, 2, 1)).lastOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(2, resultPredObj);
assertNull(new $<Integer>(Collections.<Integer>emptyList()).lastOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void lastOrNull() {
final Integer result = $.lastOrNull(asList(5, 4, 3, 2, 1));
assertEquals("1", result.toString());
final Integer resultObj = new $<Integer>(asList(5, 4, 3, 2, 1)).lastOrNull();
assertEquals("1", resultObj.toString());
final Integer resultChain = $.chain(asList(5, 4, 3, 2, 1)).lastOrNull().item();
assertEquals("1", resultChain.toString());
assertNull($.lastOrNull(Collections.emptyList()));
assertNull(new $<Integer>(Collections.<Integer>emptyList()).lastOrNull());
final int resultPred = $.lastOrNull(asList(5, 4, 3, 2, 1), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(2, resultPred);
final int resultPredChain = $.chain(asList(5, 4, 3, 2, 1)).lastOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}).item();
assertEquals(2, resultPredChain);
assertNull($.lastOrNull(Collections.<Integer>emptyList(), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
final int resultPredObj = new $<Integer>(asList(5, 4, 3, 2, 1)).lastOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(2, resultPredObj);
assertNull(new $<Integer>(Collections.<Integer>emptyList()).lastOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <E, F extends Number> Double average(final Iterable<E> iterable, final Function<E, F> func) {
F sum = sum(iterable, func);
return sum.doubleValue() / size(iterable);
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public static <E, F extends Number> Double average(final Iterable<E> iterable, final Function<E, F> func) {
F sum = sum(iterable, func);
if (sum == null) {
return null;
}
return sum.doubleValue() / size(iterable);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void firstOrNull() {
final Integer result = $.firstOrNull(asList(5, 4, 3, 2, 1));
assertEquals("5", result.toString());
final Integer resultObj = new $<Integer>(asList(5, 4, 3, 2, 1)).firstOrNull();
assertEquals("5", resultObj.toString());
assertNull($.firstOrNull(Collections.emptyList()));
assertNull(new $<Integer>(Collections.<Integer>emptyList()).firstOrNull());
final int resultPred = $.firstOrNull(asList(5, 4, 3, 2, 1), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(4, resultPred);
assertNull($.firstOrNull(Collections.<Integer>emptyList(), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
final int resultPredObj = new $<Integer>(asList(5, 4, 3, 2, 1)).firstOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(4, resultPredObj);
assertNull(new $<Integer>(Collections.<Integer>emptyList()).firstOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void firstOrNull() {
final Integer result = $.firstOrNull(asList(5, 4, 3, 2, 1));
assertEquals("5", result.toString());
final Integer resultObj = new $<Integer>(asList(5, 4, 3, 2, 1)).firstOrNull();
assertEquals("5", resultObj.toString());
final Integer resultChain = $.chain(asList(5, 4, 3, 2, 1)).firstOrNull().item();
assertEquals("5", resultChain.toString());
assertNull($.firstOrNull(Collections.emptyList()));
assertNull(new $<Integer>(Collections.<Integer>emptyList()).firstOrNull());
final int resultPred = $.firstOrNull(asList(5, 4, 3, 2, 1), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(4, resultPred);
final int resultPredChain = $.chain(asList(5, 4, 3, 2, 1)).firstOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}).item();
assertEquals(4, resultPredChain);
assertNull($.firstOrNull(Collections.<Integer>emptyList(), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
final int resultPredObj = new $<Integer>(asList(5, 4, 3, 2, 1)).firstOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(4, resultPredObj);
assertNull(new $<Integer>(Collections.<Integer>emptyList()).firstOrNull(new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
}));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static <T extends Number> double mean(final Iterable<T> iterable) {
T result = null;
int count = 0;
for (final T item : iterable) {
result = add(result, item);
count += 1;
}
return result.doubleValue() / count;
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static <T extends Number> double mean(final Iterable<T> iterable) {
T result = null;
int count = 0;
for (final T item : iterable) {
result = add(result, item);
count += 1;
}
if (result == null) {
return 0d;
}
return result.doubleValue() / count;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void detect() {
final Integer result = _.detect(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("2", result.toString());
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void detect() {
final Optional<Integer> result = _.detect(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("Optional.of(2)", result.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadingLocalTime() throws Exception {
Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "createOn", LocalTime.now());
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
//noinspection Duplicates
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v.id()).next();
assertTrue(vv.property("createOn").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
assertTrue(propertyTypeMap.containsKey("createOn"));
sqlgGraph1.tx().rollback();
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadingLocalTime() throws Exception {
Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "createOn", LocalTime.now());
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
//noinspection Duplicates
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v.id()).next();
Assert.assertTrue(vv.property("createOn").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
Assert.assertTrue(propertyTypeMap.containsKey("createOn"));
sqlgGraph1.tx().rollback();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHasHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.v(person1.id());
person2 = this.sqlgGraph.v(person2.id());
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "john").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "peter").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).in("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHasHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.traversal().V(person1.id()).next();
person2 = this.sqlgGraph.traversal().V(person2.id()).next();
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "john").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "peter").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).in("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBatchUpdatePersistentVertices() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals("b", this.sqlgGraph.v(v2.id()).value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v2.property("surname", "bb");
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals("bb", this.sqlgGraph.v(v2.id()).value("surname"));
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBatchUpdatePersistentVertices() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals("b", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v2.property("surname", "bb");
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals("bb", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBatchUpdatePersistentVerticesAllTypes() {
Assume.assumeTrue(this.sqlgGraph.features().vertex().properties().supportsFloatValues());
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals("b", this.sqlgGraph.v(v2.id()).value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v1.property("boolean", true);
v1.property("short", (short) 1);
v1.property("integer", 1);
v1.property("long", 1L);
v1.property("float", 1F);
v1.property("double", 1D);
v2.property("surname", "bb");
v2.property("boolean", false);
v2.property("short", (short) 2);
v2.property("integer", 2);
v2.property("long", 2L);
v2.property("float", 2F);
v2.property("double", 2D);
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals(true, this.sqlgGraph.v(v1.id()).value("boolean"));
assertEquals((short) 1, this.sqlgGraph.v(v1.id()).<Short>value("short").shortValue());
assertEquals(1, this.sqlgGraph.v(v1.id()).<Integer>value("integer").intValue());
assertEquals(1L, this.sqlgGraph.v(v1.id()).<Long>value("long").longValue(), 0);
assertEquals(1F, this.sqlgGraph.v(v1.id()).<Float>value("float").floatValue(), 0);
assertEquals(1D, this.sqlgGraph.v(v1.id()).<Double>value("double").doubleValue(), 0);
assertEquals("bb", this.sqlgGraph.v(v2.id()).value("surname"));
assertEquals(false, this.sqlgGraph.v(v2.id()).value("boolean"));
assertEquals((short) 2, this.sqlgGraph.v(v2.id()).<Short>value("short").shortValue());
assertEquals(2, this.sqlgGraph.v(v2.id()).<Integer>value("integer").intValue());
assertEquals(2L, this.sqlgGraph.v(v2.id()).<Long>value("long").longValue(), 0);
assertEquals(2F, this.sqlgGraph.v(v2.id()).<Float>value("float").floatValue(), 0);
assertEquals(2D, this.sqlgGraph.v(v2.id()).<Double>value("double").doubleValue(), 0);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBatchUpdatePersistentVerticesAllTypes() {
Assume.assumeTrue(this.sqlgGraph.features().vertex().properties().supportsFloatValues());
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals("b", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v1.property("boolean", true);
v1.property("short", (short) 1);
v1.property("integer", 1);
v1.property("long", 1L);
v1.property("float", 1F);
v1.property("double", 1D);
v2.property("surname", "bb");
v2.property("boolean", false);
v2.property("short", (short) 2);
v2.property("integer", 2);
v2.property("long", 2L);
v2.property("float", 2F);
v2.property("double", 2D);
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals(true, this.sqlgGraph.traversal().V(v1.id()).next().value("boolean"));
assertEquals((short) 1, this.sqlgGraph.traversal().V(v1.id()).next().<Short>value("short").shortValue());
assertEquals(1, this.sqlgGraph.traversal().V(v1.id()).next().<Integer>value("integer").intValue());
assertEquals(1L, this.sqlgGraph.traversal().V(v1.id()).next().<Long>value("long").longValue(), 0);
assertEquals(1F, this.sqlgGraph.traversal().V(v1.id()).next().<Float>value("float").floatValue(), 0);
assertEquals(1D, this.sqlgGraph.traversal().V(v1.id()).next().<Double>value("double").doubleValue(), 0);
assertEquals("bb", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
assertEquals(false, this.sqlgGraph.traversal().V(v2.id()).next().value("boolean"));
assertEquals((short) 2, this.sqlgGraph.traversal().V(v2.id()).next().<Short>value("short").shortValue());
assertEquals(2, this.sqlgGraph.traversal().V(v2.id()).next().<Integer>value("integer").intValue());
assertEquals(2L, this.sqlgGraph.traversal().V(v2.id()).next().<Long>value("long").longValue(), 0);
assertEquals(2F, this.sqlgGraph.traversal().V(v2.id()).next().<Float>value("float").floatValue(), 0);
assertEquals(2D, this.sqlgGraph.traversal().V(v2.id()).next().<Double>value("double").doubleValue(), 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadVertexProperties() {
Vertex marko = this.sqlgGraph.addVertex(T.label, "Person", "name", "marko");
this.sqlgGraph.tx().commit();
marko = this.sqlgGraph.v(marko.id());
Assert.assertEquals("marko", marko.property("name").value());
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadVertexProperties() {
Vertex marko = this.sqlgGraph.addVertex(T.label, "Person", "name", "marko");
this.sqlgGraph.tx().commit();
marko = this.sqlgGraph.traversal().V(marko.id()).next();
Assert.assertEquals("marko", marko.property("name").value());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.v(person1.id());
person2 = this.sqlgGraph.v(person2.id());
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(vertices.get(1)).in("friend").count().next().intValue());
Assert.assertEquals(2, vertices.size());
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.traversal().V(person1.id()).next();
person2 = this.sqlgGraph.traversal().V(person2.id()).next();
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(vertices.get(1)).in("friend").count().next().intValue());
Assert.assertEquals(2, vertices.size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void loadResultSet(ResultSet resultSet, List<VertexLabel> inForeignKeys, List<VertexLabel> outForeignKeys) throws SQLException {
SchemaTable inVertexColumnName = null;
SchemaTable outVertexColumnName = null;
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String columnName = resultSetMetaData.getColumnLabel(i);
if (!columnName.equals("ID") &&
!columnName.endsWith(Topology.OUT_VERTEX_COLUMN_END) &&
!columnName.endsWith(Topology.IN_VERTEX_COLUMN_END)) {
loadProperty(resultSet, columnName, i);
}
}
long inId = -1;
ListOrderedSet<Comparable> inComparables = new ListOrderedSet<>();
for (VertexLabel inVertexLabel: inForeignKeys) {
inVertexColumnName = SchemaTable.of(inVertexLabel.getSchema().getName(), inVertexLabel.getLabel());
if (inVertexLabel.hasIDPrimaryKey()) {
String foreignKey = inVertexLabel.getSchema().getName() + "." + inVertexLabel.getName() + Topology.IN_VERTEX_COLUMN_END;
inId = resultSet.getLong(foreignKey);
if (!resultSet.wasNull()) {
break;
}
} else {
for (String identifier : inVertexLabel.getIdentifiers()) {
PropertyColumn propertyColumn = inVertexLabel.getProperty(identifier).orElseThrow(
() -> new IllegalStateException(String.format("identifier %s column must be a property", identifier))
);
PropertyType propertyType = propertyColumn.getPropertyType();
String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType);
int count = 1;
for (String ignored : propertyTypeToSqlDefinition) {
if (count > 1) {
inComparables.add((Comparable)resultSet.getObject(inVertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.IN_VERTEX_COLUMN_END));
} else {
//The first column existVertexLabel no postfix
inComparables.add((Comparable)resultSet.getObject(inVertexLabel.getFullName() + "." + identifier + Topology.IN_VERTEX_COLUMN_END));
}
count++;
}
}
}
}
long outId = -1;
ListOrderedSet<Comparable> outComparables = new ListOrderedSet<>();
for (VertexLabel outVertexLabel: outForeignKeys) {
outVertexColumnName = SchemaTable.of(outVertexLabel.getSchema().getName(), outVertexLabel.getLabel());
if (outVertexLabel.hasIDPrimaryKey()) {
String foreignKey = outVertexLabel.getSchema().getName() + "." + outVertexLabel.getName() + Topology.OUT_VERTEX_COLUMN_END;
outId = resultSet.getLong(foreignKey);
if (!resultSet.wasNull()) {
break;
}
} else {
for (String identifier : outVertexLabel.getIdentifiers()) {
PropertyColumn propertyColumn = outVertexLabel.getProperty(identifier).orElseThrow(
() -> new IllegalStateException(String.format("identifier %s column must be a property", identifier))
);
PropertyType propertyType = propertyColumn.getPropertyType();
String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType);
int count = 1;
for (String ignored : propertyTypeToSqlDefinition) {
if (count > 1) {
outComparables.add((Comparable)resultSet.getObject(outVertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.OUT_VERTEX_COLUMN_END));
} else {
//The first column existVertexLabel no postfix
outComparables.add((Comparable)resultSet.getObject(outVertexLabel.getFullName() + "." + identifier + Topology.OUT_VERTEX_COLUMN_END));
}
count++;
}
}
}
}
if (inId != -1) {
this.inVertex = SqlgVertex.of(this.sqlgGraph, inId, inVertexColumnName.getSchema(), SqlgUtil.removeTrailingInId(inVertexColumnName.getTable()));
} else {
Preconditions.checkState(!inComparables.isEmpty(), "The in ids are not found for the edge!");
this.inVertex = SqlgVertex.of(this.sqlgGraph, inComparables, inVertexColumnName.getSchema(), SqlgUtil.removeTrailingInId(inVertexColumnName.getTable()));
}
if (outId != -1) {
this.outVertex = SqlgVertex.of(this.sqlgGraph, outId, outVertexColumnName.getSchema(), SqlgUtil.removeTrailingOutId(outVertexColumnName.getTable()));
} else {
Preconditions.checkState(!outComparables.isEmpty(), "The out ids are not found for the edge!");
this.outVertex = SqlgVertex.of(this.sqlgGraph, outComparables, outVertexColumnName.getSchema(), SqlgUtil.removeTrailingOutId(outVertexColumnName.getTable()));
}
}
#location 80
#vulnerability type NULL_DEREFERENCE | #fixed code
private void loadResultSet(ResultSet resultSet, List<VertexLabel> inForeignKeys, List<VertexLabel> outForeignKeys) throws SQLException {
SchemaTable inVertexColumnName = null;
SchemaTable outVertexColumnName = null;
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
String columnName = resultSetMetaData.getColumnLabel(i);
if (!columnName.equals("ID") &&
!columnName.endsWith(Topology.OUT_VERTEX_COLUMN_END) &&
!columnName.endsWith(Topology.IN_VERTEX_COLUMN_END)) {
loadProperty(resultSet, columnName, i);
}
}
long inId = -1;
List<Comparable> inComparables = new ArrayList<>();
for (VertexLabel inVertexLabel: inForeignKeys) {
inVertexColumnName = SchemaTable.of(inVertexLabel.getSchema().getName(), inVertexLabel.getLabel());
if (inVertexLabel.hasIDPrimaryKey()) {
String foreignKey = inVertexLabel.getSchema().getName() + "." + inVertexLabel.getName() + Topology.IN_VERTEX_COLUMN_END;
inId = resultSet.getLong(foreignKey);
if (!resultSet.wasNull()) {
break;
}
} else {
for (String identifier : inVertexLabel.getIdentifiers()) {
PropertyColumn propertyColumn = inVertexLabel.getProperty(identifier).orElseThrow(
() -> new IllegalStateException(String.format("identifier %s column must be a property", identifier))
);
PropertyType propertyType = propertyColumn.getPropertyType();
String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType);
int count = 1;
for (String ignored : propertyTypeToSqlDefinition) {
if (count > 1) {
inComparables.add((Comparable)resultSet.getObject(inVertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.IN_VERTEX_COLUMN_END));
} else {
//The first column existVertexLabel no postfix
inComparables.add((Comparable)resultSet.getObject(inVertexLabel.getFullName() + "." + identifier + Topology.IN_VERTEX_COLUMN_END));
}
count++;
}
}
}
}
long outId = -1;
List<Comparable> outComparables = new ArrayList<>();
for (VertexLabel outVertexLabel: outForeignKeys) {
outVertexColumnName = SchemaTable.of(outVertexLabel.getSchema().getName(), outVertexLabel.getLabel());
if (outVertexLabel.hasIDPrimaryKey()) {
String foreignKey = outVertexLabel.getSchema().getName() + "." + outVertexLabel.getName() + Topology.OUT_VERTEX_COLUMN_END;
outId = resultSet.getLong(foreignKey);
if (!resultSet.wasNull()) {
break;
}
} else {
for (String identifier : outVertexLabel.getIdentifiers()) {
PropertyColumn propertyColumn = outVertexLabel.getProperty(identifier).orElseThrow(
() -> new IllegalStateException(String.format("identifier %s column must be a property", identifier))
);
PropertyType propertyType = propertyColumn.getPropertyType();
String[] propertyTypeToSqlDefinition = this.sqlgGraph.getSqlDialect().propertyTypeToSqlDefinition(propertyType);
int count = 1;
for (String ignored : propertyTypeToSqlDefinition) {
if (count > 1) {
outComparables.add((Comparable)resultSet.getObject(outVertexLabel.getFullName() + "." + identifier + propertyType.getPostFixes()[count - 2] + Topology.OUT_VERTEX_COLUMN_END));
} else {
//The first column existVertexLabel no postfix
outComparables.add((Comparable)resultSet.getObject(outVertexLabel.getFullName() + "." + identifier + Topology.OUT_VERTEX_COLUMN_END));
}
count++;
}
}
}
}
if (inId != -1) {
this.inVertex = SqlgVertex.of(this.sqlgGraph, inId, inVertexColumnName.getSchema(), SqlgUtil.removeTrailingInId(inVertexColumnName.getTable()));
} else {
Preconditions.checkState(!inComparables.isEmpty(), "The in ids are not found for the edge!");
this.inVertex = SqlgVertex.of(this.sqlgGraph, inComparables, inVertexColumnName.getSchema(), SqlgUtil.removeTrailingInId(inVertexColumnName.getTable()));
}
if (outId != -1) {
this.outVertex = SqlgVertex.of(this.sqlgGraph, outId, outVertexColumnName.getSchema(), SqlgUtil.removeTrailingOutId(outVertexColumnName.getTable()));
} else {
Preconditions.checkState(!outComparables.isEmpty(), "The out ids are not found for the edge!");
this.outVertex = SqlgVertex.of(this.sqlgGraph, outComparables, outVertexColumnName.getSchema(), SqlgUtil.removeTrailingOutId(outVertexColumnName.getTable()));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBatchUpdatePersistentVertices() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals("b", this.sqlgGraph.v(v2.id()).value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v2.property("surname", "bb");
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals("bb", this.sqlgGraph.v(v2.id()).value("surname"));
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBatchUpdatePersistentVertices() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals("b", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v2.property("surname", "bb");
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals("bb", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.v(person1.id());
person2 = this.sqlgGraph.v(person2.id());
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(vertices.get(1)).in("friend").count().next().intValue());
Assert.assertEquals(2, vertices.size());
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.traversal().V(person1.id()).next();
person2 = this.sqlgGraph.traversal().V(person2.id()).next();
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(vertices.get(1)).in("friend").count().next().intValue());
Assert.assertEquals(2, vertices.size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMultipleReferencesToSameVertex2Instances() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
this.sqlgGraph.tx().commit();
//_v1 is in the transaction cache
//v1 is not
Vertex _v1 = this.sqlgGraph.v(v1.id());
Assert.assertEquals("john", v1.value("name"));
Assert.assertEquals("john", _v1.value("name"));
v1.property("name", "john1");
Assert.assertEquals("john1", v1.value("name"));
Assert.assertEquals("john1", _v1.value("name"));
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testMultipleReferencesToSameVertex2Instances() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
this.sqlgGraph.tx().commit();
//_v1 is in the transaction cache
//v1 is not
Vertex _v1 = this.sqlgGraph.traversal().V(v1.id()).next();
Assert.assertEquals("john", v1.value("name"));
Assert.assertEquals("john", _v1.value("name"));
v1.property("name", "john1");
Assert.assertEquals("john1", v1.value("name"));
Assert.assertEquals("john1", _v1.value("name"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHasHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.v(person1.id());
person2 = this.sqlgGraph.v(person2.id());
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "john").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "peter").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).in("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEdgeBetweenVerticesPropertiesEagerlyLoadedOnHasHas() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "peter");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.traversal().V(person1.id()).next();
person2 = this.sqlgGraph.traversal().V(person2.id()).next();
person1.addEdge("friend", person2);
Assert.assertEquals("john", person1.value("name"));
Assert.assertEquals("peter", person2.value("name"));
this.sqlgGraph.tx().commit();
List<Vertex> vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "john").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).out("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
vertices = this.sqlgGraph.traversal().V().<Vertex>has(T.label, "Person").<Vertex>has("name", "peter").toList();
Assert.assertEquals(1, vertexTraversal(vertices.get(0)).in("friend").count().next().intValue());
Assert.assertEquals(1, vertices.size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@BeforeClass
public static void beforeClass() throws ClassNotFoundException, IOException, PropertyVetoException, NamingException, ConfigurationException {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
String url = configuration.getString("jdbc.url");
//obtain the connection that we will later supply from JNDI
SqlgGraph g = SqlgGraph.open(configuration);
ds = g.getSqlgDataSource().get(url);
// g.getTopology().close();
//change the connection url to be a JNDI one
configuration.setProperty("jdbc.url", "jndi:testConnection");
//set up the initial context
NamingManager.setInitialContextFactoryBuilder(environment -> {
InitialContextFactory mockFactory = mock(InitialContextFactory.class);
Context mockContext = mock(Context.class);
when(mockFactory.getInitialContext(any())).thenReturn(mockContext);
when(mockContext.lookup("testConnection")).thenReturn(ds);
return mockFactory;
});
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@BeforeClass
public static void beforeClass() throws Exception {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
String url = configuration.getString("jdbc.url");
//obtain the connection that we will later supply from JNDI
ds = new C3p0DataSourceFactory().setup(url, configuration).getDatasource();
//change the connection url to be a JNDI one
configuration.setProperty("jdbc.url", "jndi:testConnection");
//set up the initial context
NamingManager.setInitialContextFactoryBuilder(environment -> {
InitialContextFactory mockFactory = mock(InitialContextFactory.class);
Context mockContext = mock(Context.class);
when(mockFactory.getInitialContext(any())).thenReturn(mockContext);
when(mockContext.lookup("testConnection")).thenReturn(ds);
return mockFactory;
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadingJson() throws Exception {
Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsJson());
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode json = new ObjectNode(objectMapper.getNodeFactory());
json.put("username", "john");
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "doc", json);
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v1.id()).next();
assertTrue(vv.property("doc").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
assertTrue(propertyTypeMap.containsKey("doc"));
sqlgGraph1.tx().rollback();
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadingJson() throws Exception {
Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsJson());
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode json = new ObjectNode(objectMapper.getNodeFactory());
json.put("username", "john");
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "doc", json);
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v1.id()).next();
Assert.assertTrue(vv.property("doc").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
Assert.assertTrue(propertyTypeMap.containsKey("doc"));
sqlgGraph1.tx().rollback();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testVertexTransactionalCache2() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person");
Edge e1 = v1.addEdge("friend", v2);
Assert.assertEquals(1, vertexTraversal(v1).out("friend").count().next().intValue());
Vertex tmpV1 = edgeTraversal(this.sqlgGraph.e(e1.id())).outV().next();
tmpV1.addEdge("foe", v3);
//this should fail as v1's out edges will not be updated
Assert.assertEquals(1, vertexTraversal(tmpV1).out("foe").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(v1).out("foe").count().next().intValue());
this.sqlgGraph.tx().rollback();
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testVertexTransactionalCache2() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person");
Edge e1 = v1.addEdge("friend", v2);
Assert.assertEquals(1, vertexTraversal(v1).out("friend").count().next().intValue());
Vertex tmpV1 = edgeTraversal(this.sqlgGraph.traversal().E(e1.id()).next()).outV().next();
tmpV1.addEdge("foe", v3);
//this should fail as v1's out edges will not be updated
Assert.assertEquals(1, vertexTraversal(tmpV1).out("foe").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(v1).out("foe").count().next().intValue());
this.sqlgGraph.tx().rollback();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBatchUpdateDifferentPropertiesDifferentRows() {
Vertex sqlgVertex1 = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a1", "property2", "b1", "property3", "c1");
Vertex sqlgVertex2 = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a2", "property2", "b2", "property3", "c2");
Vertex sqlgVertex3 = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a3", "property2", "b3", "property3", "c3");
this.sqlgGraph.tx().commit();
sqlgVertex1 = this.sqlgGraph.v(sqlgVertex1.id());
assertEquals("a1", sqlgVertex1.value("property1"));
assertEquals("b1", sqlgVertex1.value("property2"));
assertEquals("c1", sqlgVertex1.value("property3"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
sqlgVertex1 = this.sqlgGraph.v(sqlgVertex1.id());
sqlgVertex1.property("property1", "a11");
sqlgVertex2.property("property2", "b22");
sqlgVertex3.property("property3", "c33");
this.sqlgGraph.tx().commit();
assertEquals("a11", sqlgVertex1.value("property1"));
assertEquals("b1", sqlgVertex1.value("property2"));
assertEquals("c1", sqlgVertex1.value("property3"));
sqlgVertex1 = this.sqlgGraph.v(sqlgVertex1.id());
assertEquals("a11", sqlgVertex1.value("property1"));
assertEquals("b1", sqlgVertex1.value("property2"));
assertEquals("c1", sqlgVertex1.value("property3"));
sqlgVertex2 = this.sqlgGraph.v(sqlgVertex2.id());
assertEquals("a2", sqlgVertex2.value("property1"));
assertEquals("b22", sqlgVertex2.value("property2"));
assertEquals("c2", sqlgVertex2.value("property3"));
sqlgVertex3 = this.sqlgGraph.v(sqlgVertex3.id());
assertEquals("a3", sqlgVertex3.value("property1"));
assertEquals("b3", sqlgVertex3.value("property2"));
assertEquals("c33", sqlgVertex3.value("property3"));
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBatchUpdateDifferentPropertiesDifferentRows() {
Vertex sqlgVertex1 = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a1", "property2", "b1", "property3", "c1");
Vertex sqlgVertex2 = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a2", "property2", "b2", "property3", "c2");
Vertex sqlgVertex3 = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a3", "property2", "b3", "property3", "c3");
this.sqlgGraph.tx().commit();
sqlgVertex1 = this.sqlgGraph.traversal().V(sqlgVertex1.id()).next();
assertEquals("a1", sqlgVertex1.value("property1"));
assertEquals("b1", sqlgVertex1.value("property2"));
assertEquals("c1", sqlgVertex1.value("property3"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
sqlgVertex1 = this.sqlgGraph.traversal().V(sqlgVertex1.id()).next();
sqlgVertex1.property("property1", "a11");
sqlgVertex2.property("property2", "b22");
sqlgVertex3.property("property3", "c33");
this.sqlgGraph.tx().commit();
assertEquals("a11", sqlgVertex1.value("property1"));
assertEquals("b1", sqlgVertex1.value("property2"));
assertEquals("c1", sqlgVertex1.value("property3"));
sqlgVertex1 = this.sqlgGraph.traversal().V(sqlgVertex1.id()).next();
assertEquals("a11", sqlgVertex1.value("property1"));
assertEquals("b1", sqlgVertex1.value("property2"));
assertEquals("c1", sqlgVertex1.value("property3"));
sqlgVertex2 = this.sqlgGraph.traversal().V(sqlgVertex2.id()).next();
assertEquals("a2", sqlgVertex2.value("property1"));
assertEquals("b22", sqlgVertex2.value("property2"));
assertEquals("c2", sqlgVertex2.value("property3"));
sqlgVertex3 = this.sqlgGraph.traversal().V(sqlgVertex3.id()).next();
assertEquals("a3", sqlgVertex3.value("property1"));
assertEquals("b3", sqlgVertex3.value("property2"));
assertEquals("c33", sqlgVertex3.value("property3"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadingDatasourceFromJndi() throws Exception {
SqlgGraph g = SqlgGraph.open(configuration);
assertNotNull(g.getSqlDialect());
assertNotNull(g.getSqlgDataSource().get(configuration.getString("jdbc.url")));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadingDatasourceFromJndi() throws Exception {
SqlgGraph g = SqlgGraph.open(configuration);
assertNotNull(g.getSqlDialect());
assertEquals(configuration.getString("jdbc.url"), g.getJdbcUrl());
assertNotNull(g.getConnection());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadingLocalDate() throws Exception {
Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "createOn", LocalDate.now());
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
//noinspection Duplicates
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v.id()).next();
assertTrue(vv.property("createOn").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
assertTrue(propertyTypeMap.containsKey("createOn"));
sqlgGraph1.tx().rollback();
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadingLocalDate() throws Exception {
Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "createOn", LocalDate.now());
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
//noinspection Duplicates
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v.id()).next();
Assert.assertTrue(vv.property("createOn").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
Assert.assertTrue(propertyTypeMap.containsKey("createOn"));
sqlgGraph1.tx().rollback();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadPropertiesOnUpdate() {
Vertex vertex = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a", "property2", "b");
this.sqlgGraph.tx().commit();
vertex = this.sqlgGraph.v(vertex.id());
vertex.property("property1", "aa");
assertEquals("b", vertex.value("property2"));
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadPropertiesOnUpdate() {
Vertex vertex = this.sqlgGraph.addVertex(T.label, "Person", "property1", "a", "property2", "b");
this.sqlgGraph.tx().commit();
vertex = this.sqlgGraph.traversal().V(vertex.id()).next();
vertex.property("property1", "aa");
assertEquals("b", vertex.value("property2"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Map<String, Set<IndexRef>> extractIndices(Connection conn, String catalog, String schema) throws SQLException{
// copied and simplified from the postgres JDBC driver class (PgDatabaseMetaData)
String sql = "SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, "
+ " ct.relname AS TABLE_NAME, NOT i.indisunique AS NON_UNIQUE, "
+ " NULL AS INDEX_QUALIFIER, ci.relname AS INDEX_NAME, "
+ " CASE i.indisclustered "
+ " WHEN true THEN " + java.sql.DatabaseMetaData.tableIndexClustered
+ " ELSE CASE am.amname "
+ " WHEN 'hash' THEN " + java.sql.DatabaseMetaData.tableIndexHashed
+ " ELSE " + java.sql.DatabaseMetaData.tableIndexOther
+ " END "
+ " END AS TYPE, "
+ " (i.keys).n AS ORDINAL_POSITION, "
+ " trim(both '\"' from pg_catalog.pg_get_indexdef(ci.oid, (i.keys).n, false)) AS COLUMN_NAME "
+ "FROM pg_catalog.pg_class ct "
+ " JOIN pg_catalog.pg_namespace n ON (ct.relnamespace = n.oid) "
+ " JOIN (SELECT i.indexrelid, i.indrelid, i.indoption, "
+ " i.indisunique, i.indisclustered, i.indpred, "
+ " i.indexprs, "
+ " information_schema._pg_expandarray(i.indkey) AS keys "
+ " FROM pg_catalog.pg_index i) i "
+ " ON (ct.oid = i.indrelid) "
+ " JOIN pg_catalog.pg_class ci ON (ci.oid = i.indexrelid) "
+ " JOIN pg_catalog.pg_am am ON (ci.relam = am.oid) "
+ "WHERE true ";
if (schema != null && !"".equals(schema)) {
sql += " AND n.nspname = " + maybeWrapInQoutes(schema);
}
sql += " ORDER BY NON_UNIQUE, TYPE, INDEX_NAME, ORDINAL_POSITION ";
try (Statement s=conn.createStatement()){
try (ResultSet indexRs=s.executeQuery(sql)){
Map<String, Set<IndexRef>> ret=new HashMap<>();
String lastKey=null;
String lastIndexName=null;
IndexType lastIndexType=null;
List<String> lastColumns=new LinkedList<>();
while (indexRs.next()){
String cat=indexRs.getString("TABLE_CAT");
String sch=indexRs.getString("TABLE_SCHEM");
String tbl=indexRs.getString("TABLE_NAME");
String key=cat+"."+sch+"."+tbl;
String indexName=indexRs.getString("INDEX_NAME");
boolean nonUnique=indexRs.getBoolean("NON_UNIQUE");
if (lastIndexName==null){
lastIndexName=indexName;
lastIndexType=nonUnique?IndexType.NON_UNIQUE:IndexType.UNIQUE;
lastKey=key;
} else if (!lastIndexName.equals(indexName)){
if (!lastIndexName.endsWith("_pkey") && !lastIndexName.endsWith("_idx")){
if (!Schema.GLOBAL_UNIQUE_INDEX_SCHEMA.equals(schema)){
//System.out.println(lastColumns);
//TopologyManager.addGlobalUniqueIndex(sqlgGraph,lastIndexName,lastColumns);
//} else {
MultiMap.put(ret, lastKey, new IndexRef(lastIndexName,lastIndexType,lastColumns));
}
}
lastColumns.clear();
lastIndexName=indexName;
lastIndexType=nonUnique?IndexType.NON_UNIQUE:IndexType.UNIQUE;
}
lastColumns.add(indexRs.getString("COLUMN_NAME"));
lastKey=key;
}
if (!lastIndexName.endsWith("_pkey") && !lastIndexName.endsWith("_idx")){
if (!Schema.GLOBAL_UNIQUE_INDEX_SCHEMA.equals(schema)){
//System.out.println(lastColumns);
//TopologyManager.addGlobalUniqueIndex(sqlgGraph,lastIndexName,lastColumns);
//} else {
MultiMap.put(ret, lastKey, new IndexRef(lastIndexName,lastIndexType,lastColumns));
}
}
return ret;
}
}
}
#location 53
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Map<String, Set<IndexRef>> extractIndices(Connection conn, String catalog, String schema) throws SQLException{
// copied and simplified from the postgres JDBC driver class (PgDatabaseMetaData)
String sql = "SELECT NULL AS TABLE_CAT, n.nspname AS TABLE_SCHEM, "
+ " ct.relname AS TABLE_NAME, NOT i.indisunique AS NON_UNIQUE, "
+ " NULL AS INDEX_QUALIFIER, ci.relname AS INDEX_NAME, "
+ " CASE i.indisclustered "
+ " WHEN true THEN " + java.sql.DatabaseMetaData.tableIndexClustered
+ " ELSE CASE am.amname "
+ " WHEN 'hash' THEN " + java.sql.DatabaseMetaData.tableIndexHashed
+ " ELSE " + java.sql.DatabaseMetaData.tableIndexOther
+ " END "
+ " END AS TYPE, "
+ " (i.keys).n AS ORDINAL_POSITION, "
+ " trim(both '\"' from pg_catalog.pg_get_indexdef(ci.oid, (i.keys).n, false)) AS COLUMN_NAME "
+ "FROM pg_catalog.pg_class ct "
+ " JOIN pg_catalog.pg_namespace n ON (ct.relnamespace = n.oid) "
+ " JOIN (SELECT i.indexrelid, i.indrelid, i.indoption, "
+ " i.indisunique, i.indisclustered, i.indpred, "
+ " i.indexprs, "
+ " information_schema._pg_expandarray(i.indkey) AS keys "
+ " FROM pg_catalog.pg_index i) i "
+ " ON (ct.oid = i.indrelid) "
+ " JOIN pg_catalog.pg_class ci ON (ci.oid = i.indexrelid) "
+ " JOIN pg_catalog.pg_am am ON (ci.relam = am.oid) "
+ "WHERE true ";
if (schema != null && !"".equals(schema)) {
sql += " AND n.nspname = " + maybeWrapInQoutes(schema);
} else {
// exclude schemas we know we're not interested in
sql += " AND n.nspname <> 'pg_catalog' AND n.nspname <> 'pg_toast' AND n.nspname <> '"+SQLG_SCHEMA+"'";
}
sql += " ORDER BY NON_UNIQUE, TYPE, INDEX_NAME, ORDINAL_POSITION ";
try (Statement s=conn.createStatement()){
try (ResultSet indexRs=s.executeQuery(sql)){
Map<String, Set<IndexRef>> ret=new HashMap<>();
String lastKey=null;
String lastIndexName=null;
IndexType lastIndexType=null;
List<String> lastColumns=new LinkedList<>();
while (indexRs.next()){
String cat=indexRs.getString("TABLE_CAT");
String sch=indexRs.getString("TABLE_SCHEM");
String tbl=indexRs.getString("TABLE_NAME");
String key=cat+"."+sch+"."+tbl;
String indexName=indexRs.getString("INDEX_NAME");
boolean nonUnique=indexRs.getBoolean("NON_UNIQUE");
if (lastIndexName==null){
lastIndexName=indexName;
lastIndexType=nonUnique?IndexType.NON_UNIQUE:IndexType.UNIQUE;
lastKey=key;
} else if (!lastIndexName.equals(indexName)){
if (!lastIndexName.endsWith("_pkey") && !lastIndexName.endsWith("_idx")){
if (!Schema.GLOBAL_UNIQUE_INDEX_SCHEMA.equals(schema)){
//System.out.println(lastColumns);
//TopologyManager.addGlobalUniqueIndex(sqlgGraph,lastIndexName,lastColumns);
//} else {
MultiMap.put(ret, lastKey, new IndexRef(lastIndexName,lastIndexType,lastColumns));
}
}
lastColumns.clear();
lastIndexName=indexName;
lastIndexType=nonUnique?IndexType.NON_UNIQUE:IndexType.UNIQUE;
}
lastColumns.add(indexRs.getString("COLUMN_NAME"));
lastKey=key;
}
if (lastIndexName!=null && !lastIndexName.endsWith("_pkey") && !lastIndexName.endsWith("_idx")){
if (!Schema.GLOBAL_UNIQUE_INDEX_SCHEMA.equals(schema)){
//System.out.println(lastColumns);
//TopologyManager.addGlobalUniqueIndex(sqlgGraph,lastIndexName,lastColumns);
//} else {
MultiMap.put(ret, lastKey, new IndexRef(lastIndexName,lastIndexType,lastColumns));
}
}
return ret;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMultipleReferencesToSameVertex() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
this.sqlgGraph.tx().commit();
Assert.assertEquals("john", v1.value("name"));
//_v1 is in the transaction cache
//v1 is not
Vertex _v1 = this.sqlgGraph.v(v1.id());
Assert.assertEquals("john", _v1.value("name"));
v1.property("name", "john1");
Assert.assertEquals("john1", v1.value("name"));
Assert.assertEquals("john1", _v1.value("name"));
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testMultipleReferencesToSameVertex() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "john");
this.sqlgGraph.tx().commit();
Assert.assertEquals("john", v1.value("name"));
//_v1 is in the transaction cache
//v1 is not
Vertex _v1 = this.sqlgGraph.traversal().V(v1.id()).next();
Assert.assertEquals("john", _v1.value("name"));
v1.property("name", "john1");
Assert.assertEquals("john1", v1.value("name"));
Assert.assertEquals("john1", _v1.value("name"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEdgeBetweenVertices() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.v(person1.id());
person2 = this.sqlgGraph.v(person2.id());
person1.addEdge("friend", person2);
this.sqlgGraph.tx().commit();
Assert.assertEquals(1, vertexTraversal(person1).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(person2).in("friend").count().next().intValue());
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEdgeBetweenVertices() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.traversal().V(person1.id()).next();
person2 = this.sqlgGraph.traversal().V(person2.id()).next();
person1.addEdge("friend", person2);
this.sqlgGraph.tx().commit();
Assert.assertEquals(1, vertexTraversal(person1).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(person2).in("friend").count().next().intValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@BeforeClass
public static void beforeClass() throws Exception {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
String url = configuration.getString("jdbc.url");
//obtain the connection that we will later supply from JNDI
SqlgPlugin p = findSqlgPlugin(url);
Assert.assertNotNull(p);
ds = new C3p0DataSourceFactory().setup(p.getDriverFor(url), configuration).getDatasource();
//change the connection url to be a JNDI one
configuration.setProperty("jdbc.url", "jndi:testConnection");
//set up the initial context
NamingManager.setInitialContextFactoryBuilder(environment -> {
InitialContextFactory mockFactory = mock(InitialContextFactory.class);
Context mockContext = mock(Context.class);
when(mockFactory.getInitialContext(any())).thenReturn(mockContext);
when(mockContext.lookup("testConnection")).thenReturn(ds);
return mockFactory;
});
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@BeforeClass
public static void beforeClass() throws Exception {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
ds = C3P0DataSource.create(configuration).getDatasource();
//change the connection url to be a JNDI one
configuration.setProperty("jdbc.url", "jndi:testConnection");
//set up the initial context
NamingManager.setInitialContextFactoryBuilder(environment -> {
InitialContextFactory mockFactory = mock(InitialContextFactory.class);
Context mockContext = mock(Context.class);
when(mockFactory.getInitialContext(any())).thenReturn(mockContext);
when(mockContext.lookup("testConnection")).thenReturn(ds);
return mockFactory;
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@BeforeClass
public static void beforeClass() throws ClassNotFoundException, IOException, PropertyVetoException, NamingException, ConfigurationException {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
String url = configuration.getString("jdbc.url");
//obtain the connection that we will later supply from JNDI
SqlgGraph g = SqlgGraph.open(configuration);
ds = g.getSqlgDataSource().get(url);
// g.getTopology().close();
//change the connection url to be a JNDI one
configuration.setProperty("jdbc.url", "jndi:testConnection");
//set up the initial context
NamingManager.setInitialContextFactoryBuilder(environment -> {
InitialContextFactory mockFactory = mock(InitialContextFactory.class);
Context mockContext = mock(Context.class);
when(mockFactory.getInitialContext(any())).thenReturn(mockContext);
when(mockContext.lookup("testConnection")).thenReturn(ds);
return mockFactory;
});
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@BeforeClass
public static void beforeClass() throws Exception {
URL sqlProperties = Thread.currentThread().getContextClassLoader().getResource("sqlg.properties");
configuration = new PropertiesConfiguration(sqlProperties);
if (!configuration.containsKey("jdbc.url")) {
throw new IllegalArgumentException(String.format("SqlGraph configuration requires that the %s be set", "jdbc.url"));
}
String url = configuration.getString("jdbc.url");
//obtain the connection that we will later supply from JNDI
ds = new C3p0DataSourceFactory().setup(url, configuration).getDatasource();
//change the connection url to be a JNDI one
configuration.setProperty("jdbc.url", "jndi:testConnection");
//set up the initial context
NamingManager.setInitialContextFactoryBuilder(environment -> {
InitialContextFactory mockFactory = mock(InitialContextFactory.class);
Context mockContext = mock(Context.class);
when(mockFactory.getInitialContext(any())).thenReturn(mockContext);
when(mockContext.lookup("testConnection")).thenReturn(ds);
return mockFactory;
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBatchUpdatePersistentVerticesAllTypes() {
Assume.assumeTrue(this.sqlgGraph.features().vertex().properties().supportsFloatValues());
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals("b", this.sqlgGraph.v(v2.id()).value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v1.property("boolean", true);
v1.property("short", (short) 1);
v1.property("integer", 1);
v1.property("long", 1L);
v1.property("float", 1F);
v1.property("double", 1D);
v2.property("surname", "bb");
v2.property("boolean", false);
v2.property("short", (short) 2);
v2.property("integer", 2);
v2.property("long", 2L);
v2.property("float", 2F);
v2.property("double", 2D);
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.v(v1.id()).value("name"));
assertEquals(true, this.sqlgGraph.v(v1.id()).value("boolean"));
assertEquals((short) 1, this.sqlgGraph.v(v1.id()).<Short>value("short").shortValue());
assertEquals(1, this.sqlgGraph.v(v1.id()).<Integer>value("integer").intValue());
assertEquals(1L, this.sqlgGraph.v(v1.id()).<Long>value("long").longValue(), 0);
assertEquals(1F, this.sqlgGraph.v(v1.id()).<Float>value("float").floatValue(), 0);
assertEquals(1D, this.sqlgGraph.v(v1.id()).<Double>value("double").doubleValue(), 0);
assertEquals("bb", this.sqlgGraph.v(v2.id()).value("surname"));
assertEquals(false, this.sqlgGraph.v(v2.id()).value("boolean"));
assertEquals((short) 2, this.sqlgGraph.v(v2.id()).<Short>value("short").shortValue());
assertEquals(2, this.sqlgGraph.v(v2.id()).<Integer>value("integer").intValue());
assertEquals(2L, this.sqlgGraph.v(v2.id()).<Long>value("long").longValue(), 0);
assertEquals(2F, this.sqlgGraph.v(v2.id()).<Float>value("float").floatValue(), 0);
assertEquals(2D, this.sqlgGraph.v(v2.id()).<Double>value("double").doubleValue(), 0);
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBatchUpdatePersistentVerticesAllTypes() {
Assume.assumeTrue(this.sqlgGraph.features().vertex().properties().supportsFloatValues());
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "surname", "b");
this.sqlgGraph.tx().commit();
assertEquals("a", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals("b", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
this.sqlgGraph.tx().rollback();
this.sqlgGraph.tx().normalBatchModeOn();
v1.property("name", "aa");
v1.property("boolean", true);
v1.property("short", (short) 1);
v1.property("integer", 1);
v1.property("long", 1L);
v1.property("float", 1F);
v1.property("double", 1D);
v2.property("surname", "bb");
v2.property("boolean", false);
v2.property("short", (short) 2);
v2.property("integer", 2);
v2.property("long", 2L);
v2.property("float", 2F);
v2.property("double", 2D);
this.sqlgGraph.tx().commit();
assertEquals("aa", this.sqlgGraph.traversal().V(v1.id()).next().value("name"));
assertEquals(true, this.sqlgGraph.traversal().V(v1.id()).next().value("boolean"));
assertEquals((short) 1, this.sqlgGraph.traversal().V(v1.id()).next().<Short>value("short").shortValue());
assertEquals(1, this.sqlgGraph.traversal().V(v1.id()).next().<Integer>value("integer").intValue());
assertEquals(1L, this.sqlgGraph.traversal().V(v1.id()).next().<Long>value("long").longValue(), 0);
assertEquals(1F, this.sqlgGraph.traversal().V(v1.id()).next().<Float>value("float").floatValue(), 0);
assertEquals(1D, this.sqlgGraph.traversal().V(v1.id()).next().<Double>value("double").doubleValue(), 0);
assertEquals("bb", this.sqlgGraph.traversal().V(v2.id()).next().value("surname"));
assertEquals(false, this.sqlgGraph.traversal().V(v2.id()).next().value("boolean"));
assertEquals((short) 2, this.sqlgGraph.traversal().V(v2.id()).next().<Short>value("short").shortValue());
assertEquals(2, this.sqlgGraph.traversal().V(v2.id()).next().<Integer>value("integer").intValue());
assertEquals(2L, this.sqlgGraph.traversal().V(v2.id()).next().<Long>value("long").longValue(), 0);
assertEquals(2F, this.sqlgGraph.traversal().V(v2.id()).next().<Float>value("float").floatValue(), 0);
assertEquals(2D, this.sqlgGraph.traversal().V(v2.id()).next().<Double>value("double").doubleValue(), 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadingLocalDateTime() throws Exception {
Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "createOn", LocalDateTime.now());
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
//noinspection Duplicates
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v.id()).next();
assertTrue(vv.property("createOn").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
assertTrue(propertyTypeMap.containsKey("createOn"));
sqlgGraph1.tx().rollback();
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadingLocalDateTime() throws Exception {
Vertex v = this.sqlgGraph.addVertex(T.label, "Person", "createOn", LocalDateTime.now());
this.sqlgGraph.tx().commit();
this.sqlgGraph.close();
//noinspection Duplicates
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(configuration)) {
Vertex vv = sqlgGraph1.traversal().V(v.id()).next();
Assert.assertTrue(vv.property("createOn").isPresent());
Map<String, PropertyType> propertyTypeMap = sqlgGraph1.getTopology().getAllTables().get(SchemaTable.of(
sqlgGraph1.getSqlDialect().getPublicSchema(), "V_Person").toString());
Assert.assertTrue(propertyTypeMap.containsKey("createOn"));
sqlgGraph1.tx().rollback();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testVertexTransactionalCache() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person");
v1.addEdge("friend", v2);
Assert.assertEquals(1, vertexTraversal(v1).out("friend").count().next().intValue());
Vertex tmpV1 = this.sqlgGraph.v(v1.id());
tmpV1.addEdge("foe", v3);
//this should fail as v1's out edges will not be updated
Assert.assertEquals(1, vertexTraversal(tmpV1).out("foe").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(v1).out("foe").count().next().intValue());
this.sqlgGraph.tx().rollback();
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testVertexTransactionalCache() {
Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person");
v1.addEdge("friend", v2);
Assert.assertEquals(1, vertexTraversal(v1).out("friend").count().next().intValue());
Vertex tmpV1 = this.sqlgGraph.traversal().V(v1.id()).next();
tmpV1.addEdge("foe", v3);
//this should fail as v1's out edges will not be updated
Assert.assertEquals(1, vertexTraversal(tmpV1).out("foe").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(v1).out("foe").count().next().intValue());
this.sqlgGraph.tx().rollback();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEdgeBetweenVertices() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.v(person1.id());
person2 = this.sqlgGraph.v(person2.id());
person1.addEdge("friend", person2);
this.sqlgGraph.tx().commit();
Assert.assertEquals(1, vertexTraversal(person1).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(person2).in("friend").count().next().intValue());
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEdgeBetweenVertices() {
Vertex person1 = this.sqlgGraph.addVertex(T.label, "Person");
Vertex person2 = this.sqlgGraph.addVertex(T.label, "Person");
this.sqlgGraph.tx().commit();
person1 = this.sqlgGraph.traversal().V(person1.id()).next();
person2 = this.sqlgGraph.traversal().V(person2.id()).next();
person1.addEdge("friend", person2);
this.sqlgGraph.tx().commit();
Assert.assertEquals(1, vertexTraversal(person1).out("friend").count().next().intValue());
Assert.assertEquals(1, vertexTraversal(person2).in("friend").count().next().intValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.