input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_NotTerminated() {
BEParser parser = new BEParser("i1");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_NotTerminated() {
BEParser parser = new BEParser("i1".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_String_Exception_InsufficientContent() {
new BEParser("7:abcdef").readString();
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_String_Exception_InsufficientContent() {
new BEParser("7:abcdef".getBytes()).readString(charset);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doExecute(MagnetContext context) {
TorrentId torrentId = context.getMagnetUri().getTorrentId();
MetadataFetcher metadataFetcher = new MetadataFetcher(metadataService, torrentId);
context.getRouter().registerMessagingAgent(metadataFetcher);
// need to also receive Bitfields and Haves (without validation for the number of pieces...)
BitfieldCollectingConsumer bitfieldConsumer = new BitfieldCollectingConsumer();
context.getRouter().registerMessagingAgent(bitfieldConsumer);
getDescriptor(torrentId).start();
context.getMagnetUri().getPeerAddresses().forEach(address -> {
context.getSession().get().onPeerDiscovered(new InetPeer(address));
});
Torrent torrent = metadataFetcher.fetchTorrent();
Optional<AnnounceKey> announceKey = createAnnounceKey(context.getMagnetUri());
torrent = amendTorrent(torrent, context.getMagnetUri().getDisplayName(), announceKey);
if (announceKey.isPresent()) {
TrackerAnnouncer announcer = new TrackerAnnouncer(trackerService, torrent);
announcer.start();
}
context.setTorrent(torrent);
context.setBitfieldConsumer(bitfieldConsumer);
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void doExecute(MagnetContext context) {
TorrentId torrentId = context.getMagnetUri().getTorrentId();
MetadataConsumer metadataConsumer = new MetadataConsumer(metadataService, torrentId, config);
context.getRouter().registerMessagingAgent(metadataConsumer);
// need to also receive Bitfields and Haves (without validation for the number of pieces...)
BitfieldCollectingConsumer bitfieldConsumer = new BitfieldCollectingConsumer();
context.getRouter().registerMessagingAgent(bitfieldConsumer);
getDescriptor(torrentId).start();
context.getMagnetUri().getPeerAddresses().forEach(address -> {
context.getSession().get().onPeerDiscovered(new InetPeer(address));
});
Torrent torrent = metadataConsumer.waitForTorrent();
Optional<AnnounceKey> announceKey = createAnnounceKey(context.getMagnetUri());
torrent = amendTorrent(torrent, context.getMagnetUri().getDisplayName(), announceKey);
if (announceKey.isPresent()) {
TrackerAnnouncer announcer = new TrackerAnnouncer(trackerService, torrent);
announcer.start();
}
context.setTorrent(torrent);
context.setBitfieldConsumer(bitfieldConsumer);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_List1() {
BEParser parser = new BEParser("l4:spam4:eggsi1ee");
assertEquals(BEType.LIST, parser.readType());
assertArrayEquals(
new Object[] {"spam", "eggs", BigInteger.ONE},
parser.readList().toArray()
);
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_List1() {
BEParser parser = new BEParser("l4:spam4:eggsi1ee".getBytes());
assertEquals(BEType.LIST, parser.readType());
assertArrayEquals(
new Object[] {"spam".getBytes(charset), "eggs".getBytes(charset), BigInteger.ONE},
parser.readList().toArray()
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test//(expected = Exception.class)
public void testParse_Integer_Exception_NegativeZero() {
// not sure why the protocol spec forbids negative zeroes,
// so let it be for now
BEParser parser = new BEParser("i-0e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ZERO.negate(), parser.readInteger());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test//(expected = Exception.class)
public void testParse_Integer_Exception_NegativeZero() {
// not sure why the protocol spec forbids negative zeroes,
// so let it be for now
BEParser parser = new BEParser("i-0e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ZERO.negate(), parser.readInteger());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_NotTerminated() {
BEParser parser = new BEParser("i1");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_NotTerminated() {
BEParser parser = new BEParser("i1".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_Integer1() {
BEParser parser = new BEParser("i1e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE, parser.readInteger());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_Integer1() {
BEParser parser = new BEParser("i1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE, parser.readInteger());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConnection() throws InvalidMessageException, IOException {
PeerConnection connection = new PeerConnection(mock(Peer.class), clientChannel);
Message message;
server.writeMessage(new Handshake(new byte[20], new byte[20]));
message = connection.readMessageNow();
assertNotNull(message);
assertEquals(MessageType.HANDSHAKE, message.getType());
server.writeMessage(new Bitfield(new byte[2 << 9]));
message = connection.readMessageNow();
assertNotNull(message);
assertEquals(MessageType.BITFIELD, message.getType());
assertEquals(2 << 9, ((Bitfield) message).getBitfield().length);
server.writeMessage(new Request(1, 2, 3));
message = connection.readMessageNow();
assertNotNull(message);
assertEquals(MessageType.REQUEST, message.getType());
assertEquals(1, ((Request) message).getPieceIndex());
assertEquals(2, ((Request) message).getOffset());
assertEquals(3, ((Request) message).getLength());
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConnection() throws InvalidMessageException, IOException {
IPeerConnection connection = new PeerConnection(mock(Peer.class), clientChannel);
Message message;
server.writeMessage(new Handshake(new byte[20], new byte[20]));
message = connection.readMessageNow();
assertNotNull(message);
assertEquals(MessageType.HANDSHAKE, message.getType());
server.writeMessage(new Bitfield(new byte[2 << 9]));
message = connection.readMessageNow();
assertNotNull(message);
assertEquals(MessageType.BITFIELD, message.getType());
assertEquals(2 << 9, ((Bitfield) message).getBitfield().length);
server.writeMessage(new Request(1, 2, 3));
message = connection.readMessageNow();
assertNotNull(message);
assertEquals(MessageType.REQUEST, message.getType());
assertEquals(1, ((Request) message).getPieceIndex());
assertEquals(2, ((Request) message).getOffset());
assertEquals(3, ((Request) message).getLength());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_String_Exception_LengthStartsWithZero() {
new BEParser("0:").readString();
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_String_Exception_LengthStartsWithZero() {
new BEParser("0:".getBytes()).readString(charset);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_List1() {
BEParser parser = new BEParser("l4:spam4:eggsi1ee");
assertEquals(BEType.LIST, parser.readType());
assertArrayEquals(
new Object[] {"spam", "eggs", BigInteger.ONE},
parser.readList().toArray()
);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_List1() {
BEParser parser = new BEParser("l4:spam4:eggsi1ee".getBytes());
assertEquals(BEType.LIST, parser.readType());
assertArrayEquals(
new Object[] {"spam".getBytes(charset), "eggs".getBytes(charset), BigInteger.ONE},
parser.readList().toArray()
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test//(expected = Exception.class)
public void testParse_Integer_Exception_NegativeZero() {
// not sure why the protocol spec forbids negative zeroes,
// so let it be for now
BEParser parser = new BEParser("i-0e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ZERO.negate(), parser.readInteger());
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test//(expected = Exception.class)
public void testParse_Integer_Exception_NegativeZero() {
// not sure why the protocol spec forbids negative zeroes,
// so let it be for now
BEParser parser = new BEParser("i-0e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ZERO.negate(), parser.readInteger());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_Integer1() {
BEParser parser = new BEParser("i1e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE, parser.readInteger());
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_Integer1() {
BEParser parser = new BEParser("i1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE, parser.readInteger());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_UnexpectedTokens() {
BEParser parser = new BEParser("i-1-e");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_UnexpectedTokens() {
BEParser parser = new BEParser("i-1-e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDescriptors_WriteSingleFile() {
String fileName = "1-single.bin";
long chunkSize = 16;
long fileSize = chunkSize * 4;
Torrent torrent = mockTorrent(fileName, fileSize, chunkSize,
new byte[][] {
CryptoUtil.getSha1Digest(Arrays.copyOfRange(SINGLE_FILE, 0, 16)),
CryptoUtil.getSha1Digest(Arrays.copyOfRange(SINGLE_FILE, 16, 32)),
CryptoUtil.getSha1Digest(Arrays.copyOfRange(SINGLE_FILE, 32, 48)),
CryptoUtil.getSha1Digest(Arrays.copyOfRange(SINGLE_FILE, 48, 64)),
},
mockTorrentFile(fileSize, fileName));
IDataDescriptor descriptor = new DataDescriptor(dataAccessFactory, configurationService, torrent);
List<IChunkDescriptor> chunks = descriptor.getChunkDescriptors();
assertEquals(4, chunks.size());
chunks.get(0).writeBlock(sequence(8), 0);
chunks.get(0).writeBlock(sequence(8), 8);
assertTrue(chunks.get(0).verify());
chunks.get(1).writeBlock(sequence(4), 0);
chunks.get(1).writeBlock(sequence(4), 4);
chunks.get(1).writeBlock(sequence(4), 8);
chunks.get(1).writeBlock(sequence(4), 12);
assertTrue(chunks.get(1).verify());
// reverse order
chunks.get(2).writeBlock(sequence(11), 5);
chunks.get(2).writeBlock(sequence(3), 2);
chunks.get(2).writeBlock(sequence(2), 0);
assertFalse(chunks.get(2).verify());
// "random" order
chunks.get(3).writeBlock(sequence(4), 4);
chunks.get(3).writeBlock(sequence(4), 0);
chunks.get(3).writeBlock(sequence(4), 12);
chunks.get(3).writeBlock(sequence(4), 8);
assertTrue(chunks.get(3).verify());
byte[] file = readBytesFromFile(new File(rootDirectory, fileName), (int) fileSize);
assertArrayEquals(SINGLE_FILE, file);
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testDescriptors_WriteSingleFile() {
String fileName = "1-single.bin";
IDataDescriptor descriptor = createDataDescriptor_SingleFile(fileName);
List<IChunkDescriptor> chunks = descriptor.getChunkDescriptors();
chunks.get(0).writeBlock(sequence(8), 0);
chunks.get(0).writeBlock(sequence(8), 8);
assertTrue(chunks.get(0).verify());
chunks.get(1).writeBlock(sequence(4), 0);
chunks.get(1).writeBlock(sequence(4), 4);
chunks.get(1).writeBlock(sequence(4), 8);
chunks.get(1).writeBlock(sequence(4), 12);
assertTrue(chunks.get(1).verify());
// reverse order
chunks.get(2).writeBlock(sequence(11), 5);
chunks.get(2).writeBlock(sequence(3), 2);
chunks.get(2).writeBlock(sequence(2), 0);
assertFalse(chunks.get(2).verify());
// "random" order
chunks.get(3).writeBlock(sequence(4), 4);
chunks.get(3).writeBlock(sequence(4), 0);
chunks.get(3).writeBlock(sequence(4), 12);
chunks.get(3).writeBlock(sequence(4), 8);
assertTrue(chunks.get(3).verify());
assertFileHasContents(new File(rootDirectory, fileName), SINGLE_FILE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s");
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString(charset));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void delete(String key) throws IOException {
Properties props = getProperty();
OutputStream fos = new FileOutputStream(propertyFile);
props.remove(key);
props.store(fos, "Delete '" + key + "' value");
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static void delete(String key) throws IOException {
delete(propertyFile, key);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void serverTreeItemSelected(TreeItem selectedItem, boolean refresh) {
this.itemSelected = selectedItem;
tree.setSelection(selectedItem);
text.setText(selectedItem.getText() + ":");
table.removeAll();
serverItemSelected();
if (refresh)
selectedItem.setData(ITEM_OPENED, false);
if (selectedItem.getData(ITEM_OPENED) == null
|| ((Boolean) (selectedItem.getData(ITEM_OPENED)) == false)) {
selectedItem.removeAll();
addDBTreeItem((Integer) selectedItem.getData(NODE_ID), selectedItem);
}
int dbs = service1.listDBs((Integer) selectedItem.getData(NODE_ID));
for (int i = 0; i < dbs; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { DB_PREFIX + i,
NodeType.DATABASE.toString() });
item.setData(NODE_ID, i);
item.setImage(dbImage);
item.setData(NODE_ID, i);
item.setData(NODE_TYPE, NodeType.DATABASE);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
private void serverTreeItemSelected(TreeItem selectedItem, boolean refresh) {
this.itemSelected = selectedItem;
tree.setSelection(selectedItem);
text.setText(selectedItem.getText() + ":");
table.removeAll();
serverItemSelected();
int amount = service1.listDBs((Integer) selectedItem.getData(NODE_ID));
if (selectedItem.getData(ITEM_OPENED) == null
|| ((Boolean) (selectedItem.getData(ITEM_OPENED)) == false)) {
selectedItem.removeAll();
for (int i = 0; i < amount; i++) {
TreeItem dbItem = new TreeItem(selectedItem, SWT.NONE);
dbItem.setText(DB_PREFIX + i);
dbItem.setData(NODE_ID, i);
dbItem.setData(NODE_TYPE, NodeType.DATABASE);
dbItem.setImage(dbImage);
}
selectedItem.setExpanded(true);
selectedItem.setData(ITEM_OPENED, true);
} else if (refresh){
}
for (int i = 0; i < amount; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { DB_PREFIX + i,
NodeType.DATABASE.toString() });
item.setData(NODE_ID, i);
item.setImage(dbImage);
item.setData(NODE_ID, i);
item.setData(NODE_TYPE, NodeType.DATABASE);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void execute() {
try {
server = service.listById(id);
jedis = new Jedis(server.getHost(), Integer.parseInt(server
.getPort()));
if (commands.size() > 0) {
RedisVersion version;
if (serverVersion.containsKey(String.valueOf(id))) {
version = serverVersion.get(String.valueOf(id));
} else {
version = getRedisVersion();
serverVersion.put(String.valueOf(id), version);
}
getCommand(version).command();
} else
command();
jedis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
public void execute() {
try {
server = service.listById(id);
jedis = new Jedis(server.getHost(), Integer.parseInt(server.getPort()));
command();
jedis.close();
} catch (IOException e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void pasteContainer(int sourceId, int sourceDb, String sourceContainer, int targetId, int targetDb, String targetContainer, boolean copy, boolean overwritten) {
ListContainerAllKeys command = new ListContainerAllKeysFactory(sourceId, sourceDb, sourceContainer).getListContainerAllKeys();
command.execute();
Set<Node> nodes = command.getKeys();
for(Node node: nodes) {
pasteKey(sourceId, sourceDb, node.getKey(), targetId, targetDb, targetContainer, copy, overwritten);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public void pasteContainer(int sourceId, int sourceDb, String sourceContainer, int targetId, int targetDb, String targetContainer, boolean copy, boolean overwritten) {
Set<Node> nodes = listContainerAllKeys(sourceId, sourceDb, sourceContainer);
for(Node node: nodes) {
pasteKey(sourceId, sourceDb, node.getKey(), targetId, targetDb, targetContainer, copy, overwritten);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void write(String key, String value) throws IOException {
Properties props = getProperty();
OutputStream fos = new FileOutputStream(propertyFile);
props.setProperty(key, value);
props.store(fos, "Update '" + key + "' value");
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static void write(String key, String value) throws IOException {
write(propertyFile, key, value);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean execute(DiagnosticContext context) {
if (context.getInputParams().isSkipLogs()) {
return true;
}
JsonNode diagNode = context.getTypedAttribute("diagNode", JsonNode.class);
boolean getAccess = context.getInputParams().isAccessLogs();
String commercialDir = SystemUtils.safeToString(context.getAttribute("commercialDir"));
logger.info("Processing logs and configuration files.");
JsonNode settings = diagNode.path("settings");
String name = diagNode.path("name").asText();
context.setAttribute("diagNodeName", name);
String clusterName = context.getClusterName();
JsonNode nodePaths = settings.path("path");
JsonNode defaultPaths = settings.path("default").path("path");
String config = nodePaths.path("config").asText();
String logs = nodePaths.path("logs").asText();
String conf = nodePaths.path("conf").asText();
String home = nodePaths.path("home").asText();
String defaultLogs = defaultPaths.path("logs").asText();
String defaultConf = defaultPaths.path("conf").asText();
try {
List<String> fileDirs = new ArrayList<>();
context.setAttribute("tempFileDirs", fileDirs);
// Create a directory for this node
String nodeDir = context.getTempDir() + SystemProperties.fileSeparator + name + Constants.logDir;
fileDirs.add(nodeDir);
Files.createDirectories(Paths.get(nodeDir));
FileFilter configFilter = new WildcardFileFilter("*.yml");
String configFileLoc = determineConfigLocation(conf, config, home, defaultConf);
logs = determineLogLocation(home, logs, defaultLogs);
// Copy the config directory
String configDest = nodeDir + SystemProperties.fileSeparator + "config";
FileUtils.copyDirectory(new File(configFileLoc), new File(configDest), configFilter, true);
if (commercialDir != "") {
File comm = new File(configFileLoc + SystemProperties.fileSeparator + commercialDir);
if (comm.exists()) {
FileUtils.copyDirectory(comm, new File(configDest + SystemProperties.fileSeparator + commercialDir), true);
}
}
File scripts = new File(configFileLoc + SystemProperties.fileSeparator + "scripts");
if (scripts.exists()) {
FileUtils.copyDirectory(scripts, new File(configDest + SystemProperties.fileSeparator + "scripts"), true);
}
// Creat the temp directory for the logs
File logDir = new File(logs);
File logDest = new File(nodeDir + SystemProperties.fileSeparator + "logs");
if (context.getInputParams().isArchivedLogs()) {
FileUtils.copyDirectory(logDir, logDest, true);
} else {
//Get the top level log, slow search, and slow index logs
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + ".log"), logDest);
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + "_index_indexing_slowlog.log"), logDest);
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + "_index_search_slowlog.log"), logDest);
if (getAccess) {
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + "_access.log"), logDest);
}
int majorVersion = Integer.parseInt(context.getVersion().split("\\.")[0]);
String patternString = null;
if (majorVersion > 2) {
patternString = clusterName + "-\\d{4}-\\d{2}-\\d{2}.log*";
} else {
patternString = clusterName + ".log.\\d{4}-\\d{2}-\\d{2}";
}
// Get the two most recent server log rollovers
//Pattern pattern = Pattern.compile(patternString);
FileFilter logFilter = new RegexFileFilter(patternString);
File[] logDirList = logDir.listFiles(logFilter);
Arrays.sort(logDirList, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
int limit = 2, count = 0;
for (File logListing : logDirList) {
if (count < limit) {
FileUtils.copyFileToDirectory(logListing, logDest);
count++;
} else {
break;
}
}
}
} catch (Exception e) {
logger.error("Error processing log and config files.", e);
}
logger.info("Finished processing logs and configuration files.");
return true;
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean execute(DiagnosticContext context) {
if (context.getInputParams().isSkipLogs() || ! context.isProcessLocal()) {
return true;
}
JsonNode diagNode = context.getTypedAttribute("diagNode", JsonNode.class);
if(diagNode == null){
logger.error("Could not locate node running on current host.");
return true;
}
boolean getAccess = context.getInputParams().isAccessLogs();
String commercialDir = SystemUtils.safeToString(context.getAttribute("commercialDir"));
logger.info("Processing logs and configuration files.");
JsonNode settings = diagNode.path("settings");
Iterator<JsonNode> inputArgs = diagNode.path("jvm").path("input_arguments").iterator();
String name = diagNode.path("name").asText();
context.setAttribute("diagNodeName", name);
String clusterName = context.getClusterName();
JsonNode nodePaths = settings.path("path");
JsonNode defaultPaths = settings.path("default").path("path");
String inputArgsConfig = findConfigArg(inputArgs);
String config = nodePaths.path("config").asText();
String logs = nodePaths.path("logs").asText();
String conf = nodePaths.path("conf").asText();
String home = nodePaths.path("home").asText();
String defaultLogs = defaultPaths.path("logs").asText();
String defaultConf = defaultPaths.path("conf").asText();
try {
List<String> fileDirs = new ArrayList<>();
context.setAttribute("tempFileDirs", fileDirs);
// Create a directory for this node
String nodeDir = context.getTempDir() + SystemProperties.fileSeparator + name + Constants.logDir;
fileDirs.add(nodeDir);
Files.createDirectories(Paths.get(nodeDir));
FileFilter configFilter = new WildcardFileFilter("*.yml");
String configFileLoc = determineConfigLocation(conf, config, home, defaultConf, inputArgsConfig);
// Process the config directory
String configDest = nodeDir + SystemProperties.fileSeparator + "config";
File configDir = new File(configFileLoc);
if(configDir.exists() && configDir.listFiles().length > 0){
FileUtils.copyDirectory(configDir, new File(configDest), configFilter, true);
if (commercialDir != "") {
File comm = new File(configFileLoc + SystemProperties.fileSeparator + commercialDir);
if (comm.exists()) {
FileUtils.copyDirectory(comm, new File(configDest + SystemProperties.fileSeparator + commercialDir), true);
}
}
File scripts = new File(configFileLoc + SystemProperties.fileSeparator + "scripts");
if (scripts.exists()) {
FileUtils.copyDirectory(scripts, new File(configDest + SystemProperties.fileSeparator + "scripts"), true);
}
}
File logDest = new File(nodeDir + SystemProperties.fileSeparator + "logs");
logs = determineLogLocation(home, logs, defaultLogs);
File logDir = new File(logs);
if (logDir.exists() && logDir.listFiles().length > 0) {
if (context.getInputParams().isArchivedLogs()) {
FileUtils.copyDirectory(logDir, logDest, true);
} else {
//Get the top level log, slow search, and slow index logs
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + ".log"), logDest);
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + "_index_indexing_slowlog.log"), logDest);
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + "_index_search_slowlog.log"), logDest);
if (getAccess) {
FileUtils.copyFileToDirectory(new File(logs + SystemProperties.fileSeparator + clusterName + "_access.log"), logDest);
}
int majorVersion = Integer.parseInt(context.getVersion().split("\\.")[0]);
String patternString = null;
if (majorVersion > 2) {
patternString = clusterName + "-\\d{4}-\\d{2}-\\d{2}.log*";
} else {
patternString = clusterName + ".log.\\d{4}-\\d{2}-\\d{2}";
}
// Get the two most recent server log rollovers
//Pattern pattern = Pattern.compile(patternString);
FileFilter logFilter = new RegexFileFilter(patternString);
File[] logDirList = logDir.listFiles(logFilter);
Arrays.sort(logDirList, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
int limit = 2, count = 0;
for (File logListing : logDirList) {
if (count < limit) {
FileUtils.copyFileToDirectory(logListing, logDest);
count++;
} else {
break;
}
}
}
}
else {
logger.error("Configured log directory is not readable or does not exist: " + logDir.getAbsolutePath());
}
} catch (Exception e) {
logger.error("Error processing log and config files.", e);
}
logger.info("Finished processing logs and configuration files.");
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void extractDiagnosticArchive(String sourceInput) throws Exception {
TarArchiveInputStream archive = readDiagArchive(sourceInput);
logger.info("Extracting archive...");
try {
// Base archive name - it's not redundant like Intellij is complaining...
TarArchiveEntry tae = archive.getNextTarEntry();
// First actual archived entry
tae = archive.getNextTarEntry();
while (tae != null) {
String name = tae.getName();
int fileStart = name.indexOf("/");
name = name.substring(fileStart + 1);
archiveProcessor.process(archive, name);
tae = archive.getNextTarEntry();
}
} catch (IOException e) {
logger.info("Error extracting {}.", "", e);
throw new RuntimeException("Error extracting {} from archive.", e);
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public void extractDiagnosticArchive(String sourceInput) throws Exception {
logger.info("Extracting archive...");
try {
ZipFile zf = new ZipFile(new File(sourceInput));
archiveProcessor.init(zf);
Enumeration<ZipArchiveEntry> entries = zf.getEntriesInPhysicalOrder();
while(entries.hasMoreElements()){
ZipArchiveEntry tae = entries.nextElement();
String name = tae.getName();
int fileStart = name.indexOf("/");
name = name.substring(fileStart + 1);
archiveProcessor.process(zf.getInputStream(tae), name);
}
} catch (IOException e) {
logger.info("Error extracting {}.", "", e);
throw new RuntimeException("Error extracting {} from archive.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void zipResults(String dir) {
try {
File srcDir = new File(dir);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(dir + ".zip"));
out.setLevel(ZipOutputStream.DEFLATED);
SystemUtils.zipDir("", srcDir, out);
out.close();
logger.debug("Archive " + dir + ".zip was created");
FileUtils.deleteDirectory(srcDir);
logger.debug("Temp directory " + dir + " was deleted.");
} catch (Exception ioe) {
logger.error("Couldn't create archive.\n", ioe);
throw new RuntimeException(("Error creating compressed archive from statistics files." ));
}
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public void zipResults(String dir) {
try {
File srcDir = new File(dir);
FileOutputStream fout = new FileOutputStream(dir + ".tar.gz");
GZIPOutputStream gzout = new GZIPOutputStream(fout);
TarArchiveOutputStream taos = new TarArchiveOutputStream(gzout);
taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
//out.setLevel(ZipOutputStream.DEFLATED);
archiveResults(taos, srcDir, "");
taos.close();
logger.debug("Archive " + dir + ".zip was created");
FileUtils.deleteDirectory(srcDir);
logger.debug("Temp directory " + dir + " was deleted.");
} catch (Exception ioe) {
logger.error("Couldn't create archive.\n", ioe);
throw new RuntimeException(("Error creating compressed archive from statistics files."));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void createArchive(String dir, String archiveFileName) {
try {
File srcDir = new File(dir);
String filename = dir + "-" + archiveFileName + ".tar.gz";
FileOutputStream fout = new FileOutputStream(filename);
CompressorOutputStream cout = new GzipCompressorOutputStream(fout);
TarArchiveOutputStream taos = new TarArchiveOutputStream(cout);
taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
archiveResults(archiveFileName, taos, srcDir, "", true);
taos.close();
logger.info("Archive: " + filename + " was created");
} catch (Exception ioe) {
logger.info("Couldn't create archive. {}", ioe);
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public void createArchive(String dir, String archiveFileName) {
if(! createZipArchive(dir, archiveFileName)){
logger.info("Couldn't create zip archive. Trying tar.gz");
if(! createTarArchive(dir, archiveFileName)){
logger.info("Couldn't create tar.gz archive.");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void submitRequest(String url, String queryName, String destination){
HttpResponse response = null;
InputStream responseStream = null;
try{
FileOutputStream fos = new FileOutputStream(destination);
HttpGet httpget = new HttpGet(url);
response = client.execute(httpget);
try {
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null ){
checkResponseCode(queryName, response);
responseStream = entity.getContent();
IOUtils.copy(responseStream, fos);
}
else{
Files.write(Paths.get(destination), ("No results for:" + queryName).getBytes());
}
}
catch (Exception e){
logger.error("Error writing response for " + queryName + " to disk.", e);
} finally {
HttpClientUtils.closeQuietly(response);
Thread.sleep(2000);
}
}
catch (Exception e){
if (url.contains("_license")) {
logger.info("There were no licenses installed");
}
else if (e.getMessage().contains("401 Unauthorized")) {
logger.error("Auth failure", e);
throw new RuntimeException("Authentication failure: invalid login credentials.", e);
}
else {
logger.error("Diagnostic query: " + queryName + "failed.", e);
}
}
logger.info("Diagnostic query: " + queryName + " was retrieved and saved to disk.");
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
public void submitRequest(String url, String queryName, String destination){
HttpResponse response = null;
InputStream responseStream = null;
try{
HttpClient client = getClient();
FileOutputStream fos = new FileOutputStream(destination);
HttpGet httpget = new HttpGet(url);
response = client.execute(httpget);
try {
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null ){
checkResponseCode(queryName, response);
responseStream = entity.getContent();
IOUtils.copy(responseStream, fos);
}
else{
Files.write(Paths.get(destination), ("No results for:" + queryName).getBytes());
}
}
catch (Exception e){
logger.error("Error writing response for " + queryName + " to disk.", e);
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(client);
}
}
catch (Exception e){
if (url.contains("_license")) {
logger.info("There were no licenses installed");
}
else if (e.getMessage().contains("401 Unauthorized")) {
logger.error("Auth failure", e);
throw new RuntimeException("Authentication failure: invalid login credentials.", e);
}
else {
logger.error("Diagnostic query: " + queryName + "failed.", e);
}
}
logger.info("Diagnostic query: " + queryName + " was retrieved and saved to disk.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<Issue> parse(File report) throws IOException {
List<Issue> issues = new LinkedList<>();
PylintReportParser parser = new PylintReportParser();
for (Scanner sc = new Scanner(report.toPath(), fileSystem.encoding().name()); sc.hasNext(); ) {
String line = sc.nextLine();
Issue issue = parser.parseLine(line);
if (issue != null) {
issues.add(issue);
}
}
return issues;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
private List<Issue> parse(File report) throws IOException {
List<Issue> issues = new LinkedList<>();
PylintReportParser parser = new PylintReportParser();
Scanner sc;
for (sc = new Scanner(report.toPath(), fileSystem.encoding().name()); sc.hasNext(); ) {
String line = sc.nextLine();
Issue issue = parser.parseLine(line);
if (issue != null) {
issues.add(issue);
}
}
sc.close();
return issues;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void while_statement() {
setRootRule(PythonGrammar.WHILE_STMT);
WhileStatementImpl tree = parse("while foo:\n pass\nelse:\n pass", treeMaker::whileStatement);
FirstLastTokenVerifierVisitor visitor = spy(FirstLastTokenVerifierVisitor.class);
visitor.visitWhileStatement(tree);
verify(visitor).visitPassStatement((PassStatement) tree.body().statements().get(0));
verify(visitor).visitPassStatement((PassStatement) tree.elseBody().statements().get(0));
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void while_statement() {
setRootRule(PythonGrammar.WHILE_STMT);
WhileStatementImpl tree = parse("while foo:\n pass\nelse:\n pass", treeMaker::whileStatement);
FirstLastTokenVerifierVisitor visitor = spy(FirstLastTokenVerifierVisitor.class);
visitor.visitWhileStatement(tree);
verify(visitor).visitPassStatement((PassStatement) tree.body().statements().get(0));
verify(visitor).visitPassStatement((PassStatement) tree.elseClause().body().statements().get(0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static List<String> callCommand(String command, String[] environ) {
List<String> lines = new LinkedList<String>();
PythonPlugin.LOG.debug("Calling command: '{}'", command);
BufferedReader stdInput = null;
try {
Process p = null;
if(environ == null){
p = Runtime.getRuntime().exec(command);
} else {
p = Runtime.getRuntime().exec(command, environ);
}
stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
lines.add(s);
}
} catch (IOException e) {
throw new SonarException("Error calling command '" + command +
"', details: '" + e + "'");
} finally {
IOUtils.closeQuietly(stdInput);
}
return lines;
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
public static List<String> callCommand(String command, String[] environ) {
List<String> lines = new LinkedList<String>();
PythonPlugin.LOG.debug("Calling command: '{}'", command);
BufferedReader stdInput = null;
Process process = null;
try {
if(environ == null){
process = Runtime.getRuntime().exec(command);
} else {
process = Runtime.getRuntime().exec(command, environ);
}
stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = stdInput.readLine()) != null) {
lines.add(s);
}
} catch (IOException e) {
throw new SonarException("Error calling command '" + command +
"', details: '" + e + "'");
} finally {
IOUtils.closeQuietly(stdInput);
if (process != null) {
IOUtils.closeQuietly(process.getInputStream());
IOUtils.closeQuietly(process.getOutputStream());
IOUtils.closeQuietly(process.getErrorStream());
}
}
return lines;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public ForStatement forStatement(AstNode astNode) {
AstNode forStatementNode = astNode;
Token asyncToken = null;
if (astNode.is(PythonGrammar.ASYNC_STMT)) {
asyncToken = toPyToken(astNode.getFirstChild().getToken());
forStatementNode = astNode.getFirstChild(PythonGrammar.FOR_STMT);
}
Token forKeyword = toPyToken(forStatementNode.getFirstChild(PythonKeyword.FOR).getToken());
Token inKeyword = toPyToken(forStatementNode.getFirstChild(PythonKeyword.IN).getToken());
Token colon = toPyToken(forStatementNode.getFirstChild(PythonPunctuator.COLON).getToken());
List<Expression> expressions = expressionsFromExprList(forStatementNode.getFirstChild(PythonGrammar.EXPRLIST));
List<Expression> testExpressions = expressionsFromTest(forStatementNode.getFirstChild(PythonGrammar.TESTLIST));
AstNode firstSuite = forStatementNode.getFirstChild(PythonGrammar.SUITE);
Token firstIndent = firstSuite.getFirstChild(PythonTokenType.INDENT) == null ? null : toPyToken(firstSuite.getFirstChild(PythonTokenType.INDENT).getToken());
Token firstNewLine = firstSuite.getFirstChild(PythonTokenType.INDENT) == null ? null : toPyToken(firstSuite.getFirstChild(PythonTokenType.NEWLINE).getToken());
Token firstDedent = firstSuite.getFirstChild(PythonTokenType.DEDENT) == null ? null : toPyToken(firstSuite.getFirstChild(PythonTokenType.DEDENT).getToken());
StatementList body = getStatementListFromSuite(firstSuite);
AstNode lastSuite = forStatementNode.getLastChild(PythonGrammar.SUITE);
Token lastIndent = lastSuite.getFirstChild(PythonTokenType.INDENT) == null ? null : toPyToken(lastSuite.getFirstChild(PythonTokenType.INDENT).getToken());
Token lastNewLine = lastSuite.getFirstChild(PythonTokenType.INDENT) == null ? null : toPyToken(lastSuite.getFirstChild(PythonTokenType.NEWLINE).getToken());
Token lastDedent = lastSuite.getFirstChild(PythonTokenType.DEDENT) == null ? null : toPyToken(lastSuite.getFirstChild(PythonTokenType.DEDENT).getToken());
AstNode elseKeywordNode = forStatementNode.getFirstChild(PythonKeyword.ELSE);
Token elseKeyword = null;
Token elseColonKeyword = null;
if (elseKeywordNode != null) {
elseKeyword = toPyToken(elseKeywordNode.getToken());
elseColonKeyword = toPyToken(elseKeywordNode.getNextSibling().getToken());
}
StatementList elseBody = lastSuite == firstSuite ? null : getStatementListFromSuite(lastSuite);
return new ForStatementImpl(forStatementNode, forKeyword, expressions, inKeyword, testExpressions, colon, firstNewLine, firstIndent,
body, firstDedent, elseKeyword, elseColonKeyword, lastNewLine, lastIndent, elseBody, lastDedent, asyncToken);
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
public ForStatement forStatement(AstNode astNode) {
AstNode forStatementNode = astNode;
Token asyncToken = null;
if (astNode.is(PythonGrammar.ASYNC_STMT)) {
asyncToken = toPyToken(astNode.getFirstChild().getToken());
forStatementNode = astNode.getFirstChild(PythonGrammar.FOR_STMT);
}
Token forKeyword = toPyToken(forStatementNode.getFirstChild(PythonKeyword.FOR).getToken());
Token inKeyword = toPyToken(forStatementNode.getFirstChild(PythonKeyword.IN).getToken());
Token colon = toPyToken(forStatementNode.getFirstChild(PythonPunctuator.COLON).getToken());
List<Expression> expressions = expressionsFromExprList(forStatementNode.getFirstChild(PythonGrammar.EXPRLIST));
List<Expression> testExpressions = expressionsFromTest(forStatementNode.getFirstChild(PythonGrammar.TESTLIST));
AstNode firstSuite = forStatementNode.getFirstChild(PythonGrammar.SUITE);
StatementList body = getStatementListFromSuite(firstSuite);
AstNode lastSuite = forStatementNode.getLastChild(PythonGrammar.SUITE);
AstNode elseKeywordNode = forStatementNode.getFirstChild(PythonKeyword.ELSE);
Token elseKeyword = null;
Token elseColonKeyword = null;
if (elseKeywordNode != null) {
elseKeyword = toPyToken(elseKeywordNode.getToken());
elseColonKeyword = toPyToken(elseKeywordNode.getNextSibling().getToken());
}
Token lastIndent = firstSuite == lastSuite ? null : suiteIndent(lastSuite);
Token lastNewLine = firstSuite == lastSuite ? null : suiteNewLine(lastSuite);
Token lastDedent = firstSuite == lastSuite ? null : suiteDedent(lastSuite);
StatementList elseBody = firstSuite == lastSuite ? null : getStatementListFromSuite(lastSuite);
return new ForStatementImpl(forStatementNode, forKeyword, expressions, inKeyword, testExpressions, colon, suiteNewLine(firstSuite), suiteIndent(firstSuite),
body, suiteDedent(firstSuite), elseKeyword, elseColonKeyword, lastNewLine, lastIndent, elseBody, lastDedent, asyncToken);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void definition_callee_symbol() {
FileInput tree = parse(
"def fn(): pass",
"fn('foo')"
);
// TODO: create a symbol for function declaration
CallExpression callExpression = getCallExpression(tree);
assertThat(callExpression.calleeSymbol()).isNull();
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void definition_callee_symbol() {
FileInput tree = parse(
"def fn(): pass",
"fn('foo')"
);
assertNameAndQualifiedName(tree, "fn", null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void no_field() {
ClassDef empty = parseClass(
"class C: ",
" pass");
assertThat(empty.classFields()).isEmpty();
assertThat(empty.instanceFields()).isEmpty();
ClassDef empty2 = parseClass(
"class C:",
" def f(): pass");
assertThat(empty2.classFields()).isEmpty();
assertThat(empty2.instanceFields()).isEmpty();
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void no_field() {
ClassDef empty = parseClass(
"class C: ",
" pass");
assertThat(empty.classFields()).isEmpty();
assertThat(empty.instanceFields()).isEmpty();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void relative_import_symbols() {
FileInput tree = parse(
new SymbolTableBuilder("my_package.my_module"),
"from . import b"
);
Name b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("my_package.b");
// no package
tree = parse(
new SymbolTableBuilder("my_module"),
"from . import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("b");
// two levels up
tree = parse(
new SymbolTableBuilder("my_package.my_module"),
"from ..my_package import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME) && ((Name) t).name().equals("b"));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("my_package.b");
tree = parse(
new SymbolTableBuilder("my_package1.my_package2.my_module"),
"from ..other import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME) && ((Name) t).name().equals("b"));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("my_package1.other.b");
// overflow packages hierarchy
tree = parse(
new SymbolTableBuilder("my_package.my_module"),
"from ...my_package import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME) && ((Name) t).name().equals("b"));
assertThat(b.symbol().fullyQualifiedName()).isNull();
// no fully qualified module name
tree = parse(
new SymbolTableBuilder(),
"from . import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isNull();
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void relative_import_symbols() {
FileInput tree = parse(
new SymbolTableBuilder("my_package", "my_module.py"),
"from . import b"
);
Name b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("my_package.b");
// no package
tree = parse(
new SymbolTableBuilder("", "my_module.py"),
"from . import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("b");
// no package, init file
tree = parse(
new SymbolTableBuilder("", "__init__.py"),
"from . import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("b");
// two levels up
tree = parse(
new SymbolTableBuilder("my_package", "my_module.py"),
"from ..my_package import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME) && ((Name) t).name().equals("b"));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("my_package.b");
tree = parse(
new SymbolTableBuilder("my_package1.my_package2", "my_module.py"),
"from ..other import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME) && ((Name) t).name().equals("b"));
assertThat(b.symbol().fullyQualifiedName()).isEqualTo("my_package1.other.b");
// overflow packages hierarchy
tree = parse(
new SymbolTableBuilder("my_package", "my_module.py"),
"from ...my_package import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME) && ((Name) t).name().equals("b"));
assertThat(b.symbol().fullyQualifiedName()).isNull();
// no fully qualified module name
tree = parse(
new SymbolTableBuilder(),
"from . import b"
);
b = getFirstChild(tree, t -> t.is(Tree.Kind.NAME));
assertThat(b.symbol().fullyQualifiedName()).isNull();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<Issue> parse(File report) throws java.io.FileNotFoundException {
List<Issue> issues = new LinkedList<Issue>();
PylintReportParser parser = new PylintReportParser();
for(Scanner sc = new Scanner(report); sc.hasNext(); ) {
String line = sc.nextLine();
Issue issue = parser.parseLine(line);
if (issue != null){
issues.add(issue);
}
}
return issues;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
private List<Issue> parse(File report) throws IOException {
List<Issue> issues = new LinkedList<Issue>();
PylintReportParser parser = new PylintReportParser();
for(Scanner sc = new Scanner(report.toPath(), fileSystem.encoding().name()); sc.hasNext(); ) {
String line = sc.nextLine();
Issue issue = parser.parseLine(line);
if (issue != null){
issues.add(issue);
}
}
return issues;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public int size() {
Long size = JedisUtil.getJedis().dbSize();
return size.intValue();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public int size() {
Long size = Objects.requireNonNull(JedisUtil.getJedis()).dbSize();
return size.intValue();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
String token = (String) auth.getCredentials();
// 解密获得account,用于和数据库进行对比
String account = JWTUtil.getClaim(token, "account");
// 帐号为空
if (StringUtils.isBlank(account)) {
throw new AuthenticationException("Token中帐号为空(The account in Token is empty.)");
}
// 查询用户是否存在
UserDto userDto = new UserDto();
userDto.setAccount(account);
userDto = userMapper.selectOne(userDto);
if (userDto == null) {
throw new AuthenticationException("该帐号不存在(The account does not exist.)");
}
// 开始认证,要Token认证通过,且Redis中存在Token,且两个时间戳一致
if(JWTUtil.verify(token) && JedisUtil.exists(Constant.PREFIX_SHIRO_ACCESS + account)){
// Redis的时间戳
String currentTimeMillisRedis = JedisUtil.getObject(Constant.PREFIX_SHIRO_ACCESS + account).toString();
// 获取Token时间戳,与Redis的时间戳对比
if(JWTUtil.getClaim(token, "currentTimeMillis").equals(currentTimeMillisRedis)){
return new SimpleAuthenticationInfo(token, token, "userRealm");
}
}
throw new AuthenticationException("Token已过期(Token expired or incorrect.)");
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
String token = (String) auth.getCredentials();
// 解密获得account,用于和数据库进行对比
String account = JWTUtil.getClaim(token, "account");
// 帐号为空
if (StringUtils.isBlank(account)) {
throw new AuthenticationException("Token中帐号为空(The account in Token is empty.)");
}
// 查询用户是否存在
UserDto userDto = new UserDto();
userDto.setAccount(account);
userDto = userMapper.selectOne(userDto);
if (userDto == null) {
throw new AuthenticationException("该帐号不存在(The account does not exist.)");
}
// 开始认证,要Token认证通过,且Redis中存在Token,且两个时间戳一致
if(JWTUtil.verify(token) && JedisUtil.exists(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account)){
// Redis的时间戳
String currentTimeMillisRedis = JedisUtil.getObject(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account).toString();
// 获取Token时间戳,与Redis的时间戳对比
if(JWTUtil.getClaim(token, "currentTimeMillis").equals(currentTimeMillisRedis)){
return new SimpleAuthenticationInfo(token, token, "userRealm");
}
}
throw new AuthenticationException("Token已过期(Token expired or incorrect.)");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Set keys() {
Set<byte[]> keys = JedisUtil.getJedis().keys(new String("*").getBytes());
Set<Object> set = new HashSet<Object>();
for (byte[] bs : keys) {
set.add(SerializableUtil.unserializable(bs));
}
return set;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Set keys() {
Set<byte[]> keys = Objects.requireNonNull(JedisUtil.getJedis()).keys("*".getBytes());
Set<Object> set = new HashSet<Object>();
for (byte[] bs : keys) {
set.add(SerializableUtil.unserializable(bs));
}
return set;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void clear() throws CacheException {
JedisUtil.getJedis().flushDB();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void clear() throws CacheException {
Objects.requireNonNull(JedisUtil.getJedis()).flushDB();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private HashSet<String> extractOutputVariables(String stateMachineText) throws IOException {
InputStream is = new ByteArrayInputStream(stateMachineText.getBytes());
BufferedReader bReader = new BufferedReader(new InputStreamReader(is));
HashSet<String> outputVars = new HashSet<String>();
String line = bReader.readLine();
while (line != null) {
if (line.contains("var_out")) {
int startIndex = line.indexOf("var_out");
int lastIndex = startIndex;
while (lastIndex < line.length() && (Character.isLetter(line.charAt(lastIndex))
|| Character.isDigit(line.charAt(lastIndex))
|| line.charAt(lastIndex) == '_'
|| line.charAt(lastIndex) == '-')) {
lastIndex++;
}
if (lastIndex == line.length()) {
throw new IOException("Reached the end of the line while parsing variable name in line: '" + line
+ "'.");
}
String varName = line.substring(startIndex, lastIndex);
log.info("Found variable: " + varName);
outputVars.add(varName);
}
line = bReader.readLine();
}
return outputVars;
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
private HashSet<String> extractOutputVariables(String stateMachineText) throws IOException {
Set<String> names = ScXmlUtils.getAttributesValues(stateMachineText, "assign", "name");
return (HashSet<String>) names;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDefaultDataConsumerAccess(){
DataPipe thePipe = new DataPipe();
DataConsumer dc = thePipe.getDataConsumer();
Assert.assertNotNull(dc);
Assert.assertNotNull(dc.getFlags());
Assert.assertFalse(dc.getFlags().get(0).get());
Assert.assertEquals(10000, dc.getMaxNumberOfLines());
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testDefaultDataConsumerAccess() {
DataPipe thePipe = new DataPipe();
DataConsumer dc = thePipe.getDataConsumer();
dc.setFlags(new Hashtable<String, AtomicBoolean>());
Assert.assertNotNull(dc);
Assert.assertNotNull(dc.getFlags());
Assert.assertEquals(10000, dc.getMaxNumberOfLines());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String getProperty(String name) {
Properties properties = new Properties();
Resource resource = new ClassPathResource("server.properties");
FileInputStream fileInputStream = null;
String value = null;
try {
fileInputStream = new FileInputStream(resource.getFile());
properties.load(new FileInputStream(resource.getFile()));
value = properties.getProperty(name);
} catch (Exception e) {
}finally {
if(fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return value;
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public String getProperty(String name) {
Properties properties = new Properties();
FileInputStream fileInputStream = null;
String value = null;
try {
fileInputStream = new FileInputStream(this.getProperties());
properties.load(fileInputStream);
value = properties.getProperty(name);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping("/file/downloadFile")
@ResponseBody
public void downloadFile(String path, String name, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment;filename=" + name);
response.setContentType("application/octet-stream");
String peersUrl = getPeers().getServerAddress();
if(StrUtil.isNotBlank(getPeersGroupName())){
peersUrl += "/"+getPeersGroupName();
}else {
peersUrl += "/group1";
}
BufferedInputStream in = null;
try {
URL url = new URL(peersUrl+path+"/"+name);
in = new BufferedInputStream(url.openStream());
response.reset();
response.setContentType("application/octet-stream");
String os = System.getProperty("os.name");
if(os.toLowerCase().indexOf("windows") != -1){
name = new String(name.getBytes("GBK"), "ISO-8859-1");
}else{
//判断浏览器
String userAgent = request.getHeader("User-Agent").toLowerCase();
if(userAgent.indexOf("msie") > 0){
name = URLEncoder.encode(name, "ISO-8859-1");
}
}
response.setHeader("Content-Disposition","attachment;filename=" + name);
// 将网络输入流转换为输出流
int i;
while ((i = in.read()) != -1) {
response.getOutputStream().write(i);
}
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@RequestMapping("/file/downloadFile")
@ResponseBody
public void downloadFile(String path, String name, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment;filename=" + name);
response.setContentType("application/octet-stream");
String peersUrl = getPeers().getServerAddress();
if(StrUtil.isNotBlank(getPeersGroupName())){
peersUrl += "/"+getPeersGroupName();
}else {
peersUrl += "/group1";
}
BufferedInputStream in = null;
try {
URL url = new URL(peersUrl+path+"/"+name);
in = new BufferedInputStream(url.openStream());
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
// 将网络输入流转换为输出流
int i;
while ((i = in.read()) != -1) {
response.getOutputStream().write(i);
}
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void addSuper(@NotNull Type superclass) {
this.superclass = superclass;
table.addSuper(superclass.table);
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public void addSuper(@NotNull Type superclass) {
this.superclass = superclass;
table.setSuper(superclass.table);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "&";
break;
default:
System.err.println("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "@";
break;
default:
Util.msg("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getFirstNode().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getFirstNode();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getSingle().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getSingle();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void buildTupleType() {
Scope bt = BaseTuple.getTable();
String[] tuple_methods = {
"__add__", "__contains__", "__eq__", "__ge__", "__getnewargs__",
"__gt__", "__iter__", "__le__", "__len__", "__lt__", "__mul__",
"__ne__", "__new__", "__rmul__", "count", "index"
};
for (String m : tuple_methods) {
bt.update(m, newLibUrl("stdtypes"), newFunc(), METHOD);
}
Binding b = bt.update("__getslice__", newDataModelUrl("object.__getslice__"),
newFunc(), METHOD);
b.markDeprecated();
bt.update("__getitem__", newDataModelUrl("object.__getitem__"), newFunc(), METHOD);
bt.update("__iter__", newDataModelUrl("object.__iter__"), newFunc(), METHOD);
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
String[] list(String... names) {
return names;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void setAttrType(@NotNull Type targetType, @NotNull Type v) {
if (targetType.isUnknownType()) {
Analyzer.self.putProblem(this, "Can't set attribute for UnknownType");
return;
}
// new attr, mark the type as "mutated"
if (targetType.getTable().lookupAttr(attr.id) == null ||
!targetType.getTable().lookupAttrType(attr.id).equals(v))
{
targetType.setMutated(true);
}
targetType.getTable().insert(attr.id, attr, v, ATTRIBUTE);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void setAttrType(@NotNull Type targetType, @NotNull Type v) {
if (targetType.isUnknownType()) {
Analyzer.self.putProblem(this, "Can't set attribute for UnknownType");
return;
}
// new attr, mark the type as "mutated"
if (targetType.table.lookupAttr(attr.id) == null ||
!targetType.table.lookupAttrType(attr.id).equals(v))
{
targetType.setMutated(true);
}
targetType.table.insert(attr.id, attr, v, ATTRIBUTE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int compareTo(@NotNull Object o) {
return getFirstNode().getStart() - ((Binding)o).getFirstNode().getStart();
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public int compareTo(@NotNull Object o) {
return getSingle().getStart() - ((Binding)o).getSingle().getStart();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean equals(Object obj) {
if (obj instanceof Function) {
Function fo = (Function) obj;
return (fo.getFile().equals(getFile()) && fo.start == start);
} else {
return false;
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean equals(Object obj) {
if (obj instanceof Function) {
Function fo = (Function) obj;
return (fo.file.equals(file) && fo.start == start);
} else {
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void writeSymJson(@NotNull Binding binding, JsonGenerator json) throws IOException {
if (binding.start < 0) {
return;
}
String name = binding.node.name;
boolean isExported = !(
Binding.Kind.VARIABLE == binding.kind ||
Binding.Kind.PARAMETER == binding.kind ||
Binding.Kind.SCOPE == binding.kind ||
Binding.Kind.ATTRIBUTE == binding.kind ||
(name != null && (name.length() == 0 || name.startsWith("lambda%"))));
String path = binding.qname.replace("%20", ".");
if (!seenDef.contains(path)) {
seenDef.add(path);
if (binding.kind == Binding.Kind.METHOD) {
neMethods++;
}
if (binding.kind == Binding.Kind.CLASS) {
neClass++;
}
json.writeStartObject();
json.writeStringField("name", name);
json.writeStringField("path", path);
json.writeStringField("file", binding.file);
json.writeNumberField("identStart", binding.start);
json.writeNumberField("identEnd", binding.end);
json.writeNumberField("defStart", binding.bodyStart);
json.writeNumberField("defEnd", binding.bodyEnd);
json.writeBooleanField("exported", isExported);
json.writeStringField("kind", kindName(binding.kind));
if (binding.kind == Binding.Kind.METHOD || binding.kind == Binding.Kind.CLASS_METHOD) {
// get args expression
String argExpr = null;
Type t = binding.type;
if (t.isUnionType()) {
t = t.asUnionType().firstUseful();
}
if (t != null && t.isFuncType()) {
Function func = t.asFuncType().func;
if (func != null) {
argExpr = func.getArgList();
}
}
String signature;
if (argExpr == null) {
signature = "";
} else if (argExpr.equals("()")) {
signature = "";
} else {
signature = argExpr;
}
json.writeStringField("signature", signature);
}
String doc = binding.findDocString().value;
if (doc != null) {
json.writeStringField("docstring", doc);
}
json.writeEndObject();
}
}
#location 65
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void writeSymJson(@NotNull Binding binding, JsonGenerator json) throws IOException {
if (binding.start < 0) {
return;
}
String name = binding.node.name;
boolean isExported = !(
Binding.Kind.VARIABLE == binding.kind ||
Binding.Kind.PARAMETER == binding.kind ||
Binding.Kind.SCOPE == binding.kind ||
Binding.Kind.ATTRIBUTE == binding.kind ||
(name != null && (name.length() == 0 || name.startsWith("lambda%"))));
String path = binding.qname.replace("%20", ".");
if (!seenDef.contains(path)) {
seenDef.add(path);
json.writeStartObject();
json.writeStringField("name", name);
json.writeStringField("path", path);
json.writeStringField("file", binding.file);
json.writeNumberField("identStart", binding.start);
json.writeNumberField("identEnd", binding.end);
json.writeNumberField("defStart", binding.bodyStart);
json.writeNumberField("defEnd", binding.bodyEnd);
json.writeBooleanField("exported", isExported);
json.writeStringField("kind", kindName(binding.kind));
if (binding.kind == Binding.Kind.METHOD || binding.kind == Binding.Kind.CLASS_METHOD) {
// get args expression
Type t = binding.type;
if (t.isUnionType()) {
t = t.asUnionType().firstUseful();
}
if (t != null && t.isFuncType()) {
Function func = t.asFuncType().func;
if (func != null) {
String signature = func.getArgList();
if (!signature.equals("")) {
signature = "(" + signature + ")";
}
json.writeStringField("signature", signature);
}
}
}
Str docstring = binding.findDocString();
if (docstring != null) {
json.writeStringField("docstring", docstring.value);
}
json.writeEndObject();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void restrictNumType(Compare compare, Scope s1, Scope s2) {
List<Node> ops = compare.ops;
if (ops.size() > 0 && ops.get(0) instanceof Op) {
String opname = ((Op) ops.get(0)).name;
Node left = compare.left;
Node right = compare.comparators.get(0);
if (!left.isName()) {
Node tmp = right;
right = left;
left = tmp;
opname = Op.invert(opname);
}
if (left.isName()) {
Name leftName = left.asName();
Type leftType = left.resolve(s1);
Type rightType = right.resolve(s1);
NumType trueType = Analyzer.self.builtins.BaseNum;
NumType falseType = Analyzer.self.builtins.BaseNum;
if (opname.equals("<") || opname.equals("<=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newUpper = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setUpper(newUpper.getUpper());
falseType = new NumType(leftType.asNumType());
falseType.setLower(newUpper.getUpper());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else if (opname.equals(">") || opname.equals(">=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newLower = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setLower(newLower.getLower());
falseType = new NumType(leftType.asNumType());
falseType.setUpper(newLower.getLower());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else {
trueType = leftType.asNumType();
}
Binding b = s1.lookup(leftName.id).get(0);
s1.update(leftName.id, new Binding(leftName.id, b.getNode(), trueType, Binding.Kind.SCOPE));
s2.update(leftName.id, new Binding(leftName.id, b.getNode(), falseType, Binding.Kind.SCOPE));
}
}
}
#location 46
#vulnerability type NULL_DEREFERENCE | #fixed code
public void restrictNumType(Compare compare, Scope s1, Scope s2) {
List<Node> ops = compare.ops;
if (ops.size() > 0 && ops.get(0) instanceof Op) {
Op op = ((Op) ops.get(0));
String opname = op.name;
if (op.isNumberComparisonOp()) {
Node left = compare.left;
Node right = compare.comparators.get(0);
if (!left.isName()) {
Node tmp = right;
right = left;
left = tmp;
opname = Op.invert(opname);
}
if (left.isName()) {
Name leftName = left.asName();
Type leftType = left.resolve(s1);
Type rightType = right.resolve(s1);
NumType trueType = Analyzer.self.builtins.BaseNum;
NumType falseType = Analyzer.self.builtins.BaseNum;
if (opname.equals("<") || opname.equals("<=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newUpper = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setUpper(newUpper.getUpper());
falseType = new NumType(leftType.asNumType());
falseType.setLower(newUpper.getUpper());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
} else if (opname.equals(">") || opname.equals(">=")) {
if (leftType.isNumType() && rightType.isNumType()) {
NumType newLower = rightType.asNumType();
trueType = new NumType(leftType.asNumType());
trueType.setLower(newLower.getLower());
falseType = new NumType(leftType.asNumType());
falseType.setUpper(newLower.getLower());
} else {
Analyzer.self.putProblem(test, "comparing non-numbers: " + leftType + " and " + rightType);
}
}
Node loc;
List<Binding> bs = s1.lookup(leftName.id);
if (bs != null && bs.size() > 0) {
loc = bs.get(0).getNode();
} else {
loc = leftName;
}
s1.update(leftName.id, new Binding(leftName.id, loc, trueType, Binding.Kind.SCOPE));
s2.update(leftName.id, new Binding(leftName.id, loc, falseType, Binding.Kind.SCOPE));
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NotNull
@Override
public Type transform(@NotNull State s) {
ClassType classType = new ClassType(getName().id, s);
List<Type> baseTypes = new ArrayList<>();
for (Node base : bases) {
Type baseType = transformExpr(base, s);
if (baseType.isClassType()) {
classType.addSuper(baseType);
} else if (baseType.isUnionType()) {
for (Type b : baseType.asUnionType().getTypes()) {
classType.addSuper(b);
break;
}
} else {
Analyzer.self.putProblem(base, base + " is not a class");
}
baseTypes.add(baseType);
}
// Bind ClassType to name here before resolving the body because the
// methods need this type as self.
Binder.bind(s, name, classType, Binding.Kind.CLASS);
if (body != null) {
transformExpr(body, classType.getTable());
}
return Type.CONT;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@NotNull
@Override
public Type transform(@NotNull State s) {
if (locator != null) {
Type existing = transformExpr(locator, s);
if (existing instanceof ClassType) {
if (body != null) {
transformExpr(body, existing.table);
}
return Type.CONT;
}
}
ClassType classType = new ClassType(name.id, s);
if (base != null) {
Type baseType = transformExpr(base, s);
if (baseType.isClassType()) {
classType.addSuper(baseType);
} else {
Analyzer.self.putProblem(base, base + " is not a class");
}
}
// Bind ClassType to name here before resolving the body because the
// methods need this type as self.
Binder.bind(s, name, classType, Binding.Kind.CLASS);
if (body != null) {
transformExpr(body, classType.getTable());
}
return Type.CONT;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void bindIter(@NotNull Scope s, Node target, @NotNull Node iter, Binding.Kind kind) {
Type iterType = Node.resolveExpr(iter, s);
if (iterType.isListType()) {
bind(s, target, iterType.asListType().getElementType(), kind);
} else if (iterType.isTupleType()) {
bind(s, target, iterType.asTupleType().toListType().getElementType(), kind);
} else {
List<Binding> ents = iterType.getTable().lookupAttr("__iter__");
for (Binding ent : ents) {
if (ent == null || !ent.getType().isFuncType()) {
if (!iterType.isUnknownType()) {
iter.addWarning("not an iterable type: " + iterType);
}
bind(s, target, Indexer.idx.builtins.unknown, kind);
} else {
bind(s, target, ent.getType().asFuncType().getReturnType(), kind);
}
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void bindIter(@NotNull Scope s, Node target, @NotNull Node iter, Binding.Kind kind) {
Type iterType = Node.resolveExpr(iter, s);
if (iterType.isListType()) {
bind(s, target, iterType.asListType().getElementType(), kind);
} else if (iterType.isTupleType()) {
bind(s, target, iterType.asTupleType().toListType().getElementType(), kind);
} else {
List<Binding> ents = iterType.getTable().lookupAttr("__iter__");
if (ents != null) {
for (Binding ent : ents) {
if (ent.getType().isFuncType()) {
bind(s, target, ent.getType().asFuncType().getReturnType(), kind);
} else {
iter.addWarning("not an iterable type: " + iterType);
bind(s, target, Indexer.idx.builtins.unknown, kind);
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NotNull
@Override
public Type transform(State s) {
Type ltype = transformExpr(left, s);
Type rtype;
// boolean operations
if (op == Op.And) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS1());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() && rtype.isTrue()) {
return new BoolType(BoolType.Value.True);
} else if (ltype.isFalse() || rtype.isFalse()) {
return new BoolType(BoolType.Value.False);
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State falseState = State.merge(ltype.asBool().getS2(), rtype.asBool().getS2());
return new BoolType(rtype.asBool().getS1(), falseState);
} else {
return new BoolType(BoolType.Value.Undecided);
}
}
if (op == Op.Or) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS2());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() || rtype.isTrue()) {
return new BoolType(BoolType.Value.True);
} else if (ltype.isFalse() && rtype.isFalse()) {
return new BoolType(BoolType.Value.False);
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State trueState = State.merge(ltype.asBool().getS1(), rtype.asBool().getS1());
return new BoolType(trueState, rtype.asBool().getS2());
} else {
return new BoolType(BoolType.Value.Undecided);
}
}
rtype = transformExpr(right, s);
if (ltype.isUnknownType() || rtype.isUnknownType()) {
return Analyzer.self.builtins.unknown;
}
// Don't do specific things about string types at the moment
if (ltype == Analyzer.self.builtins.BaseStr && rtype == Analyzer.self.builtins.BaseStr) {
return Analyzer.self.builtins.BaseStr;
}
// try to figure out actual result
if (ltype.isNumType() && rtype.isNumType()) {
FloatType leftNum = ltype.asNumType();
FloatType rightNum = rtype.asNumType();
if (op == Op.Add) {
return FloatType.add(leftNum, rightNum);
}
if (op == Op.Sub) {
return FloatType.sub(leftNum, rightNum);
}
if (op == Op.Mul) {
return FloatType.mul(leftNum, rightNum);
}
if (op == Op.Div) {
return FloatType.div(leftNum, rightNum);
}
// comparison
if (op == Op.Lt || op == Op.Gt) {
Node leftNode = left;
FloatType trueType, falseType;
Op op1 = op;
if (!left.isName()) {
leftNode = right;
FloatType tmpNum = rightNum;
rightNum = leftNum;
leftNum = tmpNum;
op1 = Op.invert(op1);
}
if (op1 == Op.Lt) {
if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l < r, then l's upper bound is r's upper bound
trueType = new FloatType(leftNum);
trueType.setUpper(rightNum.getUpper());
// false branch: if l > r, then l's lower bound is r's lower bound
falseType = new FloatType(leftNum);
falseType.setLower(rightNum.getLower());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
if (op1 == Op.Gt) {
if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// undecided, need to transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l > r, then l's lower bound is r's lower bound
trueType = new FloatType(leftNum);
trueType.setLower(rightNum.getLower());
// false branch: if l < r, then l's upper bound is r's upper bound
falseType = new FloatType(leftNum);
falseType.setUpper(rightNum.getUpper());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
}
}
Analyzer.self.putProblem(this, "operator " + op + " cannot be applied on operands " + ltype + " and " + rtype);
return ltype;
}
#location 115
#vulnerability type NULL_DEREFERENCE | #fixed code
@NotNull
@Override
public Type transform(State s) {
Type ltype = transformExpr(left, s);
Type rtype;
// boolean operations
if (op == Op.And) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS1());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() && rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() || rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State falseState = State.merge(ltype.asBool().getS2(), rtype.asBool().getS2());
return new BoolType(rtype.asBool().getS1(), falseState);
} else {
return Analyzer.self.builtins.BaseBool;
}
}
if (op == Op.Or) {
if (ltype.isUndecidedBool()) {
rtype = transformExpr(right, ltype.asBool().getS2());
} else {
rtype = transformExpr(right, s);
}
if (ltype.isTrue() || rtype.isTrue()) {
return Analyzer.self.builtins.True;
} else if (ltype.isFalse() && rtype.isFalse()) {
return Analyzer.self.builtins.False;
} else if (ltype.isUndecidedBool() && rtype.isUndecidedBool()) {
State trueState = State.merge(ltype.asBool().getS1(), rtype.asBool().getS1());
return new BoolType(trueState, rtype.asBool().getS2());
} else {
return Analyzer.self.builtins.BaseBool;
}
}
rtype = transformExpr(right, s);
if (ltype.isUnknownType() || rtype.isUnknownType()) {
return Analyzer.self.builtins.unknown;
}
// Don't do specific things about string types at the moment
if (ltype == Analyzer.self.builtins.BaseStr && rtype == Analyzer.self.builtins.BaseStr) {
return Analyzer.self.builtins.BaseStr;
}
// try to figure out actual result
if (ltype.isIntType() && rtype.isIntType()) {
IntType leftNum = ltype.asIntType();
IntType rightNum = rtype.asIntType();
if (op == Op.Add) {
return IntType.add(leftNum, rightNum);
}
if (op == Op.Sub) {
return IntType.sub(leftNum, rightNum);
}
if (op == Op.Mul) {
return IntType.mul(leftNum, rightNum);
}
if (op == Op.Div) {
return IntType.div(leftNum, rightNum);
}
// comparison
if (op == Op.Lt || op == Op.Gt) {
Node leftNode = left;
IntType trueType, falseType;
Op op1 = op;
if (!left.isName()) {
leftNode = right;
IntType tmpNum = rightNum;
rightNum = leftNum;
leftNum = tmpNum;
op1 = Op.invert(op1);
}
if (op1 == Op.Lt) {
if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l < r, then l's upper bound is r's upper bound
trueType = new IntType(leftNum);
trueType.setUpper(rightNum.getUpper());
// false branch: if l > r, then l's lower bound is r's lower bound
falseType = new IntType(leftNum);
falseType.setLower(rightNum.getLower());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
if (op1 == Op.Gt) {
if (leftNum.gt(rightNum)) {
return Analyzer.self.builtins.True;
} else if (leftNum.lt(rightNum)) {
return Analyzer.self.builtins.False;
} else {
// undecided, need to transfer bound information
State s1 = s.copy();
State s2 = s.copy();
if (leftNode.isName()) {
// true branch: if l > r, then l's lower bound is r's lower bound
trueType = new IntType(leftNum);
trueType.setLower(rightNum.getLower());
// false branch: if l < r, then l's upper bound is r's upper bound
falseType = new IntType(leftNum);
falseType.setUpper(rightNum.getUpper());
String id = leftNode.asName().id;
for (Binding b : s.lookup(id)) {
Node loc = b.getNode();
s1.update(id, new Binding(id, loc, trueType, b.getKind()));
s2.update(id, new Binding(id, loc, falseType, b.getKind()));
}
}
return new BoolType(s1, s2);
}
}
}
}
Analyzer.self.putProblem(this, "operator " + op + " cannot be applied on operands " + ltype + " and " + rtype);
return ltype;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void buildFunctionType() {
Scope t = BaseFunction.getTable();
for (String s : list("func_doc", "__doc__", "func_name", "__name__", "__module__")) {
t.update(s, new Url(DATAMODEL_URL), BaseStr, ATTRIBUTE);
}
Binding b = synthetic(t, "func_closure", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
b.markReadOnly();
synthetic(t, "func_code", new Url(DATAMODEL_URL), unknown(), ATTRIBUTE);
synthetic(t, "func_defaults", new Url(DATAMODEL_URL), newTuple(), ATTRIBUTE);
synthetic(t, "func_globals", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
synthetic(t, "func_dict", new Url(DATAMODEL_URL),
new DictType(BaseStr, Indexer.idx.builtins.unknown), ATTRIBUTE);
// Assume any function can become a method, for simplicity.
for (String s : list("__func__", "im_func")) {
synthetic(t, s, new Url(DATAMODEL_URL), new FunType(), METHOD);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
String[] list(String... names) {
return names;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void createStreams(final String host) throws Exception {
appServerPort = randomFreeLocalPort();
streams = KafkaMusicExample.createChartsStreams(CLUSTER.bootstrapServers(),
CLUSTER.schemaRegistryUrl(),
appServerPort,
TestUtils.tempDirectory().getPath(),
host);
int count = 0;
final int maxTries = 3;
while (count <= maxTries) {
try {
// Starts the Rest Service on the provided host:port
restProxy = KafkaMusicExample.startRestProxy(streams, new HostInfo(host, appServerPort));
} catch (final Exception ex) {
log.error("Could not start Rest Service due to: " + ex.toString());
}
count++;
}
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
private void createStreams(final String host) throws Exception {
appServerPort = randomFreeLocalPort();
streams = KafkaMusicExample.createChartsStreams(CLUSTER.bootstrapServers(),
CLUSTER.schemaRegistryUrl(),
appServerPort,
TestUtils.tempDirectory().getPath(),
host);
int count = 0;
final int maxTries = 3;
while (count <= maxTries) {
try {
// Starts the Rest Service on the provided host:port
restProxy = KafkaMusicExample.startRestProxy(streams, new HostInfo(host, appServerPort));
break;
} catch (final Exception ex) {
log.error("Could not start Rest Service due to: " + ex.toString());
}
count++;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public ReturnT<String> add(XxlConfNode xxlConfNode, XxlConfUser loginUser, String loginEnv) {
// valid
if (StringUtils.isBlank(xxlConfNode.getAppname())) {
return new ReturnT<String>(500, "AppName不可为空");
}
// project permission
if (!ifHasProjectPermission(loginUser, loginEnv, xxlConfNode.getAppname())) {
return new ReturnT<String>(500, "您没有该项目的配置权限,请联系管理员开通");
}
// valid group
XxlConfProject group = xxlConfProjectDao.load(xxlConfNode.getAppname());
if (group==null) {
return new ReturnT<String>(500, "AppName非法");
}
// valid env
if (StringUtils.isBlank(xxlConfNode.getEnv())) {
return new ReturnT<String>(500, "配置Env不可为空");
}
XxlConfEnv xxlConfEnv = xxlConfEnvDao.load(xxlConfNode.getEnv());
if (xxlConfEnv == null) {
return new ReturnT<String>(500, "配置Env非法");
}
// valid key
if (StringUtils.isBlank(xxlConfNode.getKey())) {
return new ReturnT<String>(500, "配置Key不可为空");
}
xxlConfNode.setKey(xxlConfNode.getKey().trim());
XxlConfNode existNode = xxlConfNodeDao.load(xxlConfNode.getEnv(), xxlConfNode.getKey());
if (existNode != null) {
return new ReturnT<String>(500, "配置Key已存在,不可重复添加");
}
if (!xxlConfNode.getKey().startsWith(xxlConfNode.getAppname())) {
return new ReturnT<String>(500, "配置Key格式非法");
}
// valid title
if (StringUtils.isBlank(xxlConfNode.getTitle())) {
return new ReturnT<String>(500, "配置描述不可为空");
}
// value force null to ""
if (xxlConfNode.getValue() == null) {
xxlConfNode.setValue("");
}
// add node
xxlConfManager.set(xxlConfNode.getEnv(), xxlConfNode.getKey(), xxlConfNode.getValue());
xxlConfNodeDao.insert(xxlConfNode);
// node log
XxlConfNodeLog nodeLog = new XxlConfNodeLog();
nodeLog.setEnv(existNode.getEnv());
nodeLog.setKey(existNode.getKey());
nodeLog.setTitle(existNode.getTitle() + "(配置新增)" );
nodeLog.setValue(existNode.getValue());
nodeLog.setOptuser(loginUser.getUsername());
xxlConfNodeLogDao.add(nodeLog);
return ReturnT.SUCCESS;
}
#location 59
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public ReturnT<String> add(XxlConfNode xxlConfNode, XxlConfUser loginUser, String loginEnv) {
// valid
if (StringUtils.isBlank(xxlConfNode.getAppname())) {
return new ReturnT<String>(500, "AppName不可为空");
}
// project permission
if (!ifHasProjectPermission(loginUser, loginEnv, xxlConfNode.getAppname())) {
return new ReturnT<String>(500, "您没有该项目的配置权限,请联系管理员开通");
}
// valid group
XxlConfProject group = xxlConfProjectDao.load(xxlConfNode.getAppname());
if (group==null) {
return new ReturnT<String>(500, "AppName非法");
}
// valid env
if (StringUtils.isBlank(xxlConfNode.getEnv())) {
return new ReturnT<String>(500, "配置Env不可为空");
}
XxlConfEnv xxlConfEnv = xxlConfEnvDao.load(xxlConfNode.getEnv());
if (xxlConfEnv == null) {
return new ReturnT<String>(500, "配置Env非法");
}
// valid key
if (StringUtils.isBlank(xxlConfNode.getKey())) {
return new ReturnT<String>(500, "配置Key不可为空");
}
xxlConfNode.setKey(xxlConfNode.getKey().trim());
XxlConfNode existNode = xxlConfNodeDao.load(xxlConfNode.getEnv(), xxlConfNode.getKey());
if (existNode != null) {
return new ReturnT<String>(500, "配置Key已存在,不可重复添加");
}
if (!xxlConfNode.getKey().startsWith(xxlConfNode.getAppname())) {
return new ReturnT<String>(500, "配置Key格式非法");
}
// valid title
if (StringUtils.isBlank(xxlConfNode.getTitle())) {
return new ReturnT<String>(500, "配置描述不可为空");
}
// value force null to ""
if (xxlConfNode.getValue() == null) {
xxlConfNode.setValue("");
}
// add node
xxlConfManager.set(xxlConfNode.getEnv(), xxlConfNode.getKey(), xxlConfNode.getValue());
xxlConfNodeDao.insert(xxlConfNode);
// node log
XxlConfNodeLog nodeLog = new XxlConfNodeLog();
nodeLog.setEnv(xxlConfNode.getEnv());
nodeLog.setKey(xxlConfNode.getKey());
nodeLog.setTitle(xxlConfNode.getTitle() + "(配置新增)" );
nodeLog.setValue(xxlConfNode.getValue());
nodeLog.setOptuser(loginUser.getUsername());
xxlConfNodeLogDao.add(nodeLog);
return ReturnT.SUCCESS;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public ZooKeeper getClient(){
if (zooKeeper==null) {
try {
if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) {
if (zooKeeper==null) { // 二次校验,防止并发创建client
try {
zooKeeper = new ZooKeeper(zkaddress, 10000, watcher); // TODO,本地变量方式,成功才会赋值
if (zkdigest!=null && zkdigest.trim().length()>0) {
zooKeeper.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password"
}
zooKeeper.exists(zkpath, false); // sync
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
INSTANCE_INIT_LOCK.unlock();
}
logger.info(">>>>>>>>>> xxl-conf, XxlZkClient init success.");
}
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
if (zooKeeper == null) {
throw new XxlConfException("XxlZkClient.zooKeeper is null.");
}
return zooKeeper;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public ZooKeeper getClient(){
if (zooKeeper == null) {
try {
zooKeeper = new ZooKeeper(zkaddress, 10000, watcher); // TODO,本地变量方式,成功才会赋值
if (zkdigest != null && zkdigest.trim().length() > 0) {
zooKeeper.addAuthInfo("digest", zkdigest.getBytes()); // like "account:password"
}
zooKeeper.exists(zkpath, false); // sync
connectedSemaphore.await();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
} catch (KeeperException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (zooKeeper == null) {
throw new XxlConfException("XxlZkClient.zooKeeper is null.");
}
return zooKeeper;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public ZooKeeper getClient(){
if (zooKeeper==null) {
try {
if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) {
if (zooKeeper==null) { // 二次校验,防止并发创建client
try {
zooKeeper = new ZooKeeper(zkaddress, 10000, watcher); // TODO,本地变量方式,成功才会赋值
if (zkdigest!=null && zkdigest.trim().length()>0) {
zooKeeper.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password"
}
zooKeeper.exists(zkpath, false); // sync
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
INSTANCE_INIT_LOCK.unlock();
}
logger.info(">>>>>>>>>> xxl-conf, XxlZkClient init success.");
}
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
if (zooKeeper == null) {
throw new XxlConfException("XxlZkClient.zooKeeper is null.");
}
return zooKeeper;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public ZooKeeper getClient(){
if (zooKeeper==null) {
try {
if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) {
if (zooKeeper==null) { // 二次校验,防止并发创建client
// init new-client
ZooKeeper newZk = null;
try {
newZk = new ZooKeeper(zkaddress, 10000, watcher);
if (zkdigest!=null && zkdigest.trim().length()>0) {
newZk.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password"
}
newZk.exists(zkpath, false); // sync wait until succcess conn
// set success new-client
zooKeeper = newZk;
logger.info(">>>>>>>>>> xxl-conf, XxlZkClient init success.");
} catch (Exception e) {
// close fail new-client
if (newZk != null) {
newZk.close();
}
logger.error(e.getMessage(), e);
} finally {
INSTANCE_INIT_LOCK.unlock();
}
}
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
if (zooKeeper == null) {
throw new XxlConfException("XxlZkClient.zooKeeper is null.");
}
return zooKeeper;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUnwrapConnection() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
StubConnection unwrapped = connection.unwrap(StubConnection.class);
Assert.assertTrue("unwrapped connection is not instance of StubConnection: " + unwrapped, (unwrapped != null && unwrapped instanceof StubConnection));
}
finally
{
ds.shutdown();
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUnwrapConnection() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
StubConnection unwrapped = connection.unwrap(StubConnection.class);
Assert.assertTrue("unwrapped connection is not instance of StubConnection: " + unwrapped, (unwrapped != null && unwrapped instanceof StubConnection));
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testShutdown2() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.shutdown();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testShutdown2() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.close();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" max=%d%4$s, avg=%d%4$s, med=%d%4$s\n", max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
}
#location 34
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long counter = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
counter += runner.getCounter();
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" %s max=%d%5$s, avg=%d%5$s, med=%d%5$s\n", (Boolean.getBoolean("showCounter") ? "Counter=" + counter : ""), max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testOverflow()
{
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
list.add(new StubStatement());
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testOverflow()
{
ArrayList<Statement> verifyList = new ArrayList<>();
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
StubStatement statement = new StubStatement();
list.add(statement);
verifyList.add(statement);
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
Assert.assertSame(verifyList.get(i), list.get(i));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@HikariInject
public ResultSet executeQuery() throws SQLException
{
IHikariResultSetProxy resultSet = (IHikariResultSetProxy) __executeQuery();
resultSet.setProxyStatement(this);
return (ResultSet) resultSet;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@HikariInject
public ResultSet executeQuery() throws SQLException
{
try
{
IHikariResultSetProxy resultSet = (IHikariResultSetProxy) __executeQuery();
if (resultSet == null)
{
return null;
}
resultSet.setProxyStatement(this);
return (ResultSet) resultSet;
}
catch (SQLException e)
{
throw checkException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testShutdown1() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
final HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread() {
public void run() {
try
{
if (ds.getConnection() != null)
{
PoolUtilities.quietlySleep(TimeUnit.SECONDS.toMillis(1));
}
}
catch (SQLException e)
{
}
}
};
threads[i].setDaemon(true);
threads[i].start();
}
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.shutdown();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
#location 43
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testShutdown1() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
final HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread() {
public void run() {
try
{
if (ds.getConnection() != null)
{
PoolUtilities.quietlySleep(TimeUnit.SECONDS.toMillis(1));
}
}
catch (SQLException e)
{
}
}
};
threads[i].setDaemon(true);
threads[i].start();
}
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.close();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" max=%d%4$s, avg=%d%4$s, med=%d%4$s\n", max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
}
#location 34
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long counter = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
counter += runner.getCounter();
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" %s max=%d%5$s, avg=%d%5$s, med=%d%5$s\n", (Boolean.getBoolean("showCounter") ? "Counter=" + counter : ""), max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rampUpDownTest() throws SQLException, InterruptedException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(60);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "250");
HikariDataSource ds = new HikariDataSource(config);
ds.setIdleTimeout(1000);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
Connection[] connections = new Connection[ds.getMaximumPoolSize()];
for (int i = 0; i < connections.length; i++)
{
connections[i] = ds.getConnection();
}
Assert.assertSame("Totals connections not as expected", 60, TestElf.getPool(ds).getTotalConnections());
for (Connection connection : connections)
{
connection.close();
}
Thread.sleep(2500);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
ds.shutdown();
}
#location 35
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rampUpDownTest() throws SQLException, InterruptedException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(60);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "250");
HikariDataSource ds = new HikariDataSource(config);
ds.setIdleTimeout(1000);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
Connection[] connections = new Connection[ds.getMaximumPoolSize()];
for (int i = 0; i < connections.length; i++)
{
connections[i] = ds.getConnection();
}
Assert.assertSame("Totals connections not as expected", 60, TestElf.getPool(ds).getTotalConnections());
for (Connection connection : connections)
{
connection.close();
}
Thread.sleep(2500);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
ds.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMaxLifetime() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "100");
HikariDataSource ds = new HikariDataSource(config);
try
{
System.clearProperty("com.zaxxer.hikari.housekeeping.periodMs");
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(2000);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 51
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testMaxLifetime() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "100");
HikariDataSource ds = new HikariDataSource(config);
try
{
System.clearProperty("com.zaxxer.hikari.housekeeping.periodMs");
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(2000);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testShutdown3() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(5);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() == 5);
ds.shutdown();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testShutdown3() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(5);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() == 5);
ds.close();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Connection getConnection() throws SQLException
{
final long start = System.currentTimeMillis();
final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
long timeout = connectionTimeout;
try {
do {
final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (bagEntry == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
if (now > bagEntry.expirationTime || (now - bagEntry.lastAccess > 1000L && !isConnectionAlive(bagEntry.connection, timeout))) {
closeConnection(bagEntry); // Throw away the dead connection and try again
timeout = connectionTimeout - elapsedTimeMs(start);
continue;
}
final IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, bagEntry);
if (leakDetectionThreshold != 0) {
proxyConnection.captureStack(leakDetectionThreshold, houseKeepingExecutorService);
}
if (isRecordMetrics) {
bagEntry.lastOpenTime = now;
}
return proxyConnection;
}
while (timeout > 0L);
}
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally {
context.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout()),
lastConnectionFailure.getAndSet(null));
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
public Connection getConnection() throws SQLException
{
final long start = System.currentTimeMillis();
final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
long timeout = connectionTimeout;
try {
do {
final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (bagEntry == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
if (now > bagEntry.expirationTime || (now - bagEntry.lastAccess > 1000L && !isConnectionAlive(bagEntry.connection, timeout))) {
closeConnection(bagEntry); // Throw away the dead connection and try again
timeout = connectionTimeout - elapsedTimeMs(start);
continue;
}
LeakTask leakTask = (leakDetectionThreshold == 0) ? NO_LEAK : new LeakTask(leakDetectionThreshold, houseKeepingExecutorService);
final IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, bagEntry, leakTask);
if (isRecordMetrics) {
bagEntry.lastOpenTime = now;
}
return proxyConnection;
}
while (timeout > 0L);
}
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally {
context.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout()),
lastConnectionFailure.getAndSet(null));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConnectionIdleFill() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(10);
config.setConnectionTimeout(1000);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Connection connection1 = ds.getConnection();
Connection connection2 = ds.getConnection();
Connection connection3 = ds.getConnection();
Connection connection4 = ds.getConnection();
Connection connection5 = ds.getConnection();
Connection connection6 = ds.getConnection();
Connection connection7 = ds.getConnection();
Thread.sleep(1200);
Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 3, TestElf.getPool(ds).getIdleConnections());
connection1.close();
connection2.close();
connection3.close();
connection4.close();
connection5.close();
connection6.close();
connection7.close();
Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 10, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 41
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConnectionIdleFill() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(10);
config.setConnectionTimeout(1000);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Connection connection1 = ds.getConnection();
Connection connection2 = ds.getConnection();
Connection connection3 = ds.getConnection();
Connection connection4 = ds.getConnection();
Connection connection5 = ds.getConnection();
Connection connection6 = ds.getConnection();
Connection connection7 = ds.getConnection();
Thread.sleep(1200);
Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 3, TestElf.getPool(ds).getIdleConnections());
connection1.close();
connection2.close();
connection3.close();
connection4.close();
connection5.close();
connection6.close();
connection7.close();
Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 10, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoCommit() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setAutoCommit(true);
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setAutoCommit(false);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertTrue(connection2.getAutoCommit());
connection2.close();
}
finally
{
ds.shutdown();
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoCommit() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setAutoCommit(true);
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setAutoCommit(false);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertTrue(connection2.getAutoCommit());
connection2.close();
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBackfill() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(4);
config.setConnectionTimeout(500);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
// This will take the pool down to zero
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT some, thing FROM somewhere WHERE something=?");
Assert.assertNotNull(statement);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
try
{
statement.getMaxFieldSize();
Assert.fail();
}
catch (Exception e)
{
Assert.assertSame(SQLException.class, e.getClass());
}
// The connection will be ejected from the pool here
connection.close();
Assert.assertSame("Totals connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
// This will cause a backfill
connection = ds.getConnection();
connection.close();
Assert.assertTrue("Totals connections not as expected", TestElf.getPool(ds).getTotalConnections() > 0);
Assert.assertTrue("Idle connections not as expected", TestElf.getPool(ds).getIdleConnections() > 0);
}
finally
{
ds.shutdown();
}
}
#location 56
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBackfill() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(4);
config.setConnectionTimeout(500);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
// This will take the pool down to zero
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT some, thing FROM somewhere WHERE something=?");
Assert.assertNotNull(statement);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
try
{
statement.getMaxFieldSize();
Assert.fail();
}
catch (Exception e)
{
Assert.assertSame(SQLException.class, e.getClass());
}
// The connection will be ejected from the pool here
connection.close();
Assert.assertSame("Totals connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
// This will cause a backfill
connection = ds.getConnection();
connection.close();
Assert.assertTrue("Totals connections not as expected", TestElf.getPool(ds).getTotalConnections() > 0);
Assert.assertTrue("Idle connections not as expected", TestElf.getPool(ds).getIdleConnections() > 0);
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testShutdown4() throws SQLException
{
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
PoolUtilities.quietlySleep(300);
ds.shutdown();
long start = System.currentTimeMillis();
while (PoolUtilities.elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5) && threadCount() > 0)
{
PoolUtilities.quietlySleep(250);
}
Assert.assertSame("Thread was leaked", 0, threadCount());
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testShutdown4() throws SQLException
{
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
PoolUtilities.quietlySleep(300);
ds.close();
long start = System.currentTimeMillis();
while (PoolUtilities.elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5) && threadCount() > 0)
{
PoolUtilities.quietlySleep(250);
}
Assert.assertSame("Thread was leaked", 0, threadCount());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreate() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT * FROM device WHERE device_id=?");
Assert.assertNotNull(statement);
statement.setInt(1, 0);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
Assert.assertFalse(resultSet.next());
resultSet.close();
statement.close();
connection.close();
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 42
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCreate() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT * FROM device WHERE device_id=?");
Assert.assertNotNull(statement);
statement.setInt(1, 0);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
Assert.assertFalse(resultSet.next());
resultSet.close();
statement.close();
connection.close();
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCatalog() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setCatalog("test");
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setCatalog("other");
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertEquals("test", connection2.getCatalog());
connection2.close();
}
finally
{
ds.shutdown();
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCatalog() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setCatalog("test");
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setCatalog("other");
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertEquals("test", connection2.getCatalog());
connection2.close();
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testOverflow()
{
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
list.add(new StubStatement());
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
}
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testOverflow()
{
ArrayList<Statement> verifyList = new ArrayList<>();
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
StubStatement statement = new StubStatement();
list.add(statement);
verifyList.add(statement);
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
Assert.assertSame(verifyList.get(i), list.get(i));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDoubleClose() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Connection connection = ds.getConnection();
connection.close();
connection.close();
}
finally
{
ds.shutdown();
}
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDoubleClose() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Connection connection = ds.getConnection();
connection.close();
connection.close();
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConnectionRetries3() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(2);
config.setConnectionTimeout(2800);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
final Connection connection1 = ds.getConnection();
final Connection connection2 = ds.getConnection();
Assert.assertNotNull(connection1);
Assert.assertNotNull(connection2);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.schedule(new Runnable() {
public void run()
{
try
{
connection1.close();
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}, 800, TimeUnit.MILLISECONDS);
long start = System.currentTimeMillis();
try
{
Connection connection3 = ds.getConnection();
connection3.close();
long elapsed = System.currentTimeMillis() - start;
Assert.assertTrue("Waited too long to get a connection.", (elapsed >= 700) && (elapsed < 950));
}
catch (SQLException e)
{
Assert.fail("Should not have timed out.");
}
finally
{
scheduler.shutdownNow();
ds.shutdown();
}
}
#location 49
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConnectionRetries3() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(2);
config.setConnectionTimeout(2800);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
final Connection connection1 = ds.getConnection();
final Connection connection2 = ds.getConnection();
Assert.assertNotNull(connection1);
Assert.assertNotNull(connection2);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.schedule(new Runnable() {
public void run()
{
try
{
connection1.close();
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}, 800, TimeUnit.MILLISECONDS);
long start = System.currentTimeMillis();
try
{
Connection connection3 = ds.getConnection();
connection3.close();
long elapsed = System.currentTimeMillis() - start;
Assert.assertTrue("Waited too long to get a connection.", (elapsed >= 700) && (elapsed < 950));
}
catch (SQLException e)
{
Assert.fail("Should not have timed out.");
}
finally
{
scheduler.shutdownNow();
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTransactionIsolation() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection2.getTransactionIsolation());
connection2.close();
}
finally
{
ds.shutdown();
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTransactionIsolation() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection2.getTransactionIsolation());
connection2.close();
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMaxLifetime2() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(800);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 47
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testMaxLifetime2() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(800);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String... args)
{
if (args.length < 3)
{
System.err.println("Usage: <poolname> <threads> <poolsize>");
System.err.println(" <poolname> 'hikari' or 'bone'");
System.exit(0);
}
THREADS = Integer.parseInt(args[1]);
POOL_MAX = Integer.parseInt(args[2]);
Benchmark1 benchmarks = new Benchmark1();
if (args[0].equals("hikari"))
{
benchmarks.ds = benchmarks.setupHikari();
System.out.printf("Benchmarking HikariCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("bone"))
{
benchmarks.ds = benchmarks.setupBone();
System.out.printf("Benchmarking BoneCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else
{
System.err.println("Start with one of: hikari, bone");
System.exit(0);
}
System.out.println("\nMixedBench");
System.out.println(" Warming up JIT");
benchmarks.startMixedBench(100, 10000);
System.out.println(" MixedBench Final Timing Runs");
long elapsed = 0;
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
System.out.printf("Elapsed time for timing runs (excluding thread start): %dms\n", TimeUnit.NANOSECONDS.toMillis(elapsed));
System.out.println("\nBoneBench");
System.out.println(" Warming up JIT");
benchmarks.startSillyBench(THREADS);
System.out.println(" BoneBench Final Timing Run");
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
}
#location 43
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String... args)
{
if (args.length < 3)
{
System.err.println("Usage: <poolname> <threads> <poolsize>");
System.err.println(" <poolname> 'hikari' or 'bone'");
System.exit(0);
}
THREADS = Integer.parseInt(args[1]);
POOL_MAX = Integer.parseInt(args[2]);
Benchmark1 benchmarks = new Benchmark1();
if (args[0].equals("hikari"))
{
benchmarks.ds = benchmarks.setupHikari();
System.out.printf("Benchmarking HikariCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("bone"))
{
benchmarks.ds = benchmarks.setupBone();
System.out.printf("Benchmarking BoneCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("dbpool"))
{
benchmarks.ds = benchmarks.setupDbPool();
System.out.printf("Benchmarking DbPool - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("c3p0"))
{
benchmarks.ds = benchmarks.setupC3P0();
System.out.printf("Benchmarking C3P0 - %d threads, %d connections", THREADS, POOL_MAX);
}
else
{
System.err.println("Start with one of: hikari, bone");
System.exit(0);
}
System.out.println("\nMixedBench");
System.out.println(" Warming up JIT");
benchmarks.startMixedBench(100, 10000);
System.out.println(" MixedBench Final Timing Runs");
long elapsed = 0;
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
System.out.printf("Elapsed time for timing runs (excluding thread start): %dms\n", TimeUnit.NANOSECONDS.toMillis(elapsed));
System.out.println("\nBoneBench");
System.out.println(" Warming up JIT");
benchmarks.startSillyBench(THREADS);
System.out.println(" BoneBench Final Timing Run");
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void startCrackedSession(ProtocolLibLoginSource source, StoredProfile profile, String username) {
BukkitLoginSession loginSession = new BukkitLoginSession(username, profile);
plugin.getLoginSessions().put(player.getAddress().toString(), loginSession);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void startCrackedSession(ProtocolLibLoginSource source, StoredProfile profile, String username) {
BukkitLoginSession loginSession = new BukkitLoginSession(username, profile);
plugin.putSession(player.getAddress(), loginSession);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSessionRestore(RestoreSessionEvent restoreSessionEvent) {
Player player = restoreSessionEvent.getPlayer();
String id = '/' + player.getAddress().getAddress().getHostAddress() + ':' + player.getAddress().getPort();
BukkitLoginSession session = plugin.getLoginSessions().get(id);
if (session != null && session.isVerified()) {
restoreSessionEvent.setCancelled(true);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSessionRestore(RestoreSessionEvent restoreSessionEvent) {
Player player = restoreSessionEvent.getPlayer();
BukkitLoginSession session = plugin.getSession(player.getAddress());
if (session != null && session.isVerified()) {
restoreSessionEvent.setCancelled(true);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void run() {
try {
BukkitLoginSession session = plugin.getLoginSessions().get(player.getAddress().toString());
if (session == null) {
disconnect("invalid-request", true
, "GameProfile {0} tried to send encryption response at invalid state", player.getAddress());
} else {
verifyResponse(session);
}
} finally {
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void run() {
try {
BukkitLoginSession session = plugin.getSession(player.getAddress());
if (session == null) {
disconnect("invalid-request", true
, "GameProfile {0} tried to send encryption response at invalid state", player.getAddress());
} else {
verifyResponse(session);
}
} finally {
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void readMessage(Player player, LoginActionMessage message) {
String playerName = message.getPlayerName();
Type type = message.getType();
InetSocketAddress address = player.getAddress();
String id = '/' + address.getAddress().getHostAddress() + ':' + address.getPort();
if (type == Type.LOGIN) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
playerSession.setVerified(true);
plugin.getLoginSessions().put(id, playerSession);
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, new ForceLoginTask(plugin.getCore(), player), 10L);
} else if (type == Type.REGISTER) {
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> {
AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook();
try {
//we need to check if the player is registered on Bukkit too
if (authPlugin == null || !authPlugin.isRegistered(playerName)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, false);
playerSession.setVerified(true);
plugin.getLoginSessions().put(id, playerSession);
new ForceLoginTask(plugin.getCore(), player).run();
}
} catch (Exception ex) {
plugin.getLog().error("Failed to query isRegistered for player: {}", player, ex);
}
}, 10L);
} else if (type == Type.CRACKED) {
//we don't start a force login task here so update it manually
plugin.getPremiumPlayers().put(player.getUniqueId(), PremiumStatus.CRACKED);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private void readMessage(Player player, LoginActionMessage message) {
String playerName = message.getPlayerName();
Type type = message.getType();
InetSocketAddress address = player.getAddress();
if (type == Type.LOGIN) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
playerSession.setVerified(true);
plugin.putSession(address, playerSession);
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, new ForceLoginTask(plugin.getCore(), player), 10L);
} else if (type == Type.REGISTER) {
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> {
AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook();
try {
//we need to check if the player is registered on Bukkit too
if (authPlugin == null || !authPlugin.isRegistered(playerName)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, false);
playerSession.setVerified(true);
plugin.putSession(address, playerSession);
new ForceLoginTask(plugin.getCore(), player).run();
}
} catch (Exception ex) {
plugin.getLog().error("Failed to query isRegistered for player: {}", player, ex);
}
}, 10L);
} else if (type == Type.CRACKED) {
//we don't start a force login task here so update it manually
plugin.getPremiumPlayers().put(player.getUniqueId(), PremiumStatus.CRACKED);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
protected static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-log4j1";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-log4j1" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logger" + sep;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logger-" + Time.uniqueId() + sep;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul-api";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
static String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul-api" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logback";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logback" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-log4j2";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-log4j2" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-slf4j";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
static String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-slf4j" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jcl";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
static String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jcl-" + Time.uniqueId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath();
if (path.startsWith("/ws/")) {
String sessionKey = getSessionKey(httpRequest);
String sysRole = null;
boolean isAuthByApiKey = false;
if (sessionKey != null) {
User user = userService.getUserBySessionKey(sessionKey);
user.setSessionKey(sessionKey);
if (user != null) {
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
}
} else {
String apiKey = httpRequest.getHeader(Constants.HTTP_HEADER_API_KEY);
if (apiKey != null) {
User user = userService.getUserByApiKey(apiKey);
if (user != null) {
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
isAuthByApiKey = true;
}
}
}
if (sysRole != null) {
boolean isValid = false;
if (isAuthByApiKey) {
// Authorized by using API key
isValid = validateByApiKey(httpRequest.getMethod(), path);
} else {
// Authorized by using cookie.
if (Constants.SYS_ROLE_VIEWER.equals(sysRole)) {
isValid = validateViewer(httpRequest.getMethod(), path);
} else if (Constants.SYS_ROLE_DEVELOPER.equals(sysRole) || Constants.SYS_ROLE_ADMIN.equals(sysRole)) {
isValid = true;
} else {
isValid = false;
}
}
if (isValid) {
chain.doFilter(request, response);
} else {
return401(response);
}
} else {
return401(response);
}
} else {
chain.doFilter(request, response);
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath();
if (path.startsWith("/ws/")) {
String sessionKey = getSessionKey(httpRequest);
String sysRole = null;
boolean isAuthByApiKey = false;
if (sessionKey != null) {
User user = userService.getUserBySessionKey(sessionKey);
if (user != null) {
user.setSessionKey(sessionKey);
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
}
} else {
String apiKey = httpRequest.getHeader(Constants.HTTP_HEADER_API_KEY);
if (apiKey != null) {
User user = userService.getUserByApiKey(apiKey);
if (user != null) {
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
isAuthByApiKey = true;
}
}
}
if (sysRole != null) {
boolean isValid = false;
if (isAuthByApiKey) {
// Authorized by using API key
isValid = validateByApiKey(httpRequest.getMethod(), path);
} else {
// Authorized by using cookie.
if (Constants.SYS_ROLE_VIEWER.equals(sysRole)) {
isValid = validateViewer(httpRequest.getMethod(), path);
} else if (Constants.SYS_ROLE_DEVELOPER.equals(sysRole) || Constants.SYS_ROLE_ADMIN.equals(sysRole)) {
isValid = true;
} else {
isValid = false;
}
}
if (isValid) {
chain.doFilter(request, response);
} else {
return401(response);
}
} else {
return401(response);
}
} else {
chain.doFilter(request, response);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args){
FullAPI test = null;
ProblemSet ps = new ProblemSet();
File parent = new File("/Users/tdutko200/git/jstylo/jsan_resources/corpora/drexel_1");
try {
for (File author : parent.listFiles()) {
if (!author.getName().equalsIgnoreCase(".DS_Store")) {
for (File document : author.listFiles()) {
if (!document.getName().equalsIgnoreCase(".DS_Store")) {
Document doc = new StringDocument(toDeleteGetStringFromFile(document), author.getName(),document.getName());
doc.load();
ps.addTrainDoc(author.getName(), doc);
}
}
}
}
} catch (Exception e) {
LOG.error("Womp womp.",e);
System.exit(1);
}
try {
test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
.ps(ps)
.setAnalyzer(new WekaAnalyzer())
.numThreads(1).analysisType(analysisType.CROSS_VALIDATION).useCache(false).chunkDocs(false)
.loadDocContents(true)
.build();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to intialize API, exiting...");
System.exit(1);
}
test.prepareInstances();
test.calcInfoGain();
//test.applyInfoGain(5);
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
System.out.println(test.getResults().toJson().toString());
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args){
FullAPI test = null;
try {
test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
.psPath("jsan_resources/problem_sets/drexel_1_train_test.xml")
.setAnalyzer(new SparkAnalyzer())
.numThreads(1).analysisType(analysisType.TRAIN_TEST_KNOWN).useCache(false).chunkDocs(false)
.loadDocContents(true)
.build();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to intialize API, exiting...");
System.exit(1);
}
test.prepareInstances();
test.calcInfoGain();
//test.applyInfoGain(5);
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
System.out.println(test.getResults().toJson().toString());
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args){
ProblemSet ps = new ProblemSet();
File sourceDir = new File("jsan_resources/corpora/drexel_1");
System.out.println(sourceDir.getAbsolutePath());
for (File author : sourceDir.listFiles()){
for (File doc : author.listFiles()){
ps.addTrainDoc(author.getName(), new Document(doc.getAbsolutePath(),author.getName(),doc.getName()));
}
}
FullAPI test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
//.psPath("./jsan_resources/problem_sets/enron_demo.xml")
.ps(ps)
.classifierPath("weka.classifiers.functions.SMO")
.numThreads(1)
.analysisType(analysisType.CROSS_VALIDATION)
.useCache(false)
.chunkDocs(false)
.build();
test.prepareInstances();
test.calcInfoGain();
//test.applyInfoGain(1500);
test.prepareAnalyzer();
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args){
FullAPI test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
.psPath("./jsan_resources/problem_sets/drexel_1_small.xml")
.classifierPath("weka.classifiers.functions.SMO")
.numThreads(1)
.analysisType(analysisType.CROSS_VALIDATION)
.useCache(false)
.chunkDocs(false)
.useDocTitles(true)
.build();
test.prepareInstances();
//test.calcInfoGain();
//test.applyInfoGain(1500);
test.prepareAnalyzer();
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void saveMeBackup(File f, String toWrite) throws IOException
{
String backup = "/Users/bekahoverdorf/btbackup/timestamp" + BekahUtil.getNow();
String path = f.getAbsolutePath();
Scanner pathScanner = new Scanner(path).useDelimiter("/");
boolean record = false;
while (pathScanner.hasNext())
{
String temp = pathScanner.next();
if (record)
{
backup += "/" + temp;
}
if (temp.equals("Documents") || temp.equals("NetBeansProjects"))
{
record = true;
}
}
// make the backup
File backupFile = new File(backup);
File backupDir = new File(backupFile.getParent());
backupDir.mkdirs();
backupFile.createNewFile();
FileWriter backupfstream = new FileWriter(backupFile);
BufferedWriter backupout = new BufferedWriter(backupfstream);
backupout.write(toWrite);
backupout.close();
// make the file
File dir = new File(f.getParent());
dir.mkdirs();
f.createNewFile();
FileWriter fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toWrite);
out.close();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static void saveMeBackup(File f, String toWrite) throws IOException
{
String backup = "/Users/bekahoverdorf/btbackup/timestamp" + BekahUtil.getNow();
String path = f.getAbsolutePath();
Scanner baseScanner = new Scanner(path);
Scanner pathScanner = baseScanner.useDelimiter("/");
boolean record = false;
while (pathScanner.hasNext())
{
String temp = pathScanner.next();
if (record)
{
backup += "/" + temp;
}
if (temp.equals("Documents") || temp.equals("NetBeansProjects"))
{
record = true;
}
}
// make the backup
File backupFile = new File(backup);
File backupDir = new File(backupFile.getParent());
backupDir.mkdirs();
backupFile.createNewFile();
FileWriter backupfstream = new FileWriter(backupFile);
BufferedWriter backupout = new BufferedWriter(backupfstream);
backupout.write(toWrite);
backupout.close();
// make the file
File dir = new File(f.getParent());
dir.mkdirs();
f.createNewFile();
FileWriter fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toWrite);
out.close();
pathScanner.close();
baseScanner.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void checkProviderInfo(ProviderGroup providerGroup) {
List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
if (CommonUtils.isEmpty(providerInfos)) {
return;
}
Iterator<ProviderInfo> iterator = providerInfos.iterator();
while (iterator.hasNext()) {
ProviderInfo providerInfo = iterator.next();
if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(),
"Unmatched protocol between consumer [{}] and provider [{}].",
consumerConfig.getProtocol(), providerInfo.getProtocolType());
}
}
if (StringUtils.isEmpty(providerInfo.getSerializationType())) {
providerInfo.setSerializationType(consumerConfig.getSerialization());
}
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void checkProviderInfo(ProviderGroup providerGroup) {
List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
if (CommonUtils.isEmpty(providerInfos)) {
return;
}
Iterator<ProviderInfo> iterator = providerInfos.iterator();
while (iterator.hasNext()) {
ProviderInfo providerInfo = iterator.next();
if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(),
"Unmatched protocol between consumer [{}] and provider [{}].",
consumerConfig.getProtocol(), providerInfo.getProtocolType());
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void stop() {
if (!started) {
return;
}
try {
// 关闭端口,不关闭线程池
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort());
}
httpServer.stop();
httpServer = null;
} catch (Exception e) {
LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e);
}
started = false;
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void stop() {
if (!started) {
return;
}
try {
// 关闭端口,不关闭线程池
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort());
}
httpServer.stop();
} catch (Exception e) {
LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e);
}
started = false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void decorateRequest(SofaRequest request) {
// 公共的设置
super.decorateRequest(request);
// 缓存是为了加快速度
request.setTargetServiceUniqueName(serviceName);
request.setSerializeType(serializeType);
if (!consumerConfig.isGeneric()) {
// 找到调用类型, generic的时候类型在filter里进行判断
request.setInvokeType(consumerConfig.getMethodInvokeType(request.getMethodName()));
}
RpcInvokeContext invokeCtx = RpcInvokeContext.peekContext();
RpcInternalContext internalContext = RpcInternalContext.getContext();
if (invokeCtx != null) {
// 如果用户设置了调用级别回调函数
SofaResponseCallback responseCallback = invokeCtx.getResponseCallback();
if (responseCallback != null) {
request.setSofaResponseCallback(responseCallback);
invokeCtx.setResponseCallback(null); // 一次性用完
invokeCtx.put(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN,
isSendableResponseCallback(responseCallback));
}
// 如果用户设置了调用级别超时时间
Integer timeout = invokeCtx.getTimeout();
if (timeout != null) {
request.setTimeout(timeout);
invokeCtx.setTimeout(null);// 一次性用完
}
// 如果用户指定了调用的URL
String targetURL = invokeCtx.getTargetURL();
if (targetURL != null) {
internalContext.setAttachment(HIDDEN_KEY_PINPOINT, targetURL);
invokeCtx.setTargetURL(null);// 一次性用完
}
// 如果用户指定了透传数据
if (RpcInvokeContext.isBaggageEnable()) {
// 需要透传
BaggageResolver.carryWithRequest(invokeCtx, request);
internalContext.setAttachment(HIDDEN_KEY_INVOKE_CONTEXT, invokeCtx);
}
}
if (RpcInternalContext.isAttachmentEnable()) {
internalContext.setAttachment(INTERNAL_KEY_APP_NAME, consumerConfig.getAppName());
internalContext.setAttachment(INTERNAL_KEY_PROTOCOL_NAME, consumerConfig.getProtocol());
}
// 额外属性通过HEAD传递给服务端
request.addRequestProp(RemotingConstants.HEAD_APP_NAME, consumerConfig.getAppName());
request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, consumerConfig.getProtocol());
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
protected void decorateRequest(SofaRequest request) {
// 公共的设置
super.decorateRequest(request);
// 缓存是为了加快速度
request.setTargetServiceUniqueName(serviceName);
request.setSerializeType(serializeType == null ? 0 : serializeType);
if (!consumerConfig.isGeneric()) {
// 找到调用类型, generic的时候类型在filter里进行判断
request.setInvokeType(consumerConfig.getMethodInvokeType(request.getMethodName()));
}
RpcInvokeContext invokeCtx = RpcInvokeContext.peekContext();
RpcInternalContext internalContext = RpcInternalContext.getContext();
if (invokeCtx != null) {
// 如果用户设置了调用级别回调函数
SofaResponseCallback responseCallback = invokeCtx.getResponseCallback();
if (responseCallback != null) {
request.setSofaResponseCallback(responseCallback);
invokeCtx.setResponseCallback(null); // 一次性用完
invokeCtx.put(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN,
isSendableResponseCallback(responseCallback));
}
// 如果用户设置了调用级别超时时间
Integer timeout = invokeCtx.getTimeout();
if (timeout != null) {
request.setTimeout(timeout);
invokeCtx.setTimeout(null);// 一次性用完
}
// 如果用户指定了调用的URL
String targetURL = invokeCtx.getTargetURL();
if (targetURL != null) {
internalContext.setAttachment(HIDDEN_KEY_PINPOINT, targetURL);
invokeCtx.setTargetURL(null);// 一次性用完
}
// 如果用户指定了透传数据
if (RpcInvokeContext.isBaggageEnable()) {
// 需要透传
BaggageResolver.carryWithRequest(invokeCtx, request);
internalContext.setAttachment(HIDDEN_KEY_INVOKE_CONTEXT, invokeCtx);
}
}
if (RpcInternalContext.isAttachmentEnable()) {
internalContext.setAttachment(INTERNAL_KEY_APP_NAME, consumerConfig.getAppName());
internalContext.setAttachment(INTERNAL_KEY_PROTOCOL_NAME, consumerConfig.getProtocol());
}
// 额外属性通过HEAD传递给服务端
request.addRequestProp(RemotingConstants.HEAD_APP_NAME, consumerConfig.getAppName());
request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, consumerConfig.getProtocol());
} | 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.