output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public static String getPfadVlc() {
if (Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) {
new DialogOk(null, true, new PanelProgrammPfade(), "Pfade Standardprogramme").setVisible(true);
}
return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR];
}
|
#vulnerable code
public static String getPfadVlc() {
///////////////////////
if (!Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) {
return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR];
}
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsVlcPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_VLC;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC_VLC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static ListePset getStandardprogramme(DDaten ddaten) {
ListePset pSet;
InputStream datei;
switch (getOs()) {
case OS_LINUX:
datei = new GetFile().getPsetVorlageLinux();
break;
case OS_MAC:
datei = new GetFile().getPsetVorlageMac();
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
datei = new GetFile().getPsetVorlageWindows();
}
// Standardgruppen laden
pSet = IoXmlLesen.importPset(datei, true);
return pSet;
}
|
#vulnerable code
public static ListePset getStandardprogramme(DDaten ddaten) {
ListePset pSet;
InputStream datei;
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
datei = new GetFile().getPsetVorlageLinux();
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
datei = new GetFile().getPsetVorlageMac();
} else {
datei = new GetFile().getPsetVorlageWindows();
}
// Standardgruppen laden
pSet = IoXmlLesen.importPset(datei, true);
return pSet;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe";
final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_VLC;
break;
case OS_MAC:
pfad = PFAD_MAC_VLC;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
if (System.getenv("ProgramFiles") != null) {
pfad = System.getenv("ProgramFiles") + PFAD_WIN;
} else if (System.getenv("ProgramFiles(x86)") != null) {
pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN;
} else {
pfad = PFAD_WIN_DEFAULT;
}
}
if (!new File(pfad).exists()) {
pfad = "";
}
return pfad;
}
|
#vulnerable code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsVlcPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_VLC;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC_VLC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stopContainer(String containerId) {
try {
SwarmUtilities.stopServiceByContainerId(containerId);
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
}
|
#vulnerable code
public void stopContainer(String containerId) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String serviceId = task.serviceId();
Service.Criteria criteria = Service.Criteria.builder()
.serviceId(serviceId)
.build();
List<Service> services = dockerClient.listServices(criteria);
if (!CollectionUtils.isEmpty(services)) {
dockerClient.removeService(serviceId);
}
}
}
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private String getContainerId(String containerName) {
final String containerNameSearch = containerName.contains("/") ?
containerName : String.format("/%s", containerName);
List<Container> containerList = null;
try {
containerList = dockerClient.listContainers(DockerClient.ListContainersParam.allContainers());
} catch (DockerException | InterruptedException e) {
logger.log(Level.FINE, nodeId + " Error while getting containerId", e);
ga.trackException(e);
}
return containerList.stream()
.filter(container -> containerNameSearch.equalsIgnoreCase(container.names().get(0)))
.findFirst().get().id();
}
|
#vulnerable code
private String getContainerId(String containerName) {
List<Container> containerList = null;
try {
containerList = dockerClient.listContainers(DockerClient.ListContainersParam.allContainers());
} catch (DockerException | InterruptedException e) {
logger.log(Level.FINE, nodeId + " Error while getting containerId", e);
ga.trackException(e);
}
for (Container container : containerList) {
if (containerName.equalsIgnoreCase(container.names().get(0))) {
return container.id();
}
}
return null;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
String swarmNodeIp = null;
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
List<Node> nodes = dockerClient.listNodes();
for (Node node :nodes) {
if (node.id().equals(task.nodeId())) {
swarmNodeIp = node.status().addr();
execCommandOnRemote(swarmNodeIp, containerId, command);
}
}
}
}
} catch (DockerException | InterruptedException | NullPointerException e) {
logger.debug(nodeId + " Error while executing the command", e);
ga.trackException(e);
}
}
|
#vulnerable code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
String swarmNodeIp = null;
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.status().containerStatus().containerId().equals(containerId)) {
List<Node> nodes = dockerClient.listNodes();
for (Node node :nodes) {
if (node.id().equals(task.nodeId())) {
swarmNodeIp = node.status().addr();
}
}
}
}
} catch (DockerException | InterruptedException | NullPointerException e) {
logger.debug(nodeId + " Error while executing the command", e);
ga.trackException(e);
}
if (swarmNodeIp != null) {
execCommandOnRemote(swarmNodeIp, containerId, command);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void pollerThreadTearsDownNodeAfterTestIsCompleted() throws IOException {
// Supported desired capability for the test session
Map<String, Object> requestedCapability = getCapabilitySupportedByDockerSelenium();
// Start poller thread
proxy.startPolling();
// Mock the poller HttpClient to avoid exceptions due to failed connections
proxy.getDockerSeleniumNodePollerThread().setClient(getMockedClient());
// Get a test session
TestSession newSession = proxy.getNewSession(requestedCapability);
Assert.assertNotNull(newSession);
// The node should be busy since there is a session in it
Assert.assertTrue(proxy.isBusy());
// We release the session, the node should be free
WebDriverRequest request = mock(WebDriverRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getMethod()).thenReturn("DELETE");
when(request.getRequestType()).thenReturn(RequestType.STOP_SESSION);
newSession.getSlot().doFinishRelease();
proxy.afterCommand(newSession, request, response);
// After running one test, the node shouldn't be busy and also down
Assert.assertFalse(proxy.isBusy());
long sleepTime = proxy.getDockerSeleniumNodePollerThread().getSleepTimeBetweenChecks();
await().atMost(sleepTime + 2000, MILLISECONDS).untilCall(to(proxy).isDown(), equalTo(true));
}
|
#vulnerable code
@Test
public void pollerThreadTearsDownNodeAfterTestIsCompleted() throws IOException {
// Supported desired capability for the test session
Map<String, Object> requestedCapability = getCapabilitySupportedByDockerSelenium();
// Start poller thread
proxy.startPolling();
// Mock the poller HttpClient to avoid exceptions due to failed connections
proxy.getDockerSeleniumNodePollerThread().setClient(getMockedClient());
// Get a test session
TestSession newSession = proxy.getNewSession(requestedCapability);
Assert.assertNotNull(newSession);
// The node should be busy since there is a session in it
Assert.assertTrue(proxy.isBusy());
// We release the session, the node should be free
newSession.getSlot().doFinishRelease();
// After running one test, the node shouldn't be busy and also down
Assert.assertFalse(proxy.isBusy());
long sleepTime = proxy.getDockerSeleniumNodePollerThread().getSleepTimeBetweenChecks();
await().atMost(sleepTime + 2000, MILLISECONDS).untilCall(to(proxy).isDown(), equalTo(true));
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getLatestDownloadedImage(String imageName) {
// TODO: verify this is handled by docker
return imageName;
}
|
#vulnerable code
public String getLatestDownloadedImage(String imageName) {
List<Image> images;
try {
images = dockerClient.listImages(DockerClient.ListImagesParam.byName(imageName));
if (images.isEmpty()) {
logger.error(nodeId + " A downloaded docker-selenium image was not found!");
return imageName;
}
for (int i = images.size() - 1; i >= 0; i--) {
if (images.get(i).repoTags() == null) {
images.remove(i);
}
}
images.sort((o1, o2) -> o2.created().compareTo(o1.created()));
return images.get(0).repoTags().get(0);
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while executing the command", e);
ga.trackException(e);
}
return imageName;
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stopContainer(String containerId) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String serviceId = task.serviceId();
List<Service> services = dockerClient.listServices();
if (services.stream().anyMatch(service -> service.id().equals(serviceId))) {
dockerClient.removeService(serviceId);
}
}
}
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
}
|
#vulnerable code
public void stopContainer(String containerId) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.status().containerStatus().containerId().equals(containerId)) {
String serviceId = task.serviceId();
dockerClient.removeService(serviceId);
}
}
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private String getContainerId(String zaleniumContainerName, URL remoteUrl) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
List<NetworkAttachment> networkAttachments = task.networkAttachments();
if (networkAttachments != null) {
for (NetworkAttachment networkAttachment : task.networkAttachments()) {
for (String address : networkAttachment.addresses()) {
if (address.startsWith(remoteUrl.getHost())) {
return task.status().containerStatus().containerId();
}
}
}
}
}
} catch (DockerException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
|
#vulnerable code
private String getContainerId(String zaleniumContainerName, URL remoteUrl) {
try {
List<Task> tasks = dockerClient.listTasks();
logger.debug("---------------Size of tasks list : {} ---------------", tasks.size());
for (Task task : tasks) {
logger.debug("--------------- Task : {} ---------------", task);
for (NetworkAttachment networkAttachment : task.networkAttachments()) {
for (String address : networkAttachment.addresses()) {
if (address.startsWith(remoteUrl.getHost())) {
return task.status().containerStatus().containerId();
}
}
}
}
} catch (DockerException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
try {
Task task = SwarmUtilities.getTaskByContainerId(containerId);
if (task != null) {
pullSwarmExecImage();
startSwarmExecContainer(task, command, containerId);
} else {
logger.warn("Couldn't execute command on container {}", containerId);
}
} catch (DockerException | InterruptedException e) {
logger.warn("Error while executing comman on container {}", containerId);
ga.trackException(e);
}
}
|
#vulnerable code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
try {
List<Task> tasks = dockerClient.listTasks();
pullSwarmExecImage();
for (Task task : CollectionUtils.emptyIfNull(tasks)) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
startSwarmExecContainer(task, command, containerId);
return;
}
}
} catch (DockerException | InterruptedException e) {
logger.warn("Error while executing comman on container {}", containerId);
ga.trackException(e);
}
logger.warn("Couldn't execute command on container {}", containerId);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
InputStreamGroupIterator tarStream = containerClient.copyFiles(containerId, "/videos/");
try {
InputStreamDescriptor entry;
while ((entry = tarStream.next()) != null) {
String fileExtension = entry.name().substring(entry.name().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(entry.get(), videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
}
|
#vulnerable code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
try {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(tarStream, videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
}
#location 39
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
TaskStatus taskStatus = task.status();
ContainerStatus containerStatus = taskStatus.containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String state = taskStatus.state();
return termStates.contains(state);
}
}
return false;
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
}
|
#vulnerable code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
TaskStatus taskStatus = task.status();
String state = taskStatus.state();
if (termStates.contains(state)) {
return taskStatus.containerStatus().containerId().equals(containerId);
}
}
return false;
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
try {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
List<Task> tasks = dockerClient.listTasks();
boolean containerExists = tasks.stream().anyMatch(task -> {
ContainerStatus containerStatus = task.status().containerStatus();
return containerStatus != null && containerStatus.containerId().equals(containerId);
});
if (!containerExists) {
logger.info("Container {} has no task - terminal.", container);
return true;
} else {
return tasks.stream().anyMatch(task -> {
ContainerStatus containerStatus = task.status().containerStatus();
boolean hasTerminalState = termStates.contains(task.status().state());
boolean isContainer = containerStatus != null && containerStatus.containerId().equals(containerId);
boolean isTerminated = isContainer && hasTerminalState;
if (isTerminated) {
logger.info("Container {} is {} - terminal.", container, task.status().state());
}
return isTerminated;
});
}
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
}
|
#vulnerable code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
TaskStatus taskStatus = task.status();
ContainerStatus containerStatus = taskStatus.containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String state = taskStatus.state();
return termStates.contains(state);
}
}
return false;
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private ContainerCreationStatus getContainerCreationStatus (String serviceId, String nodePort) throws DockerException, InterruptedException {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.serviceId().equals(serviceId)) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null) {
String containerId = containerStatus.containerId();
String containerName = containerStatus.containerId();
return new ContainerCreationStatus(true, containerName, containerId, nodePort);
}
}
}
return null;
}
|
#vulnerable code
private ContainerCreationStatus getContainerCreationStatus (String serviceId, String nodePort) throws DockerException, InterruptedException {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.serviceId().equals(serviceId)) {
ContainerStatus containerStatus = task.status().containerStatus();
String containerId = containerStatus.containerId();
String containerName = containerStatus.containerId();
return new ContainerCreationStatus(true, containerName, containerId, nodePort);
}
}
return null;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
InputStreamGroupIterator tarStream = containerClient.copyFiles(containerId, "/videos/");
try {
InputStreamDescriptor entry;
while ((entry = tarStream.next()) != null) {
String fileExtension = entry.name().substring(entry.name().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(entry.get(), videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
}
|
#vulnerable code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
try {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(tarStream, videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
}
#location 38
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String getContainerIp(String containerName) {
String containerId = this.getContainerId(containerName);
if (containerId == null) {
return null;
}
try {
List<Task> tasks = dockerClient.listTasks();
String swarmOverlayNetwork = ZaleniumConfiguration.getSwarmOverlayNetwork();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null) {
if (containerStatus.containerId().equals(containerId)) {
for (NetworkAttachment networkAttachment : task.networkAttachments()) {
if (networkAttachment.network().spec().name().equals(swarmOverlayNetwork)) {
String cidrSuffix = "/\\d+$";
return networkAttachment.addresses().get(0).replaceAll(cidrSuffix, "");
}
}
}
}
}
} catch (DockerException | InterruptedException e) {
logger.debug(nodeId + " Error while getting the container IP.", e);
ga.trackException(e);
}
return null;
}
|
#vulnerable code
@Override
public String getContainerIp(String containerName) {
String containerId = this.getContainerId(containerName);
if (containerId == null) {
return null;
}
try {
ContainerInfo containerInfo = dockerClient.inspectContainer(containerId);
if (containerInfo.networkSettings().ipAddress().trim().isEmpty()) {
ImmutableMap<String, AttachedNetwork> networks = containerInfo.networkSettings().networks();
return networks.entrySet().stream().findFirst().get().getValue().ipAddress();
}
return containerInfo.networkSettings().ipAddress();
} catch (DockerException | InterruptedException e) {
logger.debug(nodeId + " Error while getting the container IP.", e);
ga.trackException(e);
}
return null;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void loadMountedFolder(String zaleniumContainerName) {
if (this.mountedFolder == null) {
String containerId = getContainerId(String.format("/%s", zaleniumContainerName));
if (containerId == null) {
return;
}
ContainerInfo containerInfo = null;
try {
containerInfo = dockerClient.inspectContainer(containerId);
} catch (DockerException | InterruptedException e) {
logger.log(Level.WARNING, nodeId + " Error while getting mounted folders.", e);
ga.trackException(e);
}
for (ContainerMount containerMount : containerInfo.mounts()) {
if ("/tmp/mounted".equalsIgnoreCase(containerMount.destination())) {
this.mountedFolder = containerMount;
}
}
}
}
|
#vulnerable code
private void loadMountedFolder(String zaleniumContainerName) {
if (this.mountedFolder == null) {
String containerId = getContainerId(String.format("/%s", zaleniumContainerName));
ContainerInfo containerInfo = null;
try {
containerInfo = dockerClient.inspectContainer(containerId);
} catch (DockerException | InterruptedException e) {
logger.log(Level.WARNING, nodeId + " Error while getting mounted folders.", e);
ga.trackException(e);
}
for (ContainerMount containerMount : containerInfo.mounts()) {
if ("/tmp/mounted".equalsIgnoreCase(containerMount.destination())) {
this.mountedFolder = containerMount;
}
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static Future<TermStatus> runAsync(final CommandLine parsed, final List<CommandAtom> commands,
final Function<Commander, Commander> binder) {
/*
* Found command inner run method, double check for CommandAtom
*/
final List<String> args = parsed.getArgList();
return findAsync(args.get(Values.IDX), commands).compose(command -> {
/*
* Create CommandArgs
*/
final CommandInput input = getInput(parsed).bind(command);
/*
* Commander
*/
final Commander commander;
if (CommandType.SYSTEM == command.getType()) {
/*
* Sub-System call
*/
commander = Ut.instance(ConsoleCommander.class);
} else {
/*
* Plugin processing
* instance instead of single for shared usage
*/
commander = Ut.instance(command.getPlugin());
}
/*
* binder processing
*/
Sl.welcomeCommand(command);
return binder.apply(commander.bind(command)).executeAsync(input);
});
}
|
#vulnerable code
static Future<TermStatus> runAsync(final CommandLine parsed, final List<CommandAtom> commands,
final Function<Commander, Commander> binder) {
/*
* Found command inner run method
*/
final CommandAtom command = commands.stream()
.filter(each -> parsed.hasOption(each.getName()) || parsed.hasOption(each.getSimple()))
.findAny().orElse(null);
if (Objects.isNull(command) || !command.valid()) {
/*
* Internal error
*/
if (Objects.nonNull(command)) {
Sl.failWarn(" Plugin null -> name = {0},{1}, type = {2}",
command.getSimple(), command.getName(), command.getType());
}
throw new CommandMissingException(ConsoleInteract.class, Ut.fromJoin(parsed.getArgs()));
} else {
final Options options = new Options();
commands.stream().map(CommandAtom::option).forEach(options::addOption);
/*
* Create CommandArgs
*/
final List<String> inputArgs = parsed.getArgList();
final List<String> inputNames = command.getOptionNames();
final CommandInput commandInput = CommandInput.create(inputNames, inputArgs);
commandInput.bind(options);
/*
* Commander
*/
final Commander commander;
if (CommandType.SYSTEM == command.getType()) {
/*
* Sub-System call
*/
commander = Ut.instance(ConsoleCommander.class);
} else {
/*
* Plugin processing
* instance instead of single for shared usage
*/
commander = Ut.instance(command.getPlugin());
}
/*
* binder processing
*/
Sl.welcomeCommand(command);
return binder.apply(commander.bind(command)).executeAsync(commandInput);
}
}
#location 48
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
<T> Future<T> fetchOneAsync(final String field, final Object value) {
return JqTool.future(this.vertxDAO.fetchOneAsync(this.analyzer.column(field), value));
}
|
#vulnerable code
<T> Integer count(final JsonObject filters) {
final DSLContext context = JooqInfix.getDSL();
return null == filters ? context.fetchCount(this.vertxDAO.getTable()) :
context.fetchCount(this.vertxDAO.getTable(), JooqCond.transform(filters, this.analyzer::column));
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Resolver<T> getResolver(final RoutingContext context,
final Epsilon<T> income) {
/* 1.Read the resolver first **/
final Annotation annotation = income.getAnnotation();
final Class<?> resolverCls = Ut.invoke(annotation, "resolver");
final String header = context.request().getHeader(HttpHeaders.CONTENT_TYPE);
/* 2.Check configured in default **/
if (UnsetResolver.class == resolverCls) {
/* 3. Old path **/
final JsonObject content = NODE.read();
// LOGGER.info("[ RESOLVER ] Resolvers = {0}", content.encodePrettily());
final String resolver;
if (null == header) {
resolver = content.getString("default");
} else {
final MediaType type = MediaType.valueOf(header);
final JsonObject resolverMap = content.getJsonObject(type.getType());
resolver = resolverMap.getString(type.getSubtype());
}
LOGGER.info(Info.RESOLVER, resolver, header, context.request().absoluteURI());
return Ut.singleton(resolver);
} else {
LOGGER.info(Info.RESOLVER_CONFIG, resolverCls, header);
/*
* Split workflow
* Resolver or Solve
*/
if (Ut.isImplement(resolverCls, Resolver.class)) {
/*
* Resolver Directly
*/
return Ut.singleton(resolverCls);
} else {
/*
* Solve component, contract to set Solve<T> here.
*/
final Resolver<T> resolver = Ut.singleton(SolveResolver.class);
Ut.contract(resolver, Solve.class, Ut.singleton(resolverCls));
return resolver;
}
}
}
|
#vulnerable code
private Resolver<T> getResolver(final RoutingContext context,
final Epsilon<T> income) {
/* 1.Read the resolver first **/
final Annotation annotation = income.getAnnotation();
final Class<?> resolverCls = Ut.invoke(annotation, "resolver");
final String header = context.request().getHeader(HttpHeaders.CONTENT_TYPE);
/* 2.Check configured in default **/
if (UnsetResolver.class == resolverCls) {
/* 3. Old path **/
final JsonObject content = NODE.read();
// LOGGER.info("[ RESOLVER ] Resolvers = {0}", content.encodePrettily());
final String resolver;
if (null == header) {
resolver = content.getString("default");
} else {
final MediaType type = MediaType.valueOf(header);
final JsonObject resolverMap = content.getJsonObject(type.getType());
resolver = resolverMap.getString(type.getSubtype());
}
LOGGER.info(Info.RESOLVER, resolver, header, context.request().absoluteURI());
return Ut.singleton(resolver);
} else {
LOGGER.info(Info.RESOLVER_CONFIG, resolverCls, header);
return Ut.singleton(resolverCls);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
<T> Future<T> fetchOneAsync(final String field, final Object value) {
return JqTool.future(this.vertxDAO.fetchOneAsync(this.analyzer.column(field), value));
}
|
#vulnerable code
<T> Integer count(final JsonObject filters) {
final DSLContext context = JooqInfix.getDSL();
return null == filters ? context.fetchCount(this.vertxDAO.getTable()) :
context.fetchCount(this.vertxDAO.getTable(), JooqCond.transform(filters, this.analyzer::column));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String unique(final CacheMeta meta) {
final TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put(meta.primaryString(), this.id);
return CacheTool.keyId(meta.typeName(), treeMap);
}
|
#vulnerable code
@Override
public String unique(final CacheMeta meta) {
final Class<?> entityCls = meta.type();
final TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put(meta.primaryString(), this.id);
return CacheTool.keyId(entityCls.getName(), treeMap);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void onTable(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE",
() -> DyeCell.create(this.workbook)
.color("FFFFFF", "3EB7FF")
.align(HorizontalAlignment.CENTER)
.border(BorderStyle.THIN)
.font(13, false));
cell.setCellStyle(dyeCell.build());
}
|
#vulnerable code
void onData(final Cell cell) {
final DyeCell dye;
if (CellType.NUMERIC == cell.getCellType()) {
/*
* Buf for date exporting here
*/
final double cellValue = cell.getNumericCellValue();
if (DateUtil.isValidExcelDate(cellValue)) {
final Date value = DateUtil.getJavaDate(cellValue, TimeZone.getDefault());
final LocalDateTime datetime = Ut.toDateTime(value);
final LocalTime time = datetime.toLocalTime();
if (LocalTime.MIN == time) {
/*
* LocalDate
*/
dye = this.onDataValue("DATA-DATE").dateFormat(false);
} else {
/*
* LocalDateTime
*/
dye = this.onDataValue("DATA-DATETIME").dateFormat(true);
}
} else {
/*
* Number
*/
dye = this.onDataValue("DATA-VALUE");
}
} else {
/*
* Other
*/
dye = this.onDataValue("DATA-VALUE");
}
cell.setCellStyle(dye.build());
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
<T> Future<JsonObject> searchAsync(final JsonObject params, final JqFlow workflow) {
return this.search.searchAsync(params, workflow);
}
|
#vulnerable code
<T> T fetchOne(final JsonObject filters) {
final Condition condition = JooqCond.transform(filters, Operator.AND, this.analyzer::column);
final DSLContext context = JooqInfix.getDSL();
return this.toResult(context.selectFrom(this.vertxDAO.getTable()).where(condition).fetchOne(this.vertxDAO.mapper()));
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Future<JsonArray> groupAsync(final String sigma) {
/*
* Build condition of `sigma`
*/
final JsonObject condition = new JsonObject();
condition.put(KeField.SIGMA, sigma);
/*
* Permission Groups processing
*「Upgrade」
* Old method because `GROUP` is in S_PERMISSION
* return Ux.Jooq.on(SPermissionDao.class).countByAsync(condition, "group", "identifier");
* New version: S_PERM_SET processing
*/
return Ux.Jooq.on(SPermSetDao.class).fetchJAsync(condition);
}
|
#vulnerable code
@Override
public Future<JsonArray> groupAsync(final String sigma) {
/*
* Build condition of `sigma`
*/
final JsonObject condition = new JsonObject();
condition.put(KeField.SIGMA, sigma);
/*
* Permission Groups processing
*/
return Ux.Jooq.on(SPermissionDao.class)
.countByAsync(condition, "group", "identifier");
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Address(Addr.Authority.PERMISSION_BY_ROLE)
public Future<JsonArray> fetchAsync(final String roleId) {
return Fn.getEmpty(Ux.futureJArray(), () -> Ux.Jooq.on(RRolePermDao.class)
.fetchAsync(KeField.ROLE_ID, roleId)
.compose(Ux::fnJArray), roleId);
}
|
#vulnerable code
@Address(Addr.Authority.PERMISSION_BY_ROLE)
public Future<JsonArray> fetchAsync(final String roleId) {
if (Ut.notNil(roleId)) {
return Ux.Jooq.on(RRolePermDao.class)
.fetchAsync(KeField.ROLE_ID, roleId)
.compose(Ux::fnJArray);
} else return Ux.futureJArray();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
L1Cache cacheL1() {
L1Cache cache = null;
final Class<?> componentCls = this.l1Config.getComponent();
if (Objects.nonNull(componentCls) && Ut.isImplement(componentCls, L1Cache.class)) {
/*
* L1 cache here
*/
final Class<?> cacheClass = this.l1Config.getComponent();
cache = Fn.poolThread(POOL_L1, () -> {
final L1Cache created = Ut.instance(cacheClass);
return created.bind(this.vertx).bind(this.l1Config.copy());
});
}
return cache;
}
|
#vulnerable code
L1Cache cacheL1() {
L1Cache cache = null;
final Class<?> componentCls = this.l1Config.getComponent();
if (Objects.nonNull(componentCls) && Ut.isImplement(componentCls, L1Cache.class)) {
/*
* L1 cache here
*/
final Class<?> cacheClass = this.l1Config.getComponent();
cache = Fn.poolThread(POOL_L1, () -> Ut.instance(cacheClass));
cache.bind(this.vertx).bind(this.l1Config.copy());
}
return cache;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Future<JsonArray> syncPerm(final JsonArray permissions, final String group, final String sigma) {
/*
* 1. permissions ->
* -- ADD = List
* -- UPDATE = List
* -- DELETE = List
*/
final Set<String> permCodes = Ut.mapString(permissions, KeField.CODE);
final JsonObject condition = new JsonObject();
condition.put(KeField.SIGMA, sigma);
return null;
}
|
#vulnerable code
@Override
public Future<JsonArray> syncPerm(final JsonArray permissions, final String group, final String sigma) {
/*
* Fetch all permissions from database and calculated removed list
*/
final JsonObject condition = new JsonObject();
condition.put(KeField.GROUP, group);
condition.put(KeField.SIGMA, sigma);
final UxJooq permDao = Ux.Jooq.on(SPermissionDao.class);
return permDao.<SPermission>fetchAndAsync(condition).compose(existing -> {
/*
* Process filter to get removed
*/
final List<SPermission> saved = Ux.fromJson(permissions, SPermission.class);
final Set<String> keeped = saved.stream().map(SPermission::getKey).collect(Collectors.toSet());
final List<String> removedKeys = existing.stream()
.filter(item -> !keeped.contains(item.getKey()))
.map(SPermission::getKey).collect(Collectors.toList());
return this.removeAsync(removedKeys, sigma).compose(nil -> {
/*
* Save Action for SPermission by `key` only
*/
final List<Future<SPermission>> futures = new ArrayList<>();
Ut.itList(saved).map(permission -> permDao.<SPermission>fetchByIdAsync(permission.getKey())
.compose(queired -> {
if (Objects.isNull(queired)) {
/*
* Insert entity object into database
*/
return permDao.insertAsync(permission);
} else {
/*
* Update the `key` hitted object into database
*/
return permDao.updateAsync(permission.getKey(), permission);
}
})).forEach(futures::add);
return Ux.thenCombineT(futures).compose(Ux::futureA);
});
});
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Future<JsonObject> fetchModule(final String appId, final String entry) {
final JsonObject filters = new JsonObject()
.put("", Boolean.TRUE)
.put("entry", entry)
.put("appId", appId);
/*
* Cache Module for future usage
*/
return AcCache.getModule(filters, () -> Ux.Jooq.on(XModuleDao.class)
.fetchOneAsync(filters)
.compose(Ux::fnJObject)
/* Metadata field usage */
.compose(Ke.mount(KeField.METADATA)));
}
|
#vulnerable code
@Override
public Future<JsonObject> fetchModule(final String appId, final String entry) {
final JsonObject filters = new JsonObject()
.put("", Boolean.TRUE)
.put("entry", entry)
.put("appId", appId);
return Ux.Jooq.on(XModuleDao.class)
.fetchOneAsync(filters)
.compose(Ux::fnJObject)
/* Metadata field usage */
.compose(Ke.mount(KeField.METADATA));
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void mount(final Router router) {
final Class<?> clazz = ZeroAmbient.getPlugin(PlugRouter.KEY_ROUTER);
if (Values.ZERO == LOG_FLAG_START.getAndIncrement()) {
LOGGER.info(Info.DY_DETECT, NAME);
}
if (null != clazz && Ut.isImplement(clazz, PlugRouter.class)) {
final JsonObject routerConfig = PlugRouter.config();
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_FOUND, NAME, clazz.getName(), routerConfig.encode());
}
// Mount dynamic router
final PlugRouter plugRouter = Fn.poolThread(Pool.PLUGS,
() -> Ut.instance(clazz));
plugRouter.bind(this.vertxRef);
plugRouter.mount(router, routerConfig);
} else {
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_SKIP, NAME,
Fn.getNull(null, () -> null == clazz ? null : clazz.getName(), clazz));
}
}
}
|
#vulnerable code
@Override
public void mount(final Router router) {
final Class<?> clazz = ZeroAmbient.getPlugin(KEY_ROUTER);
if (Values.ZERO == LOG_FLAG_START.getAndIncrement()) {
LOGGER.info(Info.DY_DETECT, NAME);
}
if (null != clazz && Ut.isImplement(clazz, PlugRouter.class)) {
final JsonObject config = uniform.read();
final JsonObject routerConfig = Fn.getNull(new JsonObject(), () -> config.getJsonObject(KEY_ROUTER), config);
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_FOUND, NAME, clazz.getName(), routerConfig.encode());
}
// Mount dynamic router
final PlugRouter plugRouter = Fn.poolThread(Pool.PLUGS,
() -> Ut.instance(clazz));
plugRouter.bind(vertxRef);
plugRouter.mount(router, routerConfig);
} else {
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_SKIP, NAME,
Fn.getNull(null, () -> null == clazz ? null : clazz.getName(), clazz));
}
}
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void onTable(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE",
() -> DyeCell.create(this.workbook)
.color("FFFFFF", "3EB7FF")
.align(HorizontalAlignment.CENTER)
.border(BorderStyle.THIN)
.font(13, false));
cell.setCellStyle(dyeCell.build());
}
|
#vulnerable code
void onData(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "DATA",
() -> DyeCell.create(this.workbook)
.border(BorderStyle.THIN)
.align(null, VerticalAlignment.TOP)
.font(13, false));
cell.setCellStyle(dyeCell.build());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static Object invokeSingle(final Object proxy,
final Method method,
final Envelop envelop) {
final Class<?> argType = method.getParameterTypes()[Values.IDX];
// Append single argument
final Object analyzed = TypedArgument.analyze(envelop, argType);
if (Objects.isNull(analyzed)) {
// One type dynamic here
final Object reference = Objects.nonNull(envelop) ? envelop.data() : new JsonObject();
// Non Direct
Object parameters = reference;
if (JsonObject.class == reference.getClass()) {
final JsonObject json = (JsonObject) reference;
if (isInterface(json)) {
// Proxy mode
if (Values.ONE == json.fieldNames().size()) {
// New Mode for direct type
parameters = json.getValue("0");
}
}
}
final Object arguments = ZeroSerializer.getValue(argType, Ut.toString(parameters));
return Ut.invoke(proxy, method.getName(), arguments);
} else {
/*
* XHeader
* User
* Session
* These three argument types could be single
*/
return Ut.invoke(proxy, method.getName(), analyzed);
}
}
|
#vulnerable code
static Object invokeSingle(final Object proxy,
final Method method,
final Envelop envelop) {
final Class<?> argType = method.getParameterTypes()[Values.IDX];
// One type dynamic here
final Object reference = Objects.nonNull(envelop) ? envelop.data() : new JsonObject();
// Non Direct
Object parameters = reference;
if (JsonObject.class == reference.getClass()) {
final JsonObject json = (JsonObject) reference;
if (isInterface(json)) {
// Proxy mode
if (Values.ONE == json.fieldNames().size()) {
// New Mode for direct type
parameters = json.getValue("0");
}
}
}
final Object arguments = ZeroSerializer.getValue(argType, Ut.toString(parameters));
return Ut.invoke(proxy, method.getName(), arguments);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
void onTable(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE",
() -> DyeCell.create(this.workbook)
.color("FFFFFF", "3EB7FF")
.align(HorizontalAlignment.CENTER)
.border(BorderStyle.THIN)
.font(13, false));
cell.setCellStyle(dyeCell.build());
}
|
#vulnerable code
void onData(final Cell cell) {
final DyeCell dye;
if (CellType.NUMERIC == cell.getCellType()) {
/*
* Buf for date exporting here
*/
final double cellValue = cell.getNumericCellValue();
if (DateUtil.isValidExcelDate(cellValue)) {
final Date value = DateUtil.getJavaDate(cellValue, TimeZone.getDefault());
final LocalDateTime datetime = Ut.toDateTime(value);
final LocalTime time = datetime.toLocalTime();
if (LocalTime.MIN == time) {
/*
* LocalDate
*/
dye = this.onDataValue("DATA-DATE").dateFormat(false);
} else {
/*
* LocalDateTime
*/
dye = this.onDataValue("DATA-DATETIME").dateFormat(true);
}
} else {
/*
* Number
*/
dye = this.onDataValue("DATA-VALUE");
}
} else {
/*
* Other
*/
dye = this.onDataValue("DATA-VALUE");
}
cell.setCellStyle(dye.build());
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void mountSession(final Router router) {
if (ZeroHeart.isSession()) {
/*
* Session Global for Authorization, replace old mode with
* SessionClient, this client will get SessionStore
* by configuration information instead of create it directly.
*/
final SessionClient client = SessionInfix.getOrCreate(this.vertx);
router.route().order(Orders.SESSION).handler(client.getHandler());
} else {
/*
* Default Session Handler here for public domain
* If enabled session extension, you should provide other session store
*/
final SessionStore store;
if (this.vertx.isClustered()) {
/*
* Cluster environment
*/
store = ClusteredSessionStore.create(this.vertx);
} else {
/*
* Single Node environment
*/
store = LocalSessionStore.create(this.vertx);
}
router.route().order(Orders.SESSION).handler(SessionHandler.create(store));
}
}
|
#vulnerable code
private void mountSession(final Router router) {
if (ZeroHeart.isSession()) {
/*
* Session Global for Authorization, replace old mode with
* SessionClient, this client will get SessionStore
* by configuration information instead of create it directly.
*/
final SessionClient client = SessionInfix.getOrCreate(this.vertx);
router.route().order(Orders.SESSION).handler(client.getHandler());
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void register(JsonProvider jsonProvider) {
this.registeredJsonProvider = Objects.requireNonNull(jsonProvider);
}
|
#vulnerable code
public void register(JsonProvider jsonProvider) {
this.registeredJsonProvider = Objects.requireNonNull(jsonProvider);
logger.debug(() -> "Set json provider to " + jsonProvider.getClass().getName());
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee".getBytes());
assertEquals(BEType.MAP, parser.readType());
byte[][] expected = new byte[][] {"a".getBytes(charset), "b".getBytes(charset)};
Map<String, Object> map = parser.readMap();
Object o = map.get("spam");
assertNotNull(o);
assertTrue(o instanceof List);
List<?> actual = (List<?>) o;
assertArrayEquals(expected, actual.toArray());
}
|
#vulnerable code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee");
assertEquals(BEType.MAP, parser.readType());
Map<String, Object> expected = new HashMap<>();
expected.put("spam", Arrays.asList("a", "b"));
assertEquals(expected, parser.readMap());
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
|
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString(charset));
}
|
#vulnerable code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_");
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString());
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test(expected = Exception.class)
public void testParse_String_Exception_EmptyString() {
new BEParser("".getBytes());
}
|
#vulnerable code
@Test(expected = Exception.class)
public void testParse_String_Exception_EmptyString() {
new BEParser("");
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString(charset));
}
|
#vulnerable code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s");
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString());
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
}
|
#vulnerable code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString(charset));
}
|
#vulnerable code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_");
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
}
|
#vulnerable code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
|
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testDescriptors_WriteMultiFile() {
String torrentName = "xyz-torrent";
File torrentDirectory = new File(rootDirectory, torrentName);
String extension = "-multi.bin";
String fileName1 = 1 + extension,
fileName2 = 2 + extension,
fileName3 = 3 + extension,
fileName4 = 4 + extension,
fileName5 = 5 + extension,
fileName6 = 6 + extension;
IDataDescriptor descriptor = createDataDescriptor_MultiFile(fileName1, fileName2, fileName3, fileName4,
fileName5, fileName6, torrentDirectory);
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());
chunks.get(2).writeBlock(new byte[]{1,2,1,2,3,1,2,3}, 0);
assertTrue(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());
// block size same as chunk size
chunks.get(4).writeBlock(sequence(16), 0);
assertTrue(chunks.get(4).verify());
// 1-byte blocks
chunks.get(5).writeBlock(sequence(1), 0);
chunks.get(5).writeBlock(sequence(1), 15);
chunks.get(5).writeBlock(sequence(14), 1);
assertFalse(chunks.get(5).verify());
chunks.get(5).writeBlock(new byte[]{1,1,2,3,4,5,6,7,8,9,1,2,3,4,5,1}, 0);
assertTrue(chunks.get(5).verify());
assertFileHasContents(new File(torrentDirectory, fileName1), MULTI_FILE_1);
assertFileHasContents(new File(torrentDirectory, fileName2), MULTI_FILE_2);
assertFileHasContents(new File(torrentDirectory, fileName3), MULTI_FILE_3);
assertFileHasContents(new File(torrentDirectory, fileName4), MULTI_FILE_4);
assertFileHasContents(new File(torrentDirectory, fileName5), MULTI_FILE_5);
assertFileHasContents(new File(torrentDirectory, fileName6), MULTI_FILE_6);
}
|
#vulnerable code
@Test
public void testDescriptors_WriteMultiFile() {
String torrentName = "xyz-torrent";
File torrentDirectory = new File(rootDirectory, torrentName);
String extension = "-multi.bin";
String fileName1 = 1 + extension,
fileName2 = 2 + extension,
fileName3 = 3 + extension,
fileName4 = 4 + extension,
fileName5 = 5 + extension,
fileName6 = 6 + extension;
long chunkSize = 16;
long torrentSize = chunkSize * 6;
long fileSize1 = 25,
fileSize2 = 18,
fileSize3 = 5,
fileSize4 = 31,
fileSize5 = 16,
fileSize6 = 1;
// sanity check
assertEquals(torrentSize, fileSize1 + fileSize2 + fileSize3 + fileSize4 + fileSize5 + fileSize6);
byte[] chunk0Hash = CryptoUtil.getSha1Digest(Arrays.copyOfRange(MULTI_FILE_1, 0, 16));
byte[] chunk1 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_1, 16, chunk1, 0, 9);
System.arraycopy(MULTI_FILE_2, 0, chunk1, 9, 7);
byte[] chunk1Hash = CryptoUtil.getSha1Digest(chunk1);
byte[] chunk2 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_2, 7, chunk2, 0, 11);
System.arraycopy(MULTI_FILE_3, 0, chunk2, 11, 5);
byte[] chunk2Hash = CryptoUtil.getSha1Digest(chunk2);
byte[] chunk3 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_4, 0, chunk3, 0, 16);
byte[] chunk3Hash = CryptoUtil.getSha1Digest(chunk3);
byte[] chunk4 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_4, 16, chunk4, 0, 15);
System.arraycopy(MULTI_FILE_5, 0, chunk4, 15, 1);
byte[] chunk4Hash = CryptoUtil.getSha1Digest(chunk4);
byte[] chunk5 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_5, 1, chunk5, 0, 15);
System.arraycopy(MULTI_FILE_6, 0, chunk5, 15, 1);
byte[] chunk5Hash = CryptoUtil.getSha1Digest(chunk5);
Torrent torrent = mockTorrent(torrentName, torrentSize, chunkSize,
new byte[][] {chunk0Hash, chunk1Hash, chunk2Hash, chunk3Hash, chunk4Hash, chunk5Hash},
mockTorrentFile(fileSize1, fileName1), mockTorrentFile(fileSize2, fileName2),
mockTorrentFile(fileSize3, fileName3), mockTorrentFile(fileSize4, fileName4),
mockTorrentFile(fileSize5, fileName5), mockTorrentFile(fileSize6, fileName6));
IDataDescriptor descriptor = new DataDescriptor(dataAccessFactory, configurationService, torrent);
List<IChunkDescriptor> chunks = descriptor.getChunkDescriptors();
assertEquals(6, 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());
chunks.get(2).writeBlock(new byte[]{1,2,1,2,3,1,2,3}, 0);
assertTrue(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());
// block size same as chunk size
chunks.get(4).writeBlock(sequence(16), 0);
assertTrue(chunks.get(4).verify());
// 1-byte blocks
chunks.get(5).writeBlock(sequence(1), 0);
chunks.get(5).writeBlock(sequence(1), 15);
chunks.get(5).writeBlock(sequence(14), 1);
assertFalse(chunks.get(5).verify());
chunks.get(5).writeBlock(new byte[]{1,1,2,3,4,5,6,7,8,9,1,2,3,4,5,1}, 0);
assertTrue(chunks.get(5).verify());
byte[] file1 = readBytesFromFile(new File(torrentDirectory, fileName1), (int) fileSize1);
assertArrayEquals(MULTI_FILE_1, file1);
byte[] file2 = readBytesFromFile(new File(torrentDirectory, fileName2), (int) fileSize2);
assertArrayEquals(MULTI_FILE_2, file2);
byte[] file3 = readBytesFromFile(new File(torrentDirectory, fileName3), (int) fileSize3);
assertArrayEquals(MULTI_FILE_3, file3);
byte[] file4 = readBytesFromFile(new File(torrentDirectory, fileName4), (int) fileSize4);
assertArrayEquals(MULTI_FILE_4, file4);
byte[] file5 = readBytesFromFile(new File(torrentDirectory, fileName5), (int) fileSize5);
assertArrayEquals(MULTI_FILE_5, file5);
byte[] file6 = readBytesFromFile(new File(torrentDirectory, fileName6), (int) fileSize6);
assertArrayEquals(MULTI_FILE_6, file6);
}
#location 62
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee".getBytes());
assertEquals(BEType.MAP, parser.readType());
byte[][] expected = new byte[][] {"a".getBytes(charset), "b".getBytes(charset)};
Map<String, Object> map = parser.readMap();
Object o = map.get("spam");
assertNotNull(o);
assertTrue(o instanceof List);
List<?> actual = (List<?>) o;
assertArrayEquals(expected, actual.toArray());
}
|
#vulnerable code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee");
assertEquals(BEType.MAP, parser.readType());
Map<String, Object> expected = new HashMap<>();
expected.put("spam", Arrays.asList("a", "b"));
assertEquals(expected, parser.readMap());
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()
);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_Integer1() {
BEParser parser = new BEParser("i1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE, parser.readInteger());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test(expected = Exception.class)
public void testParse_String_Exception_LengthStartsWithZero() {
new BEParser("0:".getBytes()).readString(charset);
}
|
#vulnerable code
@Test(expected = Exception.class)
public void testParse_String_Exception_LengthStartsWithZero() {
new BEParser("0:").readString();
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_Integer1() {
BEParser parser = new BEParser("i1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE, parser.readInteger());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString(charset));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void delete(String key) throws IOException {
delete(propertyFile, key);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void write(String key, String value) throws IOException {
write(propertyFile, key, value);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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."));
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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.");
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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.");
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void definition_callee_symbol() {
FileInput tree = parse(
"def fn(): pass",
"fn('foo')"
);
assertNameAndQualifiedName(tree, "fn", null);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public int size() {
Long size = Objects.requireNonNull(JedisUtil.getJedis()).dbSize();
return size.intValue();
}
|
#vulnerable code
@Override
public int size() {
Long size = JedisUtil.getJedis().dbSize();
return size.intValue();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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.)");
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() throws CacheException {
Objects.requireNonNull(JedisUtil.getJedis()).flushDB();
}
|
#vulnerable code
@Override
public void clear() throws CacheException {
JedisUtil.getJedis().flushDB();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private HashSet<String> extractOutputVariables(String stateMachineText) throws IOException {
Set<String> names = ScXmlUtils.getAttributesValues(stateMachineText, "assign", "name");
return (HashSet<String>) names;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void addSuper(@NotNull Type superclass) {
this.superclass = superclass;
table.setSuper(superclass.table);
}
|
#vulnerable code
public void addSuper(@NotNull Type superclass) {
this.superclass = superclass;
table.addSuper(superclass.table);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
String[] list(String... names) {
return names;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int compareTo(@NotNull Object o) {
return getSingle().getStart() - ((Binding)o).getSingle().getStart();
}
|
#vulnerable code
public int compareTo(@NotNull Object o) {
return getFirstNode().getStart() - ((Binding)o).getFirstNode().getStart();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean equals(Object obj) {
if (obj instanceof Function) {
Function fo = (Function) obj;
return (fo.file.equals(file) && fo.start == start);
} else {
return false;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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));
}
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
String[] list(String... names) {
return names;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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++;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
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.