output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public synchronized void fetchContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException {
dockerAccess.getLogSync(containerId, createLogCallback(spec));
} | #vulnerable code
public synchronized void fetchContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException {
dockerAccess.getLogSync(containerId, new DefaultLogCallback(spec));
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFromSettingsSimple() throws MojoExecutionException {
setupServers();
AuthConfig config = factory.createAuthConfig(isPush, null, settings, "roland", "test.org");
assertNotNull(config);
verifyAuthConfig(config, "roland", "secret", "[email protected]");
} | #vulnerable code
@Test
public void testFromSettingsSimple() throws MojoExecutionException {
setupServers();
AuthConfig config = factory.createAuthConfig(null,settings, "roland", "test.org");
assertNotNull(config);
verifyAuthConfig(config, "roland", "secret", "[email protected]");
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MojoExecutionService getMojoExecutionService() {
return mojoExecutionService;
} | #vulnerable code
public MojoExecutionService getMojoExecutionService() {
checkBaseInitialization();
return mojoExecutionService;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException {
LogGetHandle handle = dockerAccess.getLogAsync(containerId, createLogCallback(spec));
logHandles.put(containerId, handle);
} | #vulnerable code
public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException {
LogGetHandle handle = dockerAccess.getLogAsync(containerId, new DefaultLogCallback(spec));
logHandles.put(containerId, handle);
}
#location 2
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void fetchLogs() {
try {
callback.open();
this.request = getLogRequest(false);
final HttpResponse response = client.execute(request);
parseResponse(response);
} catch (LogCallback.DoneException e) {
// Signifies we're finished with the log stream.
} catch (IOException exp) {
callback.error(exp.getMessage());
} finally {
callback.close();
}
} | #vulnerable code
public void fetchLogs() {
try {
callback.open();
this.request = getLogRequest(false);
final HttpResponse respone = client.execute(request);
parseResponse(respone);
} catch (LogCallback.DoneException e) {
finish();
} catch (IOException exp) {
callback.error(exp.getMessage());
} finally {
callback.close();
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void variableReplacement() throws MojoExecutionException {
PortMapping mapping = createPortMapping("jolokia.port:8080","18181:8181","127.0.0.1:9090:9090", "127.0.0.1:other.port:5678");
updateDynamicMapping(mapping, 8080, 49900);
updateDynamicMapping(mapping, 5678, 49901);
mapAndVerifyReplacement(mapping,
"http://localhost:49900/", "http://localhost:${jolokia.port}/",
"http://pirx:49900/", "http://pirx:${ jolokia.port}/");
mapAndVerifyReplacement(mapping,
"http://localhost:49901/", "http://localhost:${other.port}/",
"http://pirx:49901/", "http://pirx:${ other.port}/",
"http://49900/49901","http://${jolokia.port}/${other.port}");
assertEquals((int) mapping.getPortVariables().get("jolokia.port"), 49900);
assertEquals((int) mapping.getPortVariables().get("other.port"), 49901);
assertTrue(mapping.containsDynamicPorts());
assertEquals(4, mapping.getContainerPorts().size());
assertEquals(4, mapping.getPortsMap().size());
assertEquals(2, mapping.getBindToHostMap().size());
assertEquals(49900, (long) mapping.getPortVariables().get("jolokia.port"));
assertEquals(49901, (long) mapping.getPortVariables().get("other.port"));
Map<String,Integer> p = mapping.getPortsMap();
assertEquals(p.size(),4);
assertNull(p.get("8080/tcp"));
assertNull(p.get("5678/tcp"));
assertEquals(18181, (long) p.get("8181/tcp"));
assertEquals(9090, (long) p.get("9090/tcp"));
assertEquals("127.0.0.1", mapping.getBindToHostMap().get("9090/tcp"));
assertEquals("127.0.0.1", mapping.getBindToHostMap().get("5678/tcp"));
} | #vulnerable code
@Test
public void variableReplacement() throws MojoExecutionException {
PortMapping mapping = createPortMapping("jolokia.port:8080","18181:8181","127.0.0.1:9090:9090", "127.0.0.1:other.port:5678");
updateDynamicMapping(mapping, 8080, 49900);
updateDynamicMapping(mapping, 5678, 49901);
mapAndVerifyReplacement(mapping,
"http://localhost:49900/", "http://localhost:${jolokia.port}/",
"http://pirx:49900/", "http://pirx:${ jolokia.port}/");
mapAndVerifyReplacement(mapping,
"http://localhost:49901/", "http://localhost:${other.port}/",
"http://pirx:49901/", "http://pirx:${ other.port}/");
assertEquals((int) mapping.getPortVariables().get("jolokia.port"), 49900);
assertEquals((int) mapping.getPortVariables().get("other.port"), 49901);
assertTrue(mapping.containsDynamicPorts());
assertEquals(4, mapping.getContainerPorts().size());
assertEquals(4, mapping.getPortsMap().size());
assertEquals(2, mapping.getBindToHostMap().size());
assertEquals(49900, (long) mapping.getPortVariables().get("jolokia.port"));
assertEquals(49901, (long) mapping.getPortVariables().get("other.port"));
Map<String,Integer> p = mapping.getPortsMap();
assertEquals(p.size(),4);
assertNull(p.get("8080/tcp"));
assertNull(p.get("5678/tcp"));
assertEquals(18181, (long) p.get("8181/tcp"));
assertEquals(9090, (long) p.get("9090/tcp"));
assertEquals("127.0.0.1", mapping.getBindToHostMap().get("9090/tcp"));
assertEquals("127.0.0.1", mapping.getBindToHostMap().get("5678/tcp"));
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getVersion() {
try {
return CFLintMain.class.getPackage().getImplementationVersion();
} catch (Exception e) {
return "";
}
} | #vulnerable code
public static String getVersion() {
final InputStream is = Version.class
.getResourceAsStream("/META-INF/maven/com.github.cflint/CFLint/pom.properties");
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null && !line.startsWith("version=")) {
line = reader.readLine();
}
if (line != null) {
return line.replaceAll("version=", "");
}
} catch (final Exception e) {
try {
if (is != null) {
is.close();
}
} catch (final IOException e1) {
e1.printStackTrace();
}
}
return "";
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void execute() throws IOException, TransformerException, JAXBException {
final CFLint cflint = new CFLint(loadConfig(configfile));
cflint.setVerbose(verbose);
cflint.setLogError(logerror);
cflint.setQuiet(quiet);
cflint.setShowProgress(showprogress);
cflint.setProgressUsesThread(progressUsesThread);
if(extensions != null && extensions.trim().length() > 0){
try{
cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
}catch(Exception e){
System.err.println("Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage());
}
}
CFLintFilter filter = CFLintFilter.createFilter(verbose);
if(filterFile != null){
File ffile = new File(filterFile);
if(ffile.exists()){
FileInputStream fis = new FileInputStream(ffile);
byte b[] = new byte[fis.available()];
fis.read(b);
filter = CFLintFilter.createFilter(new String(b),verbose);
}
}
if (excludeCodes != null && excludeCodes.length > 0) {
filter.excludeCode(excludeCodes);
}
if (includeCodes != null && includeCodes.length > 0) {
filter.includeCode(includeCodes);
}
cflint.getBugs().setFilter(filter);
for (final String scanfolder : folder) {
cflint.scan(scanfolder);
}
if (stdIn) {
StringBuilder source = new StringBuilder();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
source.append(nextLine);
source.append(System.lineSeparator());
}
scanner.close();
cflint.process(source.toString(), stdInFile);
}
if (xmlOutput) {
Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(xmlOutFile);
if ("findbugs".equalsIgnoreCase(xmlstyle)) {
if(verbose) {
display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter);
} else {
if(verbose) {
display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().output(cflint.getBugs(), xmlwriter);
}
}
if (textOutput) {
if(textOutFile != null){
if(verbose) {
display("Writing text" + (stdOut ? "." : " to " + textOutFile));
}
}
Writer textwriter = stdOut || textOutFile==null ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile);
new TextOutput().output(cflint.getBugs(), textwriter);
}
if (htmlOutput) {
try {
if(verbose) {
display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile));
}
Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile);
new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter);
} catch (final TransformerException e) {
throw new IOException(e);
}
}
if (jsonOutput) {
if(verbose) {
display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
}
Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile);
new JSONOutput().output(cflint.getBugs(), jsonwriter);
}
if (includeCodes != null) {
cflint.getBugs().getFilter().includeCode(includeCodes);
}
if (excludeCodes != null) {
cflint.getBugs().getFilter().excludeCode(excludeCodes);
}
} | #vulnerable code
private void execute() throws IOException, TransformerException, JAXBException {
CFLintConfig config = null;
if(configfile != null){
if(configfile.toLowerCase().endsWith(".xml")){
config = ConfigUtils.unmarshal(new FileInputStream(configfile), CFLintConfig.class);
}else{
config = ConfigUtils.unmarshalJson(new FileInputStream(configfile), CFLintConfig.class);
}
}
final CFLint cflint = new CFLint(config);
cflint.setVerbose(verbose);
cflint.setLogError(logerror);
cflint.setQuiet(quiet);
cflint.setShowProgress(showprogress);
cflint.setProgressUsesThread(progressUsesThread);
if(extensions != null && extensions.trim().length() > 0){
try{
cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
}catch(Exception e){
System.err.println("Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage());
}
}
CFLintFilter filter = CFLintFilter.createFilter(verbose);
if(filterFile != null){
File ffile = new File(filterFile);
if(ffile.exists()){
FileInputStream fis = new FileInputStream(ffile);
byte b[] = new byte[fis.available()];
fis.read(b);
filter = CFLintFilter.createFilter(new String(b),verbose);
}
}
if (excludeCodes != null && excludeCodes.length > 0) {
filter.excludeCode(excludeCodes);
}
if (includeCodes != null && includeCodes.length > 0) {
filter.includeCode(includeCodes);
}
cflint.getBugs().setFilter(filter);
for (final String scanfolder : folder) {
cflint.scan(scanfolder);
}
if (stdIn) {
StringBuilder source = new StringBuilder();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
source.append(nextLine);
source.append(System.lineSeparator());
}
scanner.close();
cflint.process(source.toString(), stdInFile);
}
if (xmlOutput) {
Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(xmlOutFile);
if ("findbugs".equalsIgnoreCase(xmlstyle)) {
if(verbose) {
display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter);
} else {
if(verbose) {
display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().output(cflint.getBugs(), xmlwriter);
}
}
if (textOutput) {
if(textOutFile != null){
if(verbose) {
display("Writing text" + (stdOut ? "." : " to " + textOutFile));
}
}
Writer textwriter = stdOut || textOutFile==null ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile);
new TextOutput().output(cflint.getBugs(), textwriter);
}
if (htmlOutput) {
try {
if(verbose) {
display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile));
}
Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile);
new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter);
} catch (final TransformerException e) {
throw new IOException(e);
}
}
if (jsonOutput) {
if(verbose) {
display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
}
Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile);
new JSONOutput().output(cflint.getBugs(), jsonwriter);
}
if (includeCodes != null) {
cflint.getBugs().getFilter().includeCode(includeCodes);
}
if (excludeCodes != null) {
cflint.getBugs().getFilter().excludeCode(excludeCodes);
}
}
#location 30
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String load(final File file) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
final byte[] b = new byte[fis.available()];
fis.read(b);
return new String(b);
} catch (final Exception e) {
return null;
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
return null;
}
}
} | #vulnerable code
static String load(final File file) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
final byte[] b = new byte[fis.available()];
fis.read(b);
return new String(b);
} catch (final Exception e) {
return null;
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean include(final BugInfo bugInfo) {
if (includeCodes != null && !includeCodes.contains(bugInfo.getMessageCode())){
return false;
}
if (data != null) {
for (final Object item : data) {
final JSONObject jsonObj = (JSONObject) item;
if (jsonObj.containsKey("file")) {
if (!bugInfo.getFilename().matches(jsonObj.get("file").toString())) {
continue;
}else if (verbose){
System.out.println("Exclude matched file " + bugInfo.getFilename());
}
}
if (jsonObj.containsKey("code")) {
if (!bugInfo.getMessageCode().matches(jsonObj.get("code").toString())) {
continue;
}else if (verbose){
System.out.println("Exclude matched message code " + bugInfo.getMessageCode());
}
}
if (jsonObj.containsKey("function")) {
if (bugInfo.getFunction() == null
|| !bugInfo.getFunction().matches(jsonObj.get("function").toString())) {
continue;
}else if (verbose){
System.out.println("Exclude matched function name " + bugInfo.getFunction());
}
}
if (jsonObj.containsKey("variable")) {
if (bugInfo.getVariable() == null
|| !bugInfo.getVariable().matches(jsonObj.get("variable").toString())) {
continue;
}else if (verbose){
System.out.println("Exclude matched variable name " + bugInfo.getVariable());
}
}
if (jsonObj.containsKey("line")) {
if (bugInfo.getLine() > 0
|| !new Integer(bugInfo.getLine()).toString().matches(jsonObj.get("line").toString())) {
continue;
}else if (verbose){
System.out.println("Exclude matched line " + bugInfo.getLine());
}
}
if (jsonObj.containsKey("expression")) {
if (bugInfo.getExpression() == null
|| !bugInfo.getExpression().matches(jsonObj.get("expression").toString())) {
continue;
}else if (verbose){
System.out.println("Exclude matched expression " + bugInfo.getExpression());
}
}
return false;
}
}
return true;
} | #vulnerable code
public boolean include(final BugInfo bugInfo) {
if (includeCodes != null && !includeCodes.contains(bugInfo.getMessageCode())){
return false;
}
if (data != null) {
for (final Object item : data) {
final JSONObject jsonObj = (JSONObject) item;
if (jsonObj.containsKey("file")) {
if (!bugInfo.getFilename().matches(jsonObj.get("file").toString())) {
continue;
}
}
if (jsonObj.containsKey("code")) {
if (!bugInfo.getMessageCode().matches(jsonObj.get("code").toString())) {
continue;
}
}
if (jsonObj.containsKey("function")) {
if (bugInfo.getFunction() == null
|| !bugInfo.getFunction().matches(jsonObj.get("function").toString())) {
continue;
}
}
if (jsonObj.containsKey("variable")) {
if (bugInfo.getVariable() == null
|| !bugInfo.getFunction().matches(jsonObj.get("function").toString())) {
continue;
}
}
if (jsonObj.containsKey("line")) {
if (bugInfo.getLine() > 0
|| !new Integer(bugInfo.getLine()).toString().matches(jsonObj.get("line").toString())) {
continue;
}
}
if (jsonObj.containsKey("expression")) {
if (bugInfo.getExpression() == null
|| !bugInfo.getExpression().matches(jsonObj.get("expression").toString())) {
continue;
}
}
return false;
}
}
return true;
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getVersion() {
try {
return CFLintMain.class.getPackage().getImplementationVersion();
} catch (Exception e) {
return "";
}
} | #vulnerable code
public static String getVersion() {
final InputStream is = Version.class
.getResourceAsStream("/META-INF/maven/com.github.cflint/CFLint/pom.properties");
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null && !line.startsWith("version=")) {
line = reader.readLine();
}
if (line != null) {
return line.replaceAll("version=", "");
}
} catch (final Exception e) {
try {
if (is != null) {
is.close();
}
} catch (final IOException e1) {
e1.printStackTrace();
}
}
return "";
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void execute() throws IOException, TransformerException, JAXBException {
final CFLint cflint = new CFLint(loadConfig(configfile));
cflint.setVerbose(verbose);
cflint.setLogError(logerror);
cflint.setQuiet(quiet);
cflint.setShowProgress(showprogress);
cflint.setProgressUsesThread(progressUsesThread);
if(extensions != null && extensions.trim().length() > 0){
try{
cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
}catch(Exception e){
System.err.println("Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage());
}
}
CFLintFilter filter = CFLintFilter.createFilter(verbose);
if(filterFile != null){
File ffile = new File(filterFile);
if(ffile.exists()){
FileInputStream fis = new FileInputStream(ffile);
byte b[] = new byte[fis.available()];
fis.read(b);
filter = CFLintFilter.createFilter(new String(b),verbose);
}
}
if (excludeCodes != null && excludeCodes.length > 0) {
filter.excludeCode(excludeCodes);
}
if (includeCodes != null && includeCodes.length > 0) {
filter.includeCode(includeCodes);
}
cflint.getBugs().setFilter(filter);
for (final String scanfolder : folder) {
cflint.scan(scanfolder);
}
if (stdIn) {
StringBuilder source = new StringBuilder();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
source.append(nextLine);
source.append(System.lineSeparator());
}
scanner.close();
cflint.process(source.toString(), stdInFile);
}
if (xmlOutput) {
Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(xmlOutFile);
if ("findbugs".equalsIgnoreCase(xmlstyle)) {
if(verbose) {
display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter);
} else {
if(verbose) {
display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().output(cflint.getBugs(), xmlwriter);
}
}
if (textOutput) {
if(textOutFile != null){
if(verbose) {
display("Writing text" + (stdOut ? "." : " to " + textOutFile));
}
}
Writer textwriter = stdOut || textOutFile==null ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile);
new TextOutput().output(cflint.getBugs(), textwriter);
}
if (htmlOutput) {
try {
if(verbose) {
display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile));
}
Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile);
new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter);
} catch (final TransformerException e) {
throw new IOException(e);
}
}
if (jsonOutput) {
if(verbose) {
display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
}
Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile);
new JSONOutput().output(cflint.getBugs(), jsonwriter);
}
if (includeCodes != null) {
cflint.getBugs().getFilter().includeCode(includeCodes);
}
if (excludeCodes != null) {
cflint.getBugs().getFilter().excludeCode(excludeCodes);
}
} | #vulnerable code
private void execute() throws IOException, TransformerException, JAXBException {
CFLintConfig config = null;
if(configfile != null){
if(configfile.toLowerCase().endsWith(".xml")){
config = ConfigUtils.unmarshal(new FileInputStream(configfile), CFLintConfig.class);
}else{
config = ConfigUtils.unmarshalJson(new FileInputStream(configfile), CFLintConfig.class);
}
}
final CFLint cflint = new CFLint(config);
cflint.setVerbose(verbose);
cflint.setLogError(logerror);
cflint.setQuiet(quiet);
cflint.setShowProgress(showprogress);
cflint.setProgressUsesThread(progressUsesThread);
if(extensions != null && extensions.trim().length() > 0){
try{
cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
}catch(Exception e){
System.err.println("Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage());
}
}
CFLintFilter filter = CFLintFilter.createFilter(verbose);
if(filterFile != null){
File ffile = new File(filterFile);
if(ffile.exists()){
FileInputStream fis = new FileInputStream(ffile);
byte b[] = new byte[fis.available()];
fis.read(b);
filter = CFLintFilter.createFilter(new String(b),verbose);
}
}
if (excludeCodes != null && excludeCodes.length > 0) {
filter.excludeCode(excludeCodes);
}
if (includeCodes != null && includeCodes.length > 0) {
filter.includeCode(includeCodes);
}
cflint.getBugs().setFilter(filter);
for (final String scanfolder : folder) {
cflint.scan(scanfolder);
}
if (stdIn) {
StringBuilder source = new StringBuilder();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
source.append(nextLine);
source.append(System.lineSeparator());
}
scanner.close();
cflint.process(source.toString(), stdInFile);
}
if (xmlOutput) {
Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(xmlOutFile);
if ("findbugs".equalsIgnoreCase(xmlstyle)) {
if(verbose) {
display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter);
} else {
if(verbose) {
display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().output(cflint.getBugs(), xmlwriter);
}
}
if (textOutput) {
if(textOutFile != null){
if(verbose) {
display("Writing text" + (stdOut ? "." : " to " + textOutFile));
}
}
Writer textwriter = stdOut || textOutFile==null ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile);
new TextOutput().output(cflint.getBugs(), textwriter);
}
if (htmlOutput) {
try {
if(verbose) {
display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile));
}
Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile);
new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter);
} catch (final TransformerException e) {
throw new IOException(e);
}
}
if (jsonOutput) {
if(verbose) {
display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
}
Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile);
new JSONOutput().output(cflint.getBugs(), jsonwriter);
}
if (includeCodes != null) {
cflint.getBugs().getFilter().includeCode(includeCodes);
}
if (excludeCodes != null) {
cflint.getBugs().getFilter().excludeCode(excludeCodes);
}
}
#location 41
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getVersion() {
try {
return CFLintMain.class.getPackage().getImplementationVersion();
} catch (Exception e) {
return "";
}
} | #vulnerable code
public static String getVersion() {
final InputStream is = Version.class
.getResourceAsStream("/META-INF/maven/com.github.cflint/CFLint/pom.properties");
try {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null && !line.startsWith("version=")) {
line = reader.readLine();
}
if (line != null) {
return line.replaceAll("version=", "");
}
} catch (final Exception e) {
try {
if (is != null) {
is.close();
}
} catch (final IOException e1) {
e1.printStackTrace();
}
}
return "";
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static CFLintConfig loadConfig(final String configfile) {
if (configfile != null) {
try {
CFLintPluginInfo pluginInfo = null;
if (configfile.toLowerCase().endsWith(".xml")) {
final Object configObj = ConfigUtils.unmarshal(new FileInputStream(configfile));
if (configObj instanceof CFLintPluginInfo)
pluginInfo = (CFLintPluginInfo) configObj;
else if(configObj instanceof CFLintConfig ){
return (CFLintConfig) configObj;
}
} else {
return ConfigUtils.unmarshalJson(new FileInputStream(configfile), CFLintConfig.class);
}
CFLintConfig returnVal = new CFLintConfig();
if (pluginInfo != null)
returnVal.setRules(pluginInfo.getRules());
return returnVal;
} catch (final Exception e) {
System.err.println("Unable to load config file. " + e.getMessage());
}
}
return null;
} | #vulnerable code
private static CFLintConfig loadConfig(final String configfile) {
if (configfile != null) {
try {
CFLintPluginInfo pluginInfo=null;
if (configfile.toLowerCase().endsWith(".xml")) {
final Object configObj = ConfigUtils.unmarshal(new FileInputStream(configfile));
if (configObj instanceof CFLintPluginInfo)
pluginInfo= (CFLintPluginInfo) configObj;
else if(configObj instanceof CFLintConfig ){
return (CFLintConfig) configObj;
}
} else {
return ConfigUtils.unmarshalJson(new FileInputStream(configfile), CFLintConfig.class);
}
CFLintConfig returnVal = new CFLintConfig();
returnVal.setRules(pluginInfo.getRules());
return returnVal;
} catch (final Exception e) {
System.err.println("Unable to load config file. " + e.getMessage());
}
}
return null;
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void registerRuleOverrides(Context context, final Token functionToken) {
final String mlText = PrecedingCommentReader.getMultiLine(context, functionToken);
if(mlText != null && !mlText.isEmpty()){
final Pattern pattern = Pattern.compile(".*\\s*@CFLintIgnore\\s+([\\w,_]+)\\s*.*", Pattern.DOTALL);
final Matcher matcher = pattern.matcher(mlText);
if (matcher.matches()) {
String ignoreCodes = matcher.group(1);
context.ignore(Arrays.asList(ignoreCodes.split(",\\s*")));
}
}
} | #vulnerable code
protected void registerRuleOverrides(Context context, final Token functionToken) {
Iterable<Token> tokens = context.beforeTokens(functionToken);
for (Token currentTok : tokens) {
if (currentTok.getChannel() == Token.HIDDEN_CHANNEL && currentTok.getType() == CFSCRIPTLexer.ML_COMMENT) {
String mlText = currentTok.getText();
Pattern pattern = Pattern.compile(".*\\s*@CFLintIgnore\\s+([\\w,_]+)\\s*.*", Pattern.DOTALL);
Matcher matcher = pattern.matcher(mlText);
if (matcher.matches()) {
String ignoreCodes = matcher.group(1);
context.ignore(Arrays.asList(ignoreCodes.split(",\\s*")));
}
} else if (currentTok.getLine() < functionToken.getLine()) {
break;
}
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void execute() throws IOException, TransformerException, JAXBException, MarshallerException {
final CFLint cflint = new CFLint(buildConfigChain());
cflint.setVerbose(verbose);
cflint.setLogError(logerror);
cflint.setQuiet(quiet);
cflint.setStrictIncludes(strictInclude);
cflint.setShowProgress(showprogress);
cflint.setProgressUsesThread(progressUsesThread);
if (extensions != null && extensions.trim().length() > 0) {
try {
cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
} catch (final Exception e) {
System.err.println(
"Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage());
}
}
final CFLintFilter filter = createBaseFilter();
cflint.getBugs().setFilter(filter);
for (final String scanfolder : folder) {
cflint.scan(scanfolder);
}
if (stdIn) {
final StringBuilder source = new StringBuilder();
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String nextLine = scanner.nextLine();
source.append(nextLine);
source.append(System.lineSeparator());
}
scanner.close();
cflint.process(source.toString(), stdInFile);
}
if (xmlOutput) {
final Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out)
: createWriter(xmlOutFile, StandardCharsets.UTF_8);
if ("findbugs".equalsIgnoreCase(xmlstyle)) {
if (verbose) {
display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter, showStats, cflint.getStats());
} else {
if (verbose) {
display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
}
new DefaultCFlintResultMarshaller().output(cflint.getBugs(), xmlwriter, showStats);
}
}
if (textOutput) {
if (textOutFile != null && verbose) {
display("Writing text" + (stdOut ? "." : " to " + textOutFile));
}
final Writer textwriter = stdOut || textOutFile == null ? new OutputStreamWriter(System.out)
: new FileWriter(textOutFile);
new TextOutput().output(cflint.getBugs(), textwriter, showStats);
}
if (htmlOutput) {
try {
if (verbose) {
display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile));
}
final Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile);
new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter, showStats, cflint.getStats());
} catch (final TransformerException e) {
throw new IOException(e);
}
}
if (jsonOutput) {
if (verbose) {
display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
}
final Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile);
new JSONOutput().output(cflint.getBugs(), jsonwriter, showStats);
}
if (verbose) {
display("Total files scanned: " + cflint.getStats().getFileCount());
display("Total size: " + cflint.getStats().getTotalSize());
}
} | #vulnerable code
private void execute() throws IOException, TransformerException, JAXBException, MarshallerException {
final CFLint cflint = new CFLint(buildConfigChain());
cflint.setVerbose(verbose);
cflint.setLogError(logerror);
cflint.setQuiet(quiet);
cflint.setStrictIncludes(strictInclude);
cflint.setShowProgress(showprogress);
cflint.setProgressUsesThread(progressUsesThread);
if (extensions != null && extensions.trim().length() > 0) {
try {
cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
} catch (final Exception e) {
System.err.println(
"Unable to use extensions (" + extensions + ") using default instead. " + e.getMessage());
}
}
final CFLintFilter filter = createBaseFilter();
cflint.getBugs().setFilter(filter);
for (final String scanfolder : folder) {
cflint.scan(scanfolder);
}
if (stdIn) {
final StringBuilder source = new StringBuilder();
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String nextLine = scanner.nextLine();
source.append(nextLine);
source.append(System.lineSeparator());
}
scanner.close();
cflint.process(source.toString(), stdInFile);
}
if (xmlOutput) {
final Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out)
: createWriter(xmlOutFile, StandardCharsets.UTF_8);
if ("findbugs".equalsIgnoreCase(xmlstyle)) {
if (verbose) {
display("Writing XML findbugs style" + (stdOut ? "." : " to " + xmlOutFile));
}
new XMLOutput().outputFindBugs(cflint.getBugs(), xmlwriter, showStats);
} else {
if (verbose) {
display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
}
new DefaultCFlintResultMarshaller().output(cflint.getBugs(), xmlwriter, showStats);
}
}
if (textOutput) {
if (textOutFile != null && verbose) {
display("Writing text" + (stdOut ? "." : " to " + textOutFile));
}
final Writer textwriter = stdOut || textOutFile == null ? new OutputStreamWriter(System.out)
: new FileWriter(textOutFile);
new TextOutput().output(cflint.getBugs(), textwriter, showStats);
}
if (htmlOutput) {
try {
if (verbose) {
display("Writing HTML" + (stdOut ? "." : " to " + htmlOutFile));
}
final Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile);
new HTMLOutput(htmlStyle).output(cflint.getBugs(), htmlwriter, showStats);
} catch (final TransformerException e) {
throw new IOException(e);
}
}
if (jsonOutput) {
if (verbose) {
display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
}
final Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile);
new JSONOutput().output(cflint.getBugs(), jsonwriter, showStats);
}
if (verbose) {
display("Total files scanned: " + cflint.getStats().getFileCount());
display("Total size: " + cflint.getStats().getTotalSize());
}
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String load(final File file) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
final byte[] b = new byte[fis.available()];
fis.read(b);
return new String(b);
} catch (final Exception e) {
return null;
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
return null;
}
}
} | #vulnerable code
static String load(final File file) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
final byte[] b = new byte[fis.available()];
fis.read(b);
return new String(b);
} catch (final Exception e) {
return null;
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void mergeConfigFileInFilter(CFLintFilter filter)
{
CFLintConfig cfg = loadConfig(configfile);
if(cfg != null){
for(PluginMessage message : cfg.getIncludes())
{
filter.includeCode(message.getCode());
}
for(PluginMessage message : cfg.getExcludes())
{
filter.excludeCode(message.getCode());
}
}
} | #vulnerable code
private void mergeConfigFileInFilter(CFLintFilter filter)
{
CFLintConfig cfg = loadConfig(configfile);
for(PluginMessage message : cfg.getIncludes())
{
filter.includeCode(message.getCode());
}
for(PluginMessage message : cfg.getExcludes())
{
filter.excludeCode(message.getCode());
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void expression(final CFExpression expression, final Context context, final BugList bugs) {
String repeatThreshold = getParameter("maximum");
String maxWarnings = getParameter("maxWarnings");
String warningScope = getParameter("warningScope");
if (repeatThreshold != null) {
threshold = Integer.parseInt(repeatThreshold);
}
if (maxWarnings != null) {
warningThreshold = Integer.parseInt(maxWarnings);
}
if (expression instanceof CFLiteral) {
CFLiteral literal = (CFLiteral) expression;
String name = literal.Decompile(0).replace("'","");
if (isCommon(name)) {
return;
}
int lineNo = literal.getLine() + context.startLine() - 1;
if (warningScope == null || warningScope.equals("global")) {
literalCount(name, lineNo, globalLiterals, true, context, bugs);
}
else if (warningScope.equals("local")) {
literalCount(name, lineNo, functionListerals, false, context, bugs);
}
}
} | #vulnerable code
@Override
public void expression(final CFExpression expression, final Context context, final BugList bugs) {
String repeatThreshold = getParameter("maximum");
int threshold = REPEAT_THRESHOLD;
if (repeatThreshold != null) {
threshold = Integer.parseInt(repeatThreshold);
}
if (expression instanceof CFLiteral) {
CFLiteral literal = (CFLiteral) expression;
String name = literal.Decompile(0).replace("'","");
int count = 1;
if (isCommon(name)) {
return;
}
if (literals.get(name) == null) {
literals.put(name, count);
done.put(name, false);
}
else {
count = literals.get(name);
count++;
literals.put(name, count);
}
if (count > threshold && !done.get(name)) {
int lineNo = literal.getLine() + context.startLine() - 1;
magicValue(name, lineNo, context, bugs);
done.put(name, true);
}
}
}
#location 29
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public AsyncIOWriter write(AtmosphereResponse r, byte[] data, int offset, int length) throws IOException {
boolean transform = filters.size() > 0 && r.getStatus() < 400;
if (transform) {
data = transform(r, data, offset, length);
offset = 0;
length = data.length;
}
logger.trace("About to write to {}", r.resource() != null ? r.resource().uuid() : "null");
if (channel.isOpen()) {
final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
pendingWrite.incrementAndGet();
if (writeHeader && !headerWritten) {
buffer.writeBytes(constructStatusAndHeaders(r).getBytes("UTF-8"));
headerWritten = true;
}
if (headerWritten) {
buffer.writeBytes(Integer.toHexString(length - offset).getBytes("UTF-8"));
buffer.writeBytes(CHUNK_DELIMITER);
}
buffer.writeBytes(data, offset, length);
if (headerWritten) {
buffer.writeBytes(CHUNK_DELIMITER);
}
channel.write(buffer).addListener(listener);
byteWritten = true;
lastWrite = System.currentTimeMillis();
} else {
logger.debug("Trying to write on a closed channel {}", channel);
throw new IOException("Channel closed");
}
headerWritten = true;
return this;
} | #vulnerable code
@Override
public AsyncIOWriter write(AtmosphereResponse r, byte[] data, int offset, int length) throws IOException {
boolean transform = filters.size() > 0 && r.getStatus() < 400;
if (transform) {
data = transform(r, data, offset, length);
offset = 0;
length = data.length;
}
logger.trace("About to write to {}", r.resource() != null ? r.resource().uuid() : "null");
if (channel.isOpen()) {
final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
pendingWrite.incrementAndGet();
if (writeHeader && !headerWritten) {
buffer.writeBytes(constructStatusAndHeaders(r).getBytes("UTF-8"));
headerWritten = true;
}
ChannelBufferOutputStream c = new ChannelBufferOutputStream(buffer);
if (headerWritten) {
c.write(Integer.toHexString(length - offset).getBytes("UTF-8"));
c.write(CHUNK_DELIMITER);
}
c.write(data, offset, length);
if (headerWritten) {
c.write(CHUNK_DELIMITER);
}
channel.write(c.buffer()).addListener(listener);
byteWritten = true;
lastWrite = System.currentTimeMillis();
} else {
logger.debug("Trying to write on a closed channel {}", channel);
throw new IOException("Channel closed");
}
headerWritten = true;
return this;
}
#location 32
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void _close() {
if (!isClosed.getAndSet(true)) {
headerWritten = false;
final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
buffer.writeBytes(ENDCHUNK);
channel.write(buffer).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!keepAlive) {
channel.close().awaitUninterruptibly();
}
}
});
}
} | #vulnerable code
void _close() {
if (!isClosed.getAndSet(true)) {
headerWritten = false;
final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
ChannelBufferOutputStream c = new ChannelBufferOutputStream(buffer);
try {
c.write(ENDCHUNK);
channel.write(buffer).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!keepAlive) {
channel.close().awaitUninterruptibly();
}
}
});
} catch (IOException e) {
logger.trace("Close error", e);
}
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void close() {
if (!open.compareAndSet(true, false)) {
return;
}
LOG.debug("Closing GStreamer device");
pipelineStop();
image = null;
} | #vulnerable code
@Override
public void close() {
if (!open.compareAndSet(true, false)) {
return;
}
LOG.debug("Closing GStreamer device");
image = null;
LOG.debug("Unlink elements");
pipe.setState(State.NULL);
Element.unlinkMany(source, filter, sink);
pipe.removeMany(source, filter, sink);
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void resume() {
if (!paused) {
return;
}
paused = false;
} | #vulnerable code
public void resume() {
if (!paused) {
return;
}
synchronized (repainter) {
repainter.notifyAll();
}
paused = false;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void open() {
if (!open.compareAndSet(false, true)) {
return;
}
LOG.debug("Opening GStreamer device");
init();
starting.set(true);
Dimension size = getResolution();
image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
image.setAccelerationPriority(0);
image.flush();
if (caps != null) {
caps.dispose();
}
caps = Caps.fromString(String.format("%s,framerate=30/1,width=%d,height=%d", format, size.width, size.height));
filter.setCaps(caps);
LOG.debug("Using filter caps: {}", caps);
pipelinePlay();
LOG.debug("Wait for device to be ready");
// wait max 20s for image to appear
synchronized (this) {
try {
this.wait(20000);
} catch (InterruptedException e) {
return;
}
}
} | #vulnerable code
@Override
public void open() {
if (!open.compareAndSet(false, true)) {
return;
}
LOG.debug("Opening GStreamer device");
init();
starting.set(true);
Dimension size = getResolution();
image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
image.setAccelerationPriority(0);
image.flush();
if (caps != null) {
caps.dispose();
}
caps = Caps.fromString(String.format("%s,width=%d,height=%d", format, size.width, size.height));
filter.setCaps(caps);
LOG.debug("Link elements");
pipe.addMany(source, filter, sink);
Element.linkMany(source, filter, sink);
pipe.setState(State.PLAYING);
// wait max 20s for image to appear
synchronized (this) {
LOG.debug("Wait for device to be ready");
try {
this.wait(20000);
} catch (InterruptedException e) {
return;
}
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void dispose() {
if (!disposed.compareAndSet(false, true)) {
return;
}
LOG.debug("Disposing GStreamer device");
close();
source.dispose();
filter.dispose();
jpegparse.dispose();
jpegdec.dispose();
caps.dispose();
sink.dispose();
pipe.dispose();
} | #vulnerable code
@Override
public void dispose() {
if (!disposed.compareAndSet(false, true)) {
return;
}
LOG.debug("Disposing GStreamer device");
close();
source.dispose();
filter.dispose();
jpegpar.dispose();
jpegdec.dispose();
caps.dispose();
sink.dispose();
pipe.dispose();
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void close() {
if (!open.compareAndSet(true, false)) {
return;
}
LOG.debug("Closing GStreamer device");
pipelineStop();
image = null;
} | #vulnerable code
@Override
public void close() {
if (!open.compareAndSet(true, false)) {
return;
}
LOG.debug("Closing GStreamer device");
image = null;
LOG.debug("Unlink elements");
pipe.setState(State.NULL);
Element.unlinkMany(source, filter, sink);
pipe.removeMany(source, filter, sink);
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void open() {
if (!open.compareAndSet(false, true)) {
return;
}
LOG.debug("Opening GStreamer device");
init();
starting.set(true);
Dimension size = getResolution();
image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
image.setAccelerationPriority(0);
image.flush();
if (caps != null) {
caps.dispose();
}
caps = Caps.fromString(String.format("%s,framerate=30/1,width=%d,height=%d", format, size.width, size.height));
filter.setCaps(caps);
LOG.debug("Using filter caps: {}", caps);
pipelinePlay();
LOG.debug("Wait for device to be ready");
// wait max 20s for image to appear
synchronized (this) {
try {
this.wait(20000);
} catch (InterruptedException e) {
return;
}
}
} | #vulnerable code
@Override
public void open() {
if (!open.compareAndSet(false, true)) {
return;
}
LOG.debug("Opening GStreamer device");
init();
starting.set(true);
Dimension size = getResolution();
image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
image.setAccelerationPriority(0);
image.flush();
if (caps != null) {
caps.dispose();
}
caps = Caps.fromString(String.format("%s,width=%d,height=%d", format, size.width, size.height));
filter.setCaps(caps);
LOG.debug("Link elements");
pipe.addMany(source, filter, sink);
Element.linkMany(source, filter, sink);
pipe.setState(State.PLAYING);
// wait max 20s for image to appear
synchronized (this) {
LOG.debug("Wait for device to be ready");
try {
this.wait(20000);
} catch (InterruptedException e) {
return;
}
}
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void certificateReadThrowsRuntimeException()
throws ExecutionException, InterruptedException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
try {
FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory());
Assert.fail();
} catch (IOException e) {
Assert.assertEquals("Expected", e.getMessage());
}
} | #vulnerable code
@Test
public void certificateReadThrowsRuntimeException()
throws ExecutionException, InterruptedException, IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
FirebaseCredential credential =
FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory());
try {
Tasks.await(credential.getAccessToken(false));
Assert.fail();
} catch (Exception e) {
Assert.assertEquals("java.io.IOException: Failed to read service account", e.getMessage());
Assert.assertEquals("Expected", e.getCause().getCause().getMessage());
}
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ConnectionContext getConnectionContext() {
return new ConnectionContext(
this.logger,
wrapAuthTokenProvider(this.getAuthTokenProvider()),
this.getExecutorService(),
this.isPersistenceEnabled(),
FirebaseDatabase.getSdkVersion(),
this.getUserAgent());
} | #vulnerable code
public ConnectionContext getConnectionContext() {
return new ConnectionContext(
this.getLogger(),
wrapAuthTokenProvider(this.getAuthTokenProvider()),
this.getExecutorService(),
this.isPersistenceEnabled(),
FirebaseDatabase.getSdkVersion(),
this.getUserAgent());
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String streamToString(InputStream inputStream) throws IOException {
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
return CharStreams.toString(reader);
} | #vulnerable code
private static String streamToString(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char[] buffer = new char[256];
int length;
while ((length = reader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, length);
}
inputStream.close();
return stringBuilder.toString();
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void refreshTokenReadThrowsRuntimeException()
throws ExecutionException, InterruptedException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
try {
FirebaseCredentials.fromRefreshToken(inputStream, transport, Utils.getDefaultJsonFactory());
Assert.fail();
} catch (IOException e) {
Assert.assertEquals("Expected", e.getMessage());
}
} | #vulnerable code
@Test
public void refreshTokenReadThrowsRuntimeException()
throws ExecutionException, InterruptedException, IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
FirebaseCredential credential =
FirebaseCredentials.fromRefreshToken(inputStream, transport, Utils.getDefaultJsonFactory());
try {
Tasks.await(credential.getAccessToken(false));
Assert.fail();
} catch (Exception e) {
Assert.assertEquals("java.io.IOException: Failed to read refresh token", e.getMessage());
Assert.assertEquals("Expected", e.getCause().getCause().getMessage());
}
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void canConvertDoubles() throws IOException {
List<Double> doubles = Arrays.asList(Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL);
for (Double original : doubles) {
String jsonString = JsonMapper.serializeJson(original);
double converted = (Double) JsonMapper.parseJsonValue(jsonString);
assertEquals(original, converted, 0);
}
} | #vulnerable code
@Test
public void canConvertDoubles() throws IOException {
List<Double> doubles = Arrays.asList(Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL);
for (Double original : doubles) {
String jsonString = JsonMapper.serializeJsonValue(original);
double converted = (Double) JsonMapper.parseJsonValue(jsonString);
assertEquals(original, converted, 0);
}
}
#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 canConvertLongs() throws IOException {
List<Long> longs = Arrays.asList(Long.MAX_VALUE, Long.MIN_VALUE);
for (Long original : longs) {
String jsonString = JsonMapper.serializeJson(original);
long converted = (Long) JsonMapper.parseJsonValue(jsonString);
assertEquals((long) original, converted);
}
} | #vulnerable code
@Test
public void canConvertLongs() throws IOException {
List<Long> longs = Arrays.asList(Long.MAX_VALUE, Long.MIN_VALUE);
for (Long original : longs) {
String jsonString = JsonMapper.serializeJsonValue(original);
long converted = (Long) JsonMapper.parseJsonValue(jsonString);
assertEquals((long) original, converted);
}
}
#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 testDeleteInstanceIdError() throws Exception {
final MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
MockHttpTransport transport = new MockHttpTransport.Builder()
.setLowLevelHttpResponse(response)
.build();
FirebaseOptions options = APP_OPTIONS.toBuilder()
.setHttpTransport(transport)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
// Disable retries by passing a regular HttpRequestFactory.
FirebaseInstanceId instanceId = new FirebaseInstanceId(app, transport.createRequestFactory());
TestResponseInterceptor interceptor = new TestResponseInterceptor();
instanceId.setInterceptor(interceptor);
try {
for (int statusCode : ERROR_CODES.keySet()) {
response.setStatusCode(statusCode).setContent("test error");
try {
instanceId.deleteInstanceIdAsync("test-iid").get();
fail("No error thrown for HTTP error");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof FirebaseInstanceIdException);
checkFirebaseInstanceIdException((FirebaseInstanceIdException) e.getCause(), statusCode);
}
assertNotNull(interceptor.getResponse());
HttpRequest request = interceptor.getResponse().getRequest();
assertEquals(HttpMethods.DELETE, request.getRequestMethod());
assertEquals(TEST_URL, request.getUrl().toString());
}
} finally {
app.delete();
}
} | #vulnerable code
@Test
public void testDeleteInstanceIdError() throws Exception {
final MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
MockHttpTransport transport = new MockHttpTransport.Builder()
.setLowLevelHttpResponse(response)
.build();
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(new MockGoogleCredentials("test-token"))
.setProjectId("test-project")
.setHttpTransport(transport)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
// Disable retries by passing a regular HttpRequestFactory.
FirebaseInstanceId instanceId = new FirebaseInstanceId(app, transport.createRequestFactory());
TestResponseInterceptor interceptor = new TestResponseInterceptor();
instanceId.setInterceptor(interceptor);
try {
for (int statusCode : ERROR_CODES.keySet()) {
response.setStatusCode(statusCode).setContent("test error");
try {
instanceId.deleteInstanceIdAsync("test-iid").get();
fail("No error thrown for HTTP error");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof FirebaseInstanceIdException);
checkFirebaseInstanceIdException((FirebaseInstanceIdException) e.getCause(), statusCode);
}
assertNotNull(interceptor.getResponse());
HttpRequest request = interceptor.getResponse().getRequest();
assertEquals(HttpMethods.DELETE, request.getRequestMethod());
assertEquals(TEST_URL, request.getUrl().toString());
}
} finally {
app.delete();
}
}
#location 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String streamToString(InputStream inputStream) throws IOException {
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
return CharStreams.toString(reader);
} | #vulnerable code
private static String streamToString(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char[] buffer = new char[256];
int length;
while ((length = reader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, length);
}
inputStream.close();
return stringBuilder.toString();
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) {
Configuration cfg = parseLegacyConfiguration();
if (cfg == null) {
cfg = parseConfiguration(args);
}
if (cfg == null) {
Options options = createOptions();
printHelp(options);
return;
}
String sourceAddress = cfg.source();
String destinationAddress = cfg.target();
int threads = cfg.workers();
boolean removeDeprecatedNodes = !cfg.copyOnly();
LOGGER.info("using " + threads + " concurrent workers to copy data");
Reader reader = new Reader(sourceAddress, threads);
Node root = reader.read();
if (root != null) {
Writer writer = new Writer(destinationAddress, root, removeDeprecatedNodes);
writer.write();
} else {
LOGGER.error("FAILED");
}
} | #vulnerable code
public static void main(String[] args)
{
String source = System.getProperty("source");
String destination = System.getProperty("destination");
if (source == null) {
help();
return;
}
int threads = getThreadsNumber();
boolean removeDeprecatedNodes = getRemoveDeprecatedNodes();
logger.info("Threads Number = " + threads);
Reader reader = new Reader(source, threads);
Node root = reader.read();
Writer writer = new Writer(destination, root, removeDeprecatedNodes);
writer.write();
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private List<ApiParamDoc> getQueryParamsFromSpringAnnotation(Method method, Class<?> controller) {
List<ApiParamDoc> apiParamDocs = new ArrayList<ApiParamDoc>();
if(controller.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = controller.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam != null) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
if(method.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
apiParamDocs.clear();
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam.length > 1) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
return apiParamDocs;
} | #vulnerable code
private List<ApiParamDoc> getQueryParamsFromSpringAnnotation(Method method, Class<?> controller) {
List<ApiParamDoc> apiParamDocs = new ArrayList<ApiParamDoc>();
if(controller.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = controller.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam != null) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
if(controller.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
apiParamDocs.clear();
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam.length > 1) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
return apiParamDocs;
}
#location 24
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("resource")
@Override
public CBORParser createParser(File f) throws IOException {
IOContext ctxt = _createContext(f, true);
return _createParser(_decorate(new FileInputStream(f), ctxt), ctxt);
} | #vulnerable code
@SuppressWarnings("resource")
@Override
public CBORParser createParser(File f) throws IOException {
return _createParser(new FileInputStream(f), _createContext(f, true));
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
// Note: may be null; if so, value needs to be skipped
if (f == null) {
return _skipUnknownField(id, wireType);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
} | #vulnerable code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if (_currentField != null) {
if ((f = _currentField.nextOrThisIf(id)) == null) {
if ((f = _currentMessage.field(id)) == null) {
return _skipUnknownField(id, wireType);
}
}
} else {
if ((f = _currentMessage.field(id)) == null) {
return _skipUnknownField(id, wireType);
}
}
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
// Note: may be null; if so, value needs to be skipped
if (f == null) {
return _skipUnknownField(id, wireType);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
} | #vulnerable code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testGarbageCollectorExports() {
assertEquals(
100L,
registry.getSampleValue(
"jvm_gc_collection_seconds_count",
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
10d,
registry.getSampleValue(
"jvm_gc_collection_seconds_sum",
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
200L,
registry.getSampleValue(
"jvm_gc_collection_seconds_count",
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
assertEquals(
20d,
registry.getSampleValue(
"jvm_gc_collection_seconds_sum",
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
} | #vulnerable code
@Test
public void testGarbageCollectorExports() {
assertEquals(
100L,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_COUNT_METRIC,
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
10d,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_TIME_METRIC,
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
200L,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_COUNT_METRIC,
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
assertEquals(
20d,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_TIME_METRIC,
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMemoryPools() {
assertEquals(
500000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_used",
new String[]{"pool"},
new String[]{"PS Eden Space"}),
.0000001);
assertEquals(
1000000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_committed",
new String[]{"pool"},
new String[]{"PS Eden Space"}),
.0000001);
assertEquals(
2000000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_max",
new String[]{"pool"},
new String[]{"PS Eden Space"}),
.0000001);
assertEquals(
10000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_used",
new String[]{"pool"},
new String[]{"PS Old Gen"}),
.0000001);
assertEquals(
20000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_committed",
new String[]{"pool"},
new String[]{"PS Old Gen"}),
.0000001);
assertEquals(
3000000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_max",
new String[]{"pool"},
new String[]{"PS Old Gen"}),
.0000001);
} | #vulnerable code
@Test
public void testMemoryPools() {
assertEquals(
500000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_USED_METRIC,
new String[]{"pool"},
new String[]{"PS-Eden-Space"}),
.0000001);
assertEquals(
1000000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_LIMIT_METRIC,
new String[]{"pool"},
new String[]{"PS-Eden-Space"}),
.0000001);
assertEquals(
10000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_USED_METRIC,
new String[]{"pool"},
new String[]{"PS-Old-Gen"}),
.0000001);
assertEquals(
20000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_LIMIT_METRIC,
new String[]{"pool"},
new String[]{"PS-Old-Gen"}),
.0000001);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void priceFormat() {
assertEquals("%7.2f ", FRACTIONS.get("FOO").getPriceFormat());
} | #vulnerable code
@Test
public void priceFormat() {
assertEquals("%7.2f ", INSTRUMENTS.get("FOO").getPriceFormat());
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(encodeLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
MoldUDP64.receive(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort), new PMDParser(processor));
} | #vulnerable code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(encodeLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
new PMDParser(processor));
transport.run();
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(encodeLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
new PMDParser(processor));
while (true)
transport.receive();
} | #vulnerable code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
MarketDataClient client = MarketDataClient.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
instruments, listener);
while (true)
client.receive();
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void priceFractionDigits() {
assertEquals(2, FRACTIONS.get("FOO").getPriceFractionDigits());
} | #vulnerable code
@Test
public void priceFractionDigits() {
assertEquals(2, INSTRUMENTS.get("FOO").getPriceFractionDigits());
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void main(Config config, boolean tsv) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "trade-report.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "trade-report.multicast-group");
int multicastPort = Configs.getPort(config, "trade-report.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "trade-report.request-address");
int requestPort = Configs.getPort(config, "trade-report.request-port");
MarketReportListener listener = tsv ? new TSVFormat() : new DisplayFormat();
MoldUDP64.receive(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort), new PMRParser(listener));
} | #vulnerable code
private static void main(Config config, boolean tsv) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "trade-report.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "trade-report.multicast-group");
int multicastPort = Configs.getPort(config, "trade-report.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "trade-report.request-address");
int requestPort = Configs.getPort(config, "trade-report.request-port");
MarketReportListener listener = tsv ? new TSVFormat() : new DisplayFormat();
MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
new PMRParser(listener));
transport.run();
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void listen(boolean taq, Config config) throws IOException {
Instruments instruments = Instruments.fromConfig(config, "instruments");
MarketDataListener listener = taq ? new TAQFormat(instruments) : new DisplayFormat(instruments);
Market market = new Market(listener);
for (Instrument instrument : instruments)
market.open(instrument.asLong());
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
} | #vulnerable code
private static void listen(boolean taq, Config config) throws IOException {
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(ASCII.packLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
}
#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 priceFactor() {
assertEquals(100.0, FRACTIONS.get("FOO").getPriceFactor(), 0.0);
} | #vulnerable code
@Test
public void priceFactor() {
assertEquals(100.0, INSTRUMENTS.get("FOO").getPriceFactor(), 0.0);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OrderBook(long instrument) {
this.instrument = instrument;
this.bids = new Long2LongRBTreeMap(BidComparator.INSTANCE);
this.asks = new Long2LongRBTreeMap(AskComparator.INSTANCE);
} | #vulnerable code
boolean add(Side side, long price, long quantity) {
Long2LongRBTreeMap levels = getLevels(side);
long size = levels.get(price);
levels.put(price, size + quantity);
return price == levels.firstLongKey();
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() throws IOException {
LineReader reader = LineReaderBuilder.builder()
.completer(new StringsCompleter(Commands.names().castToList()))
.build();
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
} | #vulnerable code
public void run() throws IOException {
ConsoleReader reader = new ConsoleReader();
reader.addCompleter(new StringsCompleter(Commands.names().castToList()));
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void listen(boolean taq, Config config) throws IOException {
Instruments instruments = Instruments.fromConfig(config, "instruments");
MarketDataListener listener = taq ? new TAQFormat(instruments) : new DisplayFormat(instruments);
Market market = new Market(listener);
for (Instrument instrument : instruments)
market.open(instrument.asLong());
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
} | #vulnerable code
private static void listen(boolean taq, Config config) throws IOException {
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(ASCII.packLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void add(long instrument, long orderId, Side side, long price, long size) {
if (orders.containsKey(orderId))
return;
OrderBook book = books.get(instrument);
if (book == null)
return;
Order order = new Order(book, side, price, size);
book.add(side, price, size);
orders.put(orderId, order);
if (order.isOnBestLevel())
book.bbo(listener);
} | #vulnerable code
public void add(long instrument, long orderId, Side side, long price, long size) {
if (orders.containsKey(orderId))
return;
OrderBook book = books.get(instrument);
if (book == null)
return;
Order order = book.add(side, price, size);
orders.put(orderId, order);
if (order.isOnBestLevel())
book.bbo(listener);
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() throws IOException {
LineReader reader = LineReaderBuilder.builder()
.completer(new StringsCompleter(Commands.names().castToList()))
.build();
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
} | #vulnerable code
public void run() throws IOException {
ConsoleReader reader = new ConsoleReader();
reader.addCompleter(new StringsCompleter(Commands.names().castToList()));
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OrderBook(long instrument) {
this.instrument = instrument;
this.bids = new Long2LongRBTreeMap(BidComparator.INSTANCE);
this.asks = new Long2LongRBTreeMap(AskComparator.INSTANCE);
} | #vulnerable code
boolean update(Side side, long price, long quantity) {
Long2LongRBTreeMap levels = getLevels(side);
long oldSize = levels.get(price);
long newSize = oldSize + quantity;
boolean onBestLevel = price == levels.firstLongKey();
if (newSize > 0)
levels.put(price, newSize);
else
levels.remove(price);
return onBestLevel;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void main(Config config) throws IOException {
MarketDataServer marketData = marketData(config);
MarketReportServer marketReport = marketReport(config);
List<String> instruments = config.getStringList("instruments");
MatchingEngine engine = new MatchingEngine(instruments, marketData, marketReport);
int orderEntryPort = Configs.getPort(config, "order-entry.port");
OrderEntryServer orderEntry = OrderEntryServer.create(orderEntryPort, engine);
marketData.version();
new Events(marketData, marketReport, orderEntry).run();
} | #vulnerable code
private static void main(Config config) throws IOException {
MarketDataServer marketData = marketData(config);
String marketReportSession = config.getString("market-report.session");
InetAddress marketReportMulticastGroup = Configs.getInetAddress(config, "market-report.multicast-group");
int marketReportMulticastPort = Configs.getPort(config, "market-report.multicast-port");
int marketReportRequestPort = Configs.getPort(config, "market-report.request-port");
MarketReportServer marketReport = MarketReportServer.create(marketReportSession,
new InetSocketAddress(marketReportMulticastGroup, marketReportMulticastPort),
marketReportRequestPort);
List<String> instruments = config.getStringList("instruments");
MatchingEngine engine = new MatchingEngine(instruments, marketData, marketReport);
int orderEntryPort = Configs.getPort(config, "order-entry.port");
OrderEntryServer orderEntry = OrderEntryServer.create(orderEntryPort, engine);
marketData.version();
new Events(marketData, marketReport, orderEntry).run();
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void run(ApplicationArguments args) throws Exception {
try {
// 测试 Redis连接是否正常
redisService.exists("febs_test");
} catch (Exception e) {
log.error(" ____ __ _ _ ");
log.error("| |_ / /\\ | | | |");
log.error("|_| /_/--\\ |_| |_|__");
log.error(" ");
log.error("FEBS启动失败,{}", e.getMessage());
log.error("Redis连接异常,请检查Redis连接配置并确保Redis服务已启动");
// 关闭 FEBS
context.close();
}
if (context.isActive()) {
InetAddress address = InetAddress.getLocalHost();
String url = String.format("http://%s:%s", address.getHostAddress(), port);
String loginUrl = febsProperties.getShiro().getLoginUrl();
if (StringUtils.isNotBlank(contextPath))
url += contextPath;
if (StringUtils.isNotBlank(loginUrl))
url += loginUrl;
log.info(" __ ___ _ ___ _ ____ _____ ____ ");
log.info("/ /` / / \\ | |\\/| | |_) | | | |_ | | | |_ ");
log.info("\\_\\_, \\_\\_/ |_| | |_| |_|__ |_|__ |_| |_|__ ");
log.info(" ");
log.info("FEBS 权限系统启动完毕,地址:{}", url);
boolean auto = febsProperties.isAutoOpenBrowser();
String[] autoEnv = febsProperties.getAutoOpenBrowserEnv();
if (auto && ArrayUtils.contains(autoEnv, active)) {
String os = System.getProperty("os.name");
// 默认为 windows时才自动打开页面
if (StringUtils.containsIgnoreCase(os, "windows")) {
//使用默认浏览器打开系统登录页
Runtime.getRuntime().exec("cmd /c start " + url);
}
}
}
} | #vulnerable code
@Override
public void run(ApplicationArguments args) throws Exception {
try {
// 测试 Redis连接是否正常
redisService.exists("febs_test");
} catch (Exception e) {
log.error(" ____ __ _ _ ");
log.error("| |_ / /\\ | | | |");
log.error("|_| /_/--\\ |_| |_|__");
log.error(" ");
log.error("FEBS启动失败,{}", e.getMessage());
log.error("Redis连接异常,请检查Redis连接配置并确保Redis服务已启动");
// 关闭 FEBS
context.close();
}
if (context.isActive()) {
InetAddress address = InetAddress.getLocalHost();
String url = String.format("http://%s:%s", address.getHostAddress(), port);
String loginUrl = febsProperties.getShiro().getLoginUrl();
if (StringUtils.isNotBlank(contextPath))
url += contextPath;
if (StringUtils.isNotBlank(loginUrl))
url += loginUrl;
log.info(" __ ___ _ ___ _ ____ _____ ____ ");
log.info("/ /` / / \\ | |\\/| | |_) | | | |_ | | | |_ ");
log.info("\\_\\_, \\_\\_/ |_| | |_| |_|__ |_|__ |_| |_|__ ");
log.info(" ");
log.info("FEBS 权限系统启动完毕,地址:{}", url);
boolean auto = febsProperties.isAutoOpenBrowser();
String[] autoEnv = febsProperties.getAutoOpenBrowserEnv();
int i = Arrays.binarySearch(autoEnv, active);
if (auto && i > 0) {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {// 默认为windows时才自动打开页面
//使用默认浏览器打开系统登录页
Runtime.getRuntime().exec("cmd /c start " + url);
}
}
}
}
#location 34
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private String[] extendArgs(String file, String oldargs[], int offset)
throws ArgumentParserException {
List<String> list = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
throw new ArgumentParserException(String.format(
"Could not read arguments from file '%s'", file), e, this);
} finally {
try {
if(reader != null) {
reader.close();
}
} catch(IOException e) {}
}
String newargs[] = new String[list.size() + oldargs.length - offset];
list.toArray(newargs);
System.arraycopy(oldargs, offset, newargs, list.size(), oldargs.length
- offset);
return newargs;
} | #vulnerable code
private String[] extendArgs(String file, String oldargs[], int offset)
throws ArgumentParserException {
List<String> list = new ArrayList<String>();
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
throw new ArgumentParserException(String.format(
"Could not read arguments from file '%s'", file), e, this);
}
String newargs[] = new String[list.size() + oldargs.length - offset];
list.toArray(newargs);
System.arraycopy(oldargs, offset, newargs, list.size(), oldargs.length
- offset);
return newargs;
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile());
}
File outFile = new File(getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
getLogger().log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
} | #vulnerable code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile());
}
File outFile = new File(getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
}
#location 33
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset()));
} | #vulnerable code
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
load(new FileInputStream(file));
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
return loadPlugin(file, false);
} | #vulnerable code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
JavaPlugin result = null;
PluginDescriptionFile description = null;
if (!file.exists()) {
throw new InvalidPluginException(new FileNotFoundException(String.format("%s does not exist", file.getPath())));
}
try {
JarFile jar = new JarFile(file);
JarEntry entry = jar.getJarEntry("plugin.yml");
if (entry == null) {
throw new InvalidPluginException(new FileNotFoundException("Jar does not contain plugin.yml"));
}
InputStream stream = jar.getInputStream(entry);
description = new PluginDescriptionFile(stream);
stream.close();
jar.close();
} catch (IOException ex) {
throw new InvalidPluginException(ex);
} catch (YAMLException ex) {
throw new InvalidPluginException(ex);
}
File dataFolder = new File(file.getParentFile(), description.getName());
File oldDataFolder = getDataFolder(file);
// Found old data folder
if (dataFolder.equals(oldDataFolder)) {
// They are equal -- nothing needs to be done!
} else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) {
server.getLogger().log( Level.INFO, String.format(
"While loading %s (%s) found old-data folder: %s next to the new one: %s",
description.getName(),
file,
oldDataFolder,
dataFolder
));
} else if (oldDataFolder.isDirectory() && !dataFolder.exists()) {
if (!oldDataFolder.renameTo(dataFolder)) {
throw new InvalidPluginException(new Exception("Unable to rename old data folder: '" + oldDataFolder + "' to: '" + dataFolder + "'"));
}
server.getLogger().log( Level.INFO, String.format(
"While loading %s (%s) renamed data folder: '%s' to '%s'",
description.getName(),
file,
oldDataFolder,
dataFolder
));
}
if (dataFolder.exists() && !dataFolder.isDirectory()) {
throw new InvalidPluginException(new Exception(String.format(
"Projected datafolder: '%s' for %s (%s) exists and is not a directory",
dataFolder,
description.getName(),
file
)));
}
ArrayList<String> depend;
try {
depend = (ArrayList)description.getDepend();
if(depend == null) {
depend = new ArrayList<String>();
}
} catch (ClassCastException ex) {
throw new InvalidPluginException(ex);
}
for(String pluginName : depend) {
if(loaders == null) {
throw new UnknownDependencyException(pluginName);
}
PluginClassLoader current = loaders.get(pluginName);
if(current == null) {
throw new UnknownDependencyException(pluginName);
}
}
PluginClassLoader loader = null;
try {
URL[] urls = new URL[1];
urls[0] = file.toURI().toURL();
loader = new PluginClassLoader(this, urls, getClass().getClassLoader());
Class<?> jarClass = Class.forName(description.getMain(), true, loader);
Class<? extends JavaPlugin> plugin = jarClass.asSubclass(JavaPlugin.class);
Constructor<? extends JavaPlugin> constructor = plugin.getConstructor();
result = constructor.newInstance();
result.initialize(this, server, description, dataFolder, file, loader);
} catch (Throwable ex) {
throw new InvalidPluginException(ex);
}
loaders.put(description.getName(), (PluginClassLoader)loader);
return (Plugin)result;
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
Player player;
if (args.length == 1 || args.length == 3) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage("Please provide a player!");
return true;
}
} else {
player = Bukkit.getPlayerExact(args[0]);
}
if (player == null) {
sender.sendMessage("Player not found: " + args[0]);
return true;
}
if (args.length < 3) {
Player target = Bukkit.getPlayerExact(args[args.length - 1]);
if (target == null) {
sender.sendMessage("Can't find user " + args[args.length - 1] + ". No tp.");
return true;
}
player.teleport(target, TeleportCause.COMMAND);
Command.broadcastCommandMessage(sender, "Teleported " + player.getName() + " to " + target.getName());
} else if (player.getWorld() != null) {
int x = getInteger(sender, args[args.length - 3], -30000000, 30000000);
int y = getInteger(sender, args[args.length - 2], 0, 256);
int z = getInteger(sender, args[args.length - 1], -30000000, 30000000);
Location location = new Location(player.getWorld(), x, y, z);
player.teleport(location);
Command.broadcastCommandMessage(sender, "Teleported " + player.getName() + " to " + + x + "," + y + "," + z);
}
return true;
} | #vulnerable code
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
Player player;
if (args.length == 1 || args.length == 3) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage("Please provide a player!");
return true;
}
} else {
player = Bukkit.getPlayerExact(args[0]);
}
if (player == null) {
sender.sendMessage("Player not found: " + args[0]);
}
if (args.length < 3) {
Player target = Bukkit.getPlayerExact(args[args.length - 1]);
if (target == null) {
sender.sendMessage("Can't find user " + args[args.length - 1] + ". No tp.");
}
player.teleport(target, TeleportCause.COMMAND);
sender.sendMessage("Teleported " + player.getName() + " to " + target.getName());
} else if (player.getWorld() != null) {
int x = getInteger(sender, args[args.length - 3], -30000000, 30000000);
int y = getInteger(sender, args[args.length - 2], 0, 256);
int z = getInteger(sender, args[args.length - 1], -30000000, 30000000);
Location location = new Location(player.getWorld(), x, y, z);
player.teleport(location);
sender.sendMessage("Teleported " + player.getName() + " to " + x + "," + y + "," + z);
}
return true;
}
#location 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void recalculatePermissions() {
clearPermissions();
Set<Permission> defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp());
Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent);
for (Permission perm : defaults) {
String name = perm.getName().toLowerCase();
permissions.put(name, new PermissionAttachmentInfo(parent, name, null, true));
Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent);
calculateChildPermissions(perm.getChildren(), false, null);
}
for (PermissionAttachment attachment : attachments) {
calculateChildPermissions(attachment.getPermissions(), false, attachment);
}
} | #vulnerable code
public void recalculatePermissions() {
dirtyPermissions = true;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | #vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
int shared_cache(boolean enable) throws SQLException
{
// The shared cache is per-process, so it is useless as
// each nested connection is its own process.
return -1;
} | #vulnerable code
int enable_load_extension(boolean enable) throws SQLException
{
return call("sqlite3_enable_load_extension", handle, enable ? 1 : 0);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void setMaxRows(int max) throws SQLException {
//checkOpen();
if (max < 0)
throw new SQLException("max row count must be >= 0");
rs.maxRows = max;
} | #vulnerable code
public void setMaxRows(int max) throws SQLException {
checkOpen();
if (max < 0)
throw new SQLException("max row count must be >= 0");
rs.maxRows = max;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = String.format("sqlite-%s-", getVersion());
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
} | #vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = "sqlite-3.6.4-";
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | #vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int getMaxRows() throws SQLException {
//checkOpen();
return rs.maxRows;
} | #vulnerable code
public int getMaxRows() throws SQLException {
checkOpen();
return rs.maxRows;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | #vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
if(!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
}
finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
}
finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
} | #vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
}
finally {
if(!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
}
finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
}
#location 66
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void basicBusyHandler() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// let busyWork block inside insert
busyWork.lockedLatch.await();
try{
workWork();
fail("Should throw SQLITE_BUSY exception");
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
busyWork.completeLatch.countDown();
busyWork.join();
assertEquals(3, calls[0]);
} | #vulnerable code
@Test
public void basicBusyHandler() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// I let busyWork prepare a huge insert
Thread.sleep(1000);
synchronized(busyWork){
try{
workWork();
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
}
busyWork.interrupt();
assertEquals(3, calls[0]);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
if (!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
} | #vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
}
#location 43
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Map<String,Class<?>> getTypeMap() throws SQLException {
synchronized (this) {
if (this.typeMap == null) {
this.typeMap = new HashMap<String, Class<?>>();
}
return this.typeMap;
}
} | #vulnerable code
public Map<String,Class<?>> getTypeMap() throws SQLException {
synchronized (typeMap) {
if (this.typeMap == null) {
this.typeMap = new HashMap<String, Class<?>>();
}
return this.typeMap;
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testUnregister() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// let busyWork block inside insert
busyWork.lockedLatch.await();
try{
workWork();
fail("Should throw SQLITE_BUSY exception");
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
busyWork.completeLatch.countDown();
busyWork.join();
assertEquals(3, calls[0]);
int totalCalls = calls[0];
BusyHandler.clearHandler(conn);
busyWork = new BusyWork();
busyWork.start();
// let busyWork block inside insert
busyWork.lockedLatch.await();
try{
workWork();
fail("Should throw SQLITE_BUSY exception");
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
busyWork.completeLatch.countDown();
busyWork.join();
assertEquals(totalCalls, calls[0]);
} | #vulnerable code
@Test
public void testUnregister() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// I let busyWork prepare a huge insert
Thread.sleep(1000);
synchronized(busyWork){
try{
workWork();
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
}
assertEquals(3, calls[0]);
int totalCalls = calls[0];
BusyHandler.clearHandler(conn);
busyWork = new BusyWork();
busyWork.start();
// I let busyWork prepare a huge insert
Thread.sleep(1000);
synchronized(busyWork){
try{
workWork();
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
}
busyWork.interrupt();
assertEquals(totalCalls, calls[0]);
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | #vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean execute(String sql) throws SQLException {
internalClose();
SQLExtension ext = ExtendedCommand.parse(sql);
if (ext != null) {
ext.execute(db);
return false;
}
this.sql = sql;
db.prepare(this);
return exec();
} | #vulnerable code
public boolean execute(String sql) throws SQLException {
internalClose();
SQLExtension ext = ExtendedCommand.parse(sql);
if (ext != null) {
ext.execute(db);
return false;
}
this.sql = sql;
boolean success = false;
try {
db.prepare(this);
final boolean result = exec();
success = true;
return result;
} finally {
if (!success) {
internalClose();
}
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void setTypeMap(Map map) throws SQLException {
synchronized (this) {
this.typeMap = map;
}
} | #vulnerable code
public void setTypeMap(Map map) throws SQLException {
synchronized (typeMap) {
this.typeMap = map;
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
if (!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
} | #vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
}
#location 56
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = String.format("sqlite-%s-", getVersion());
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
} | #vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = "sqlite-3.6.4-";
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
}
#location 52
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@GetMapping()
public String profile(ModelMap mmap)
{
SysUser user = getSysUser();
user.setSex(dictDataService.selectDictLabel("sys_user_sex", user.getSex()));
mmap.put("user", user);
mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
return prefix + "/profile";
} | #vulnerable code
@GetMapping()
public String profile(ModelMap mmap)
{
SysUser user = getUser();
user.setSex(dictDataService.selectDictLabel("sys_user_sex", user.getSex()));
mmap.put("user", user);
mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
return prefix + "/profile";
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getSysUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
} | #vulnerable code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Async
protected void handleLog(final JoinPoint joinPoint, final Exception e)
{
try
{
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
// 获取当前的用户
User currentUser = ShiroUtils.getUser();
// *========数据库日志=========*//
OperLog operLog = new OperLog();
operLog.setStatus(BusinessStatus.SUCCESS);
// 请求的地址
String ip = ShiroUtils.getIp();
operLog.setOperIp(ip);
// 操作地点
operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip));
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (currentUser != null)
{
operLog.setOperName(currentUser.getLoginName());
if (StringUtils.isNotNull(currentUser.getDept())
&& StringUtils.isEmpty(currentUser.getDept().getDeptName()))
{
operLog.setDeptName(currentUser.getDept().getDeptName());
}
}
if (e != null)
{
operLog.setStatus(BusinessStatus.FAIL);
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 处理设置注解上的参数
getControllerMethodDescription(controllerLog, operLog);
// 保存数据库
operLogService.insertOperlog(operLog);
}
catch (Exception exp)
{
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
} | #vulnerable code
@Async
protected void handleLog(final JoinPoint joinPoint, final Exception e)
{
try
{
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
// 获取当前的用户
User currentUser = ShiroUtils.getUser();
// *========数据库日志=========*//
OperLog operLog = new OperLog();
operLog.setStatus(BusinessStatus.SUCCESS);
// 请求的地址
String ip = ShiroUtils.getIp();
operLog.setOperIp(ip);
// 操作地点
operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip));
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (currentUser != null)
{
operLog.setOperName(currentUser.getLoginName());
operLog.setDeptName(currentUser.getDept().getDeptName());
}
if (e != null)
{
operLog.setStatus(BusinessStatus.FAIL);
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 处理设置注解上的参数
getControllerMethodDescription(controllerLog, operLog);
// 保存数据库
operLogService.insertOperlog(operLog);
}
catch (Exception exp)
{
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
#location 29
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getSysUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
} | #vulnerable code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String getLoginName()
{
return getSysUser().getLoginName();
} | #vulnerable code
public static String getLoginName()
{
return getUser().getLoginName();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getLoginName()
{
return getSysUser().getLoginName();
} | #vulnerable code
public String getLoginName()
{
return getUser().getLoginName();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Long getUserId()
{
return getSysUser().getUserId().longValue();
} | #vulnerable code
public static Long getUserId()
{
return getUser().getUserId().longValue();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Long getUserId()
{
return getSysUser().getUserId();
} | #vulnerable code
public Long getUserId()
{
return getUser().getUserId();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public List<T> importExcel(String sheetName, InputStream input) throws Exception
{
List<T> list = new ArrayList<T>();
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = null;
if (StringUtils.isNotEmpty(sheetName))
{
// 如果指定sheet名,则取指定sheet中的内容.
sheet = workbook.getSheet(sheetName);
}
else
{
// 如果传入的sheet名不存在则默认指向第1个sheet.
sheet = workbook.getSheetAt(0);
}
if (sheet == null)
{
throw new IOException("文件sheet不存在");
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0)
{
// 默认序号
int serialNum = 0;
// 有数据时才处理 得到类的所有field.
Field[] allFields = clazz.getDeclaredFields();
// 定义一个map用于存放列的序号和field.
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int col = 0; col < allFields.length; col++)
{
Field field = allFields[col];
// 将有注解的field存放到map中.
if (field.isAnnotationPresent(Excel.class))
{
// 设置类的私有字段属性可访问.
field.setAccessible(true);
fieldsMap.put(++serialNum, field);
}
}
for (int i = 1; i < rows; i++)
{
// 从第2行开始取数据,默认第一行是表头.
Row row = sheet.getRow(i);
int cellNum = serialNum;
T entity = null;
for (int j = 0; j < cellNum; j++)
{
Cell cell = row.getCell(j);
if (cell == null)
{
continue;
}
else
{
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
row.getCell(j).setCellType(CellType.STRING);
cell = row.getCell(j);
}
String c = cell.getStringCellValue();
if (StringUtils.isEmpty(c))
{
continue;
}
// 如果不存在实例则新建.
entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field.
Field field = fieldsMap.get(j + 1);
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType)
{
field.set(entity, String.valueOf(c));
}
else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
{
field.set(entity, Integer.parseInt(c));
}
else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
{
field.set(entity, Long.valueOf(c));
}
else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
{
field.set(entity, Float.valueOf(c));
}
else if ((Short.TYPE == fieldType) || (Short.class == fieldType))
{
field.set(entity, Short.valueOf(c));
}
else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
{
field.set(entity, Double.valueOf(c));
}
else if (Character.TYPE == fieldType)
{
if ((c != null) && (c.length() > 0))
{
field.set(entity, Character.valueOf(c.charAt(0)));
}
}
else if (java.util.Date.class == fieldType)
{
if (cell.getCellTypeEnum() == CellType.NUMERIC)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell.setCellValue(sdf.format(cell.getNumericCellValue()));
c = sdf.format(cell.getNumericCellValue());
}
else
{
c = cell.getStringCellValue();
}
}
else if (java.math.BigDecimal.class == fieldType)
{
c = cell.getStringCellValue();
}
}
if (entity != null)
{
list.add(entity);
}
}
}
return list;
} | #vulnerable code
public List<T> importExcel(String sheetName, InputStream input) throws Exception
{
List<T> list = new ArrayList<T>();
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = null;
if (StringUtils.isNotEmpty(sheetName))
{
// 如果指定sheet名,则取指定sheet中的内容.
sheet = workbook.getSheet(sheetName);
}
else
{
// 如果传入的sheet名不存在则默认指向第1个sheet.
sheet = workbook.getSheetAt(0);
}
if (sheet == null)
{
throw new IOException("文件sheet不存在");
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0)
{
// 有数据时才处理 得到类的所有field.
Field[] allFields = clazz.getDeclaredFields();
// 定义一个map用于存放列的序号和field.
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int col = 0; col < allFields.length; col++)
{
Field field = allFields[col];
// 将有注解的field存放到map中.
if (field.isAnnotationPresent(Excel.class))
{
// 设置类的私有字段属性可访问.
field.setAccessible(true);
fieldsMap.put(col, field);
}
}
for (int i = 1; i < rows; i++)
{
// 从第2行开始取数据,默认第一行是表头.
Row row = sheet.getRow(i);
int cellNum = sheet.getRow(0).getPhysicalNumberOfCells();
T entity = null;
for (int j = 0; j < cellNum; j++)
{
Cell cell = row.getCell(j);
if (cell == null)
{
continue;
}
else
{
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
cell = row.getCell(j);
}
String c = cell.getStringCellValue();
if (StringUtils.isEmpty(c))
{
continue;
}
// 如果不存在实例则新建.
entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field.
Field field = fieldsMap.get(j + 1);
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType)
{
field.set(entity, String.valueOf(c));
}
else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
{
field.set(entity, Integer.parseInt(c));
}
else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
{
field.set(entity, Long.valueOf(c));
}
else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
{
field.set(entity, Float.valueOf(c));
}
else if ((Short.TYPE == fieldType) || (Short.class == fieldType))
{
field.set(entity, Short.valueOf(c));
}
else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
{
field.set(entity, Double.valueOf(c));
}
else if (Character.TYPE == fieldType)
{
if ((c != null) && (c.length() > 0))
{
field.set(entity, Character.valueOf(c.charAt(0)));
}
}
else if (java.util.Date.class == fieldType)
{
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell.setCellValue(sdf.format(cell.getNumericCellValue()));
c = sdf.format(cell.getNumericCellValue());
}
else
{
c = cell.getStringCellValue();
}
}
else if (java.math.BigDecimal.class == fieldType)
{
c = cell.getStringCellValue();
}
}
if (entity != null)
{
list.add(entity);
}
}
}
return list;
}
#location 73
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void clearState() {
setConnection(null);
activeSenders.clear();
activeRequestResponseClients.clear();
failAllCreationRequests();
// make sure we make configured number of attempts to re-connect
connectAttempts = new AtomicInteger(0);
} | #vulnerable code
protected void clearState() {
setConnection(null);
offeredCapabilities = Collections.emptyList();
activeSenders.clear();
activeRequestResponseClients.clear();
failAllCreationRequests();
// make sure we make configured number of attempts to re-connect
connectAttempts = new AtomicInteger(0);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void onClose(final MqttEndpoint endpoint) {
} | #vulnerable code
protected void onClose(final MqttEndpoint endpoint) {
metrics.decrementMqttConnections(getCredentials(endpoint.auth()).getTenantId());
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a telemetry sender for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async disconnected = ctx.async();
client.getOrCreateSender(
"telemetry/tenant",
() -> Future.future(),
ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await();
} | #vulnerable code
@Test
public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a telemetry sender for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
final Async disconnected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
client.getOrCreateSender("telemetry/tenant", creationResultHandler -> {
ctx.assertFalse(disconnected.isCompleted());
}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void sendRegistrationData(final ProtonDelivery delivery, final Message msg) {
vertx.runOnContext(run -> {
final JsonObject registrationMsg = RegistrationConstants.getRegistrationMsg(msg);
vertx.eventBus().send(EVENT_BUS_ADDRESS_REGISTRATION_IN, registrationMsg,
result -> {
// TODO check for correct session here...?
final String replyTo = msg.getReplyTo();
if (replyTo != null) {
final JsonObject message = (JsonObject) result.result().body();
message.put(APP_PROPERTY_CORRELATION_ID, createCorrelationId(msg));
vertx.eventBus().send(replyTo, message);
} else {
LOG.debug("No reply-to address provided, cannot send reply to client.");
}
});
ProtonHelper.accepted(delivery, true);
});
} | #vulnerable code
private void sendRegistrationData(final ProtonDelivery delivery, final Message msg) {
final ResourceIdentifier messageAddress = ResourceIdentifier.fromString(
MessageHelper.getAnnotation(msg, APP_PROPERTY_RESOURCE_ID));
checkPermission(messageAddress, permissionGranted -> {
if (permissionGranted) {
vertx.runOnContext(run -> {
final JsonObject registrationMsg = RegistrationConstants.getRegistrationMsg(msg);
vertx.eventBus().send(EVENT_BUS_ADDRESS_REGISTRATION_IN, registrationMsg,
result -> {
// TODO check for correct session here...?
final String replyTo = msg.getReplyTo();
if (replyTo != null) {
final JsonObject message = (JsonObject) result.result().body();
message.put(APP_PROPERTY_CORRELATION_ID, createCorrelationId(msg));
vertx.eventBus().send(replyTo, message);
} else {
LOG.debug("No reply-to address provided, cannot send reply to client.");
}
});
ProtonHelper.accepted(delivery, true);
});
} else {
LOG.debug("client is not authorized to register devices at [{}]", messageAddress);
MessageHelper.rejected(delivery, UNAUTHORIZED_ACCESS.toString(),
"client is not authorized to register devices at " + messageAddress);
}
});
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Optional<TimeUntilDisconnectNotification> fromMessage(final Message msg) {
final Integer ttd = MessageHelper.getTimeUntilDisconnect(msg);
if (ttd == null) {
return Optional.empty();
} else if (ttd == 0 || MessageHelper.isDeviceCurrentlyConnected(msg)) {
final String tenantId = MessageHelper.getTenantIdAnnotation(msg);
final String deviceId = MessageHelper.getDeviceId(msg);
if (tenantId != null && deviceId != null) {
final Instant creationTime = Instant.ofEpochMilli(msg.getCreationTime());
final TimeUntilDisconnectNotification notification =
new TimeUntilDisconnectNotification(tenantId, deviceId, getReadyUntilInstantFromTtd(ttd, creationTime));
return Optional.of(notification);
}
}
return Optional.empty();
} | #vulnerable code
public static Optional<TimeUntilDisconnectNotification> fromMessage(final Message msg) {
if (MessageHelper.isDeviceCurrentlyConnected(msg)) {
final String tenantId = MessageHelper.getTenantIdAnnotation(msg);
final String deviceId = MessageHelper.getDeviceId(msg);
if (tenantId != null && deviceId != null) {
final Integer ttd = MessageHelper.getTimeUntilDisconnect(msg);
final Instant creationTime = Instant.ofEpochMilli(msg.getCreationTime());
final TimeUntilDisconnectNotification notification =
new TimeUntilDisconnectNotification(tenantId, deviceId, getReadyUntilInstantFromTtd(ttd, creationTime));
return Optional.of(notification);
}
}
return Optional.empty();
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testGetOrCreateRequestResponseClientFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a registration client for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async creationFailure = ctx.async();
client.getOrCreateRequestResponseClient(
"registration/tenant",
() -> {
ctx.assertFalse(creationFailure.isCompleted());
return Future.future();
},
ctx.asyncAssertFailure(cause -> creationFailure.complete()));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
creationFailure.await();
} | #vulnerable code
@Test
public void testGetOrCreateRequestResponseClientFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a registration client for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
final Async disconnected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
client.getOrCreateRequestResponseClient("registration/tenant", creationResultHandler -> {
ctx.assertFalse(disconnected.isCompleted());
}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private R getRequestResponseResult(final Message message) {
final Integer status = MessageHelper.getApplicationProperty(
message.getApplicationProperties(),
MessageHelper.APP_PROPERTY_STATUS,
Integer.class);
if (status == null) {
return null;
} else {
final String payload = MessageHelper.getPayload(message);
final CacheDirective cacheDirective = CacheDirective.from(MessageHelper.getCacheDirective(message));
return getResult(status, payload, cacheDirective);
}
} | #vulnerable code
private R getRequestResponseResult(final Message message) {
final Integer status = MessageHelper.getApplicationProperty(
message.getApplicationProperties(),
MessageHelper.APP_PROPERTY_STATUS,
Integer.class);
final String payload = MessageHelper.getPayload(message);
final CacheDirective cacheDirective = CacheDirective.from(MessageHelper.getCacheDirective(message));
return getResult(status, payload, cacheDirective);
}
#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 testCreateEventConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async disconnected = ctx.async();
client.createEventConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await();
} | #vulnerable code
@Test
public void testCreateEventConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
final Async disconnected = ctx.async();
client.createEventConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testConnectTriesToReconnectOnFailedConnectAttempt(final TestContext ctx) {
// GIVEN a client that cannot connect to the server
// expect the connection factory to fail twice and succeed on third connect attempt
connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 1, 2);
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
// WHEN trying to connect
Async disconnectHandlerInvocation = ctx.async();
Async connectionEstablished = ctx.async();
client.connect(
new ProtonClientOptions().setReconnectAttempts(1),
ctx.asyncAssertSuccess(ok -> connectionEstablished.complete()),
failedCon -> disconnectHandlerInvocation.complete());
// THEN the client repeatedly tries to connect
connectionEstablished.await(4 * Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
// and sets the disconnect handler provided as a param in the connect method invocation
connectionFactory.getDisconnectHandler().handle(con);
disconnectHandlerInvocation.await();
} | #vulnerable code
@Test
public void testConnectTriesToReconnectOnFailedConnectAttempt(final TestContext ctx) {
// GIVEN a client that cannot connect to the server
ProtonConnection con = mock(ProtonConnection.class);
// expect the connection factory to fail twice and succeed on third connect attempt
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 1, 2);
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
// WHEN trying to connect
Async disconnectHandlerInvocation = ctx.async();
Async connectionEstablished = ctx.async();
Handler<ProtonConnection> disconnectHandler = failedCon -> disconnectHandlerInvocation.complete();
client.connect(
new ProtonClientOptions().setReconnectAttempts(1),
ctx.asyncAssertSuccess(ok -> connectionEstablished.complete()),
disconnectHandler);
// THEN the client repeatedly tries to connect
connectionEstablished.await(4 * Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
// and sets the disconnect handler provided as a param in the connect method invocation
connectionFactory.getDisconnectHandler().handle(con);
disconnectHandlerInvocation.await(1000);
}
#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 testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async disconnected = ctx.async();
client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await();
} | #vulnerable code
@Test
public void testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
final Async disconnected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testDownstreamDisconnectTriggersReconnect(final TestContext ctx) {
// expect the connection factory to be invoked twice
// first on initial connection
// second on re-connect attempt
connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 2);
// GIVEN an client connected to a server
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions().setReconnectAttempts(1), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
// WHEN the downstream connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN the adapter reconnects to the downstream container
connectionFactory.await(1, TimeUnit.SECONDS);
} | #vulnerable code
@Test
public void testDownstreamDisconnectTriggersReconnect(final TestContext ctx) {
final ProtonConnection connectionToCreate = mock(ProtonConnection.class);
when(connectionToCreate.getRemoteContainer()).thenReturn("server");
// expect the connection factory to be invoked twice
// first on initial connection
// second on re-connect attempt
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(connectionToCreate, 2);
// GIVEN an client connected to a server
final Async connected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions().setReconnectAttempts(1), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
// WHEN the downstream connection fails
connectionFactory.getDisconnectHandler().handle(connectionToCreate);
// THEN the adapter tries to reconnect to the downstream container
connectionFactory.await(1, TimeUnit.SECONDS);
}
#location 18
#vulnerability type NULL_DEREFERENCE | 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.