input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override public List<BxDocument> getDocuments() throws TransformationException { List<BxDocument> documents = new ArrayList<BxDocument>(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().endsWith("xml")) { try { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry))); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); documents.add(newDoc); } catch (IOException ex) { throw new TransformationException("Cannot read file!", ex); } } } return documents; } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Override public List<BxDocument> getDocuments() throws TransformationException { List<BxDocument> documents = new ArrayList<BxDocument>(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().endsWith("xml")) { try { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); documents.add(newDoc); } catch (IOException ex) { throw new TransformationException("Cannot read file!", ex); } } } return documents; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath))); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath))); } loadModelFromFile(modelFile, rangeFile); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8")); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8")); } loadModelFromFile(modelFile, rangeFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws JDOMException, IOException, AnalysisException { if (args.length != 3) { System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>"); System.exit(1); } int foldness = Integer.parseInt(args[0]); String modelPathSuffix = args[1]; String testPathSuffix = args[2]; Map<String, List<Result>> results = new HashMap<String, List<Result>>(); for (int i = 0; i < foldness; i++) { System.out.println("Fold "+i); String modelPath = modelPathSuffix + i; CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath); String testPath = testPathSuffix + i; File testFile = new File(testPath); List<Citation> testCitations; InputStream testIS = null; try { testIS = new FileInputStream(testFile); InputSource testSource = new InputSource(testIS); testCitations = NlmCitationExtractor.extractCitations(testSource); } finally { if (testIS != null) { testIS.close(); } } System.out.println(testCitations.size()); List<BibEntry> testEntries = new ArrayList<BibEntry>(); for (Citation c : testCitations) { BibEntry entry = CitationUtils.citationToBibref(c); testEntries.add(entry); for (String key : entry.getFieldKeys()) { if (results.get(key) == null) { results.put(key, new ArrayList<Result>()); } } } int j = 0; for (BibEntry orig : testEntries) { BibEntry test = parser.parseBibReference(orig.getText()); System.out.println(); System.out.println(); System.out.println(orig.toBibTeX()); System.out.println(test.toBibTeX()); Map<String, Result> map = new HashMap<String, Result>(); for (String s : orig.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addOrig(orig.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addExtr(test.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { List<String> origVals = orig.getAllFieldValues(s); for (String testVal : test.getAllFieldValues(s)) { boolean found = false; if (origVals.contains(testVal)) { map.get(s).addSuccess(); origVals.remove(testVal); found = true; } if (!found) { System.out.println("WRONG "+s); } } } for (Map.Entry<String, Result> s : map.entrySet()) { System.out.println(""); System.out.println(s.getKey()); System.out.println(s.getValue()); System.out.println(s.getValue().getPrecision()); System.out.println(s.getValue().getRecall()); results.get(s.getKey()).add(s.getValue()); } j++; System.out.println("Tested "+j+" out of "+testEntries.size()); } } for (String s : results.keySet()) { System.out.println(""); System.out.println(s); System.out.println(results.get(s).size()); double precision = 0; int precisionCount = 0; double recall = 0; int recallCount = 0; for (Result r : results.get(s)) { if (r.getPrecision() != null) { precision += r.getPrecision(); precisionCount++; } if (r.getRecall() != null) { recall += r.getRecall(); recallCount++; } } System.out.println("Precision count "+precisionCount); System.out.println("Mean precision "+(precision / precisionCount)); System.out.println("Recall count "+recallCount); System.out.println("Mean recall "+(recall / recallCount)); } } #location 103 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws JDOMException, IOException, AnalysisException { if (args.length != 3) { System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>"); System.exit(1); } int foldness = Integer.parseInt(args[0]); String modelPathSuffix = args[1]; String testPathSuffix = args[2]; Map<String, List<Result>> results = new HashMap<String, List<Result>>(); for (int i = 0; i < foldness; i++) { System.out.println("Fold "+i); String modelPath = modelPathSuffix + i; CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath); String testPath = testPathSuffix + i; File testFile = new File(testPath); List<Citation> testCitations; InputStream testIS = null; try { testIS = new FileInputStream(testFile); InputSource testSource = new InputSource(testIS); testCitations = NlmCitationExtractor.extractCitations(testSource); } finally { if (testIS != null) { testIS.close(); } } System.out.println(testCitations.size()); List<BibEntry> testEntries = new ArrayList<BibEntry>(); for (Citation c : testCitations) { BibEntry entry = CitationUtils.citationToBibref(c); testEntries.add(entry); for (String key : entry.getFieldKeys()) { if (results.get(key) == null) { results.put(key, new ArrayList<Result>()); } } } int j = 0; for (BibEntry orig : testEntries) { BibEntry test = parser.parseBibReference(orig.getText()); System.out.println(); System.out.println(); System.out.println(orig.toBibTeX()); System.out.println(test.toBibTeX()); Map<String, Result> map = new HashMap<String, Result>(); for (String s : orig.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addOrig(orig.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addExtr(test.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { List<String> origVals = orig.getAllFieldValues(s); for (String testVal : test.getAllFieldValues(s)) { boolean found = false; if (origVals.contains(testVal)) { map.get(s).addSuccess(); origVals.remove(testVal); found = true; } if (!found) { System.out.println("WRONG "+s); } } } for (Map.Entry<String, Result> s : map.entrySet()) { System.out.println(""); System.out.println(s.getKey()); System.out.println(s.getValue()); System.out.println(s.getValue().getPrecision()); System.out.println(s.getValue().getRecall()); results.get(s.getKey()).add(s.getValue()); } j++; System.out.println("Tested "+j+" out of "+testEntries.size()); } } for (Map.Entry<String, List<Result>> e : results.entrySet()) { System.out.println(""); System.out.println(e.getKey()); System.out.println(e.getValue().size()); double precision = 0; int precisionCount = 0; double recall = 0; int recallCount = 0; for (Result r : e.getValue()) { if (r.getPrecision() != null) { precision += r.getPrecision(); precisionCount++; } if (r.getRecall() != null) { recall += r.getRecall(); recallCount++; } } System.out.println("Precision count "+precisionCount); System.out.println("Mean precision "+(precision / precisionCount)); System.out.println("Recall count "+recallCount); System.out.println("Mean recall "+(recall / recallCount)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void deepCloneTest() throws TransformationException { InputStream stream = BxModelUtilsTest.class.getResourceAsStream(EXP_STR_LAB_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument doc = new BxDocument().setPages(reader.read(new InputStreamReader(stream))); BxDocument copy = BxModelUtils.deepClone(doc); assertFalse(doc == copy); assertTrue(BxModelUtils.areEqual(doc, copy)); Stack<BxPage> pages = new Stack<BxPage>(); Stack<BxZone> zones = new Stack<BxZone>(); Stack<BxLine> lines = new Stack<BxLine>(); Stack<BxWord> words = new Stack<BxWord>(); Stack<BxChunk> chunks = new Stack<BxChunk>(); for (BxPage page : copy) { assertTrue(page.getParent() == copy); for (BxZone zone : page) { assertTrue(zone.getParent() == page); for (BxLine line : zone) { assertTrue(line.getParent() == zone); for (BxWord word : line) { assertTrue(word.getParent() == line); for (BxChunk chunk : word) { assertTrue(chunk.getParent() == word); } } } } } BxPage page = copy.getFirstChild(); while (page != null) { pages.push(page); page = page.getNext(); } page = pages.peek(); BxZone zone = copy.getFirstChild().getFirstChild(); while (zone != null) { zones.push(zone); zone = zone.getNext(); } zone = zones.peek(); BxLine line = copy.getFirstChild().getFirstChild().getFirstChild(); while (line != null) { lines.push(line); line = line.getNext(); } line = lines.peek(); BxWord word = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (word != null) { words.push(word); word = word.getNext(); } word = words.peek(); BxChunk chunk = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (chunk != null) { chunks.push(chunk); chunk = chunk.getNext(); } chunk = chunks.peek(); while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); while (page != null) { pages.push(page); page = page.getPrev(); } while (zone != null) { zones.push(zone); zone = zone.getPrev(); } while (line != null) { lines.push(line); line = line.getPrev(); } while (word != null) { words.push(word); word = word.getPrev(); } while (chunk != null) { chunks.push(chunk); chunk = chunk.getPrev(); } while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void deepCloneTest() throws TransformationException, UnsupportedEncodingException { InputStream stream = BxModelUtilsTest.class.getResourceAsStream(EXP_STR_LAB_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument doc = new BxDocument().setPages(reader.read(new InputStreamReader(stream, "UTF-8"))); BxDocument copy = BxModelUtils.deepClone(doc); assertFalse(doc == copy); assertTrue(BxModelUtils.areEqual(doc, copy)); Stack<BxPage> pages = new Stack<BxPage>(); Stack<BxZone> zones = new Stack<BxZone>(); Stack<BxLine> lines = new Stack<BxLine>(); Stack<BxWord> words = new Stack<BxWord>(); Stack<BxChunk> chunks = new Stack<BxChunk>(); for (BxPage page : copy) { assertTrue(page.getParent() == copy); for (BxZone zone : page) { assertTrue(zone.getParent() == page); for (BxLine line : zone) { assertTrue(line.getParent() == zone); for (BxWord word : line) { assertTrue(word.getParent() == line); for (BxChunk chunk : word) { assertTrue(chunk.getParent() == word); } } } } } BxPage page = copy.getFirstChild(); while (page != null) { pages.push(page); page = page.getNext(); } page = pages.peek(); BxZone zone = copy.getFirstChild().getFirstChild(); while (zone != null) { zones.push(zone); zone = zone.getNext(); } zone = zones.peek(); BxLine line = copy.getFirstChild().getFirstChild().getFirstChild(); while (line != null) { lines.push(line); line = line.getNext(); } line = lines.peek(); BxWord word = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (word != null) { words.push(word); word = word.getNext(); } word = words.peek(); BxChunk chunk = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (chunk != null) { chunks.push(chunk); chunk = chunk.getNext(); } chunk = chunks.peek(); while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); while (page != null) { pages.push(page); page = page.getPrev(); } while (zone != null) { zones.push(zone); zone = zone.getPrev(); } while (line != null) { lines.push(line); line = line.getPrev(); } while (word != null) { words.push(word); word = word.getPrev(); } while (chunk != null) { chunks.push(chunk); chunk = chunk.getPrev(); } while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class .getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); BufferedReader rangeFile = null; if (rangeFilePath != null) { InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class .getResourceAsStream(rangeFilePath)); rangeFile = new BufferedReader(rangeISR); } loadModelFromFile(modelFile, rangeFile); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(this.getClass().getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(this.getClass().getResourceAsStream(rangeFilePath)); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<TrainingSample<BxZoneLabel>> loadProblem(File file, FeatureVectorBuilder<BxZone, BxPage> fvb) throws IOException { List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; final Pattern partsPattern = Pattern.compile(" "); final Pattern twopartPattern = Pattern.compile(":"); while ((line = br.readLine()) != null) { String[] parts = partsPattern.split(line); BxZoneLabel label = BxZoneLabel.values()[Integer.parseInt(parts[0])]; FeatureVector fv = new FeatureVector(); List<String> featureNames = fvb.getFeatureNames(); for (int partIdx = 1; partIdx < parts.length; ++partIdx) { String[] subparts = twopartPattern.split(parts[partIdx]); fv.addFeature(featureNames.get(partIdx - 1), Double.parseDouble(subparts[1])); } TrainingSample<BxZoneLabel> sample = new TrainingSample<BxZoneLabel>(fv, label); ret.add(sample); } br.close(); return ret; } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code public static List<TrainingSample<BxZoneLabel>> loadProblem(File file, FeatureVectorBuilder<BxZone, BxPage> fvb) throws IOException { List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String line; final Pattern partsPattern = Pattern.compile(" "); final Pattern twopartPattern = Pattern.compile(":"); while ((line = br.readLine()) != null) { String[] parts = partsPattern.split(line); BxZoneLabel label = BxZoneLabel.values()[Integer.parseInt(parts[0])]; FeatureVector fv = new FeatureVector(); List<String> featureNames = fvb.getFeatureNames(); for (int partIdx = 1; partIdx < parts.length; ++partIdx) { String[] subparts = twopartPattern.split(parts[partIdx]); fv.addFeature(featureNames.get(partIdx - 1), Double.parseDouble(subparts[1])); } TrainingSample<BxZoneLabel> sample = new TrainingSample<BxZoneLabel>(fv, label); ret.add(sample); } br.close(); return ret; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath)); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath), "UTF-8"); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath), "UTF-8"); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: <pubmed directory>"); System.exit(1); } File dir = new File(args[0]); for (File pdfFile : FileUtils.listFiles(dir, new String[]{"pdf"}, true)) { try { String pdfPath = pdfFile.getPath(); String nxmlPath = StringTools.getNLMPath(pdfPath); File xmlFile = new File(StringTools.getTrueVizPath(nxmlPath)); if (xmlFile.exists()) { continue; } System.out.print(pdfPath+" "); InputStream pdfStream = new FileInputStream(pdfPath); InputStream nxmlStream = new FileInputStream(nxmlPath); PubmedXMLGenerator datasetGenerator = new PubmedXMLGenerator(); datasetGenerator.setVerbose(false); BxDocument bxDoc = datasetGenerator.generateTrueViz(pdfStream, nxmlStream); FileWriter fstream = new FileWriter(StringTools.getTrueVizPath(nxmlPath)); BufferedWriter out = new BufferedWriter(fstream); BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); out.write(writer.write(bxDoc.getPages())); out.close(); System.out.println("done"); } catch (Exception e) { e.printStackTrace(); } } } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: <pubmed directory>"); System.exit(1); } File dir = new File(args[0]); for (File pdfFile : FileUtils.listFiles(dir, new String[]{"pdf"}, true)) { try { String pdfPath = pdfFile.getPath(); String nxmlPath = StringTools.getNLMPath(pdfPath); File xmlFile = new File(StringTools.getTrueVizPath(nxmlPath)); if (xmlFile.exists()) { continue; } System.out.print(pdfPath+" "); InputStream pdfStream = new FileInputStream(pdfPath); InputStream nxmlStream = new FileInputStream(nxmlPath); PubmedXMLGenerator datasetGenerator = new PubmedXMLGenerator(); datasetGenerator.setVerbose(false); BxDocument bxDoc = datasetGenerator.generateTrueViz(pdfStream, nxmlStream); int keys = 0; Set<BxZoneLabel> set = EnumSet.noneOf(BxZoneLabel.class); int total = 0; int known = 0; for (BxZone z: bxDoc.asZones()) { total++; if (z.getLabel() != null) { known++; if (z.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { set.add(z.getLabel()); } if (BxZoneLabel.REFERENCES.equals(z.getLabel())) { keys = 1; } } } if (set.contains(BxZoneLabel.MET_AFFILIATION)) { keys++; } if (set.contains(BxZoneLabel.MET_AUTHOR)) { keys++; } if (set.contains(BxZoneLabel.MET_BIB_INFO)) { keys++; } if (set.contains(BxZoneLabel.MET_TITLE)) { keys++; } int coverage = 0; if (total > 0) { coverage = known*100/total; } System.out.print(coverage+" "+set.size()+" "+keys); FileWriter fstream = new FileWriter( StringTools.getTrueVizPath(nxmlPath).replace(".xml", "."+coverage+"."+set.size()+"."+keys+".cerm.xml")); BufferedWriter out = new BufferedWriter(fstream); BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); out.write(writer.write(bxDoc.getPages())); out.close(); System.out.println(" done"); } catch (Exception e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath))); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath))); } loadModelFromFile(modelFile, rangeFile); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8")); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8")); } loadModelFromFile(modelFile, rangeFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private BxDocument getDocumentFromZip(String filename) throws TransformationException, IOException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().equals(filename)) { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry))); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); return newDoc; } } return null; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code private BxDocument getDocumentFromZip(String filename) throws TransformationException, IOException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().equals(filename)) { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); return newDoc; } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws AnalysisException, TransformationException, IOException { // args[0] path to xml directory if(args.length != 1) { System.err.println("Source directory needed!"); System.exit(1); } InputStreamReader modelISR = new InputStreamReader(Thread.currentThread().getClass() .getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier")); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(Thread.currentThread().getClass() .getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier.range")); BufferedReader rangeFile = new BufferedReader(rangeISR); SVMZoneClassifier classifier = new SVMInitialZoneClassifier(modelFile, rangeFile); ReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter(); List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]); for(BxDocument doc: docs) { System.out.println(">> " + doc.getFilename()); ror.resolve(doc); classifier.classifyZones(doc); BufferedWriter out = null; try { // Create file FileWriter fstream = new FileWriter(doc.getFilename()); out = new BufferedWriter(fstream); out.write(tvw.write(doc.getPages())); out.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { if(out != null) { out.close(); } } } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws AnalysisException, TransformationException, IOException { // args[0] path to xml directory if(args.length != 1) { System.err.println("Source directory needed!"); System.exit(1); } SVMInitialZoneClassifier classifier = new SVMInitialZoneClassifier("/pl/edu/icm/cermine/structure/svm_initial_classifier", "/pl/edu/icm/cermine/structure/svm_initial_classifier.range"); ReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter(); List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]); for(BxDocument doc: docs) { System.out.println(">> " + doc.getFilename()); ror.resolve(doc); classifier.classifyZones(doc); BufferedWriter out = null; try { // Create file FileWriter fstream = new FileWriter(doc.getFilename()); out = new BufferedWriter(fstream); out.write(tvw.write(doc.getPages())); out.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { if(out != null) { out.close(); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[8192]; int len; try { digest = MessageDigest.getInstance("SHA-1"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public static String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte[] buffer = new byte[8192]; int len; try { digest = MessageDigest.getInstance("SHA-1"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeToXml() throws Exception { // 排版缩进的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 设置编码 format.setEncoding("UTF-8"); // 创建XMLWriter对象,指定了写出文件及编码格式 XMLWriter writer = null; writer = new XMLWriter( new OutputStreamWriter(new FileOutputStream(new File(ConstantsTools.PATH_CONFIG)), "UTF-8"), format); // 写入 writer.write(document); writer.flush(); writer.close(); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public void writeToXml() throws Exception { // 排版缩进的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 设置编码 format.setEncoding("UTF-8"); // 创建XMLWriter对象,指定了写出文件及编码格式 XMLWriter writer = null; writer = new XMLWriter( new OutputStreamWriter(new FileOutputStream(new File(ConstantsTools.PATH_CONFIG)), StandardCharsets.UTF_8), format); // 写入 writer.write(document); writer.flush(); writer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void clearDirectiory(String dir) { File dirFile = new File(dir); for (File file : dirFile.listFiles()) { file.delete(); } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public static void clearDirectiory(String dir) { File dirFile = new File(dir); for (File file : Objects.requireNonNull(dirFile.listFiles())) { file.delete(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String getFileMD5(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[8192]; int len; try { digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public static String getFileMD5(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte[] buffer = new byte[8192]; int len; try { digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code <T extends GHMetaExamples.GHMetaExample> GHMetaExamples.GHMetaExample getMetaExample(Class<T> clazz) throws IOException { return retrieve().to("/meta", clazz); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code GitHub(String apiUrl, String login, String oauthAccessToken, String jwtToken, String password, HttpConnector connector, RateLimitHandler rateLimitHandler, AbuseLimitHandler abuseLimitHandler) throws IOException { if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length() - 1); // normalize this.apiUrl = apiUrl; if (null != connector) this.connector = connector; if (oauthAccessToken != null) { encodedAuthorization = "token " + oauthAccessToken; } else { if (jwtToken != null) { encodedAuthorization = "Bearer " + jwtToken; } else if (password != null) { String authorization = (login + ':' + password); String charsetName = Charsets.UTF_8.name(); encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes(charsetName)), charsetName); } else {// anonymous access encodedAuthorization = null; } } users = new ConcurrentHashMap<String, GHUser>(); orgs = new ConcurrentHashMap<String, GHOrganization>(); this.rateLimitHandler = rateLimitHandler; this.abuseLimitHandler = abuseLimitHandler; if (login == null && encodedAuthorization != null && jwtToken == null) login = getMyself().getLogin(); this.login = login; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected String getApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. return StringUtils.prependIfMissing(getUrl().toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/pulls/" + number; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected String getApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. final URL url = Objects.requireNonNull(getUrl(), "Missing instance URL!"); return StringUtils.prependIfMissing(url.toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/pulls/" + number; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) return null; return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) { String data = IOUtils.toString(r); return null; } return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected String getIssuesApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. return StringUtils.prependIfMissing(getUrl().toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/issues/" + number; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code protected String getIssuesApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. final URL url = Objects.requireNonNull(getUrl(), "Missing instance URL!"); return StringUtils.prependIfMissing(url.toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/issues/" + number; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static PagedIterable<GHDiscussion> readAll(GHTeam team) throws IOException { return team.root.createRequest() .setRawUrlPath(team.getUrl().toString() + "/discussions") .toIterable(GHDiscussion[].class, item -> item.wrapUp(team)); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code static PagedIterable<GHDiscussion> readAll(GHTeam team) throws IOException { return team.root.createRequest() .setRawUrlPath(getRawUrlPath(team, null)) .toIterable(GHDiscussion[].class, item -> item.wrapUp(team)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static GHDiscussion read(GHTeam team, long discussionNumber) throws IOException { return team.root.createRequest() .setRawUrlPath(team.getUrl().toString() + "/discussions/" + discussionNumber) .fetch(GHDiscussion.class) .wrapUp(team); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code static GHDiscussion read(GHTeam team, long discussionNumber) throws IOException { return team.root.createRequest() .setRawUrlPath(getRawUrlPath(team, discussionNumber)) .fetch(GHDiscussion.class) .wrapUp(team); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void delete() throws IOException { team.root.createRequest() .method("DELETE") .setRawUrlPath(team.getUrl().toString() + "/discussions/" + number) .send(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void delete() throws IOException { team.root.createRequest().method("DELETE").setRawUrlPath(getRawUrlPath(team, number)).send(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) return null; return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) { String data = IOUtils.toString(r); return null; } return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testWindowPeer() throws Exception { if (Platform.isMacOSX() || System.getProperty("java.version)").matches("1\\.6\\..*")) { // Oracle Java and jawt: it's complicated. // See http://forum.lwjgl.org/index.php?topic=4326.0 // OpenJDK 6 + Linux seem problematic too. return; } assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class)); assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class)); //assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class)); //assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class)); Frame f = new Frame(); f.pack(); f.setVisible(true); Thread.sleep(500); long p = JAWTUtils.getNativePeerHandle(f); assertTrue(p != 0); f.setVisible(false); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testWindowPeer() throws Exception { if (Platform.isMacOSX() || System.getProperty("java.version").matches("1\\.6\\..*")) { // Oracle Java and jawt: it's complicated. // See http://forum.lwjgl.org/index.php?topic=4326.0 // OpenJDK 6 + Linux seem problematic too. return; } assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class)); assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class)); //assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class)); //assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class)); Frame f = new Frame(); f.pack(); f.setVisible(true); Thread.sleep(500); long p = JAWTUtils.getNativePeerHandle(f); assertTrue(p != 0); f.setVisible(false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private HttpClient getHttpClient(PrintStream logger) { HttpClient client = null; boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; String url = stashServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); if ("".equals(url) || url == null) { url = descriptor.getStashRootUrl(); } if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } if (url.startsWith("https") && ignoreUnverifiedSSL) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { HttpClientBuilder builder = HttpClientBuilder.create(); TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, easyStrategy) .useTLS().build(); SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslConnSocketFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnSocketFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); client = builder.build(); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } finally { if (client == null) { logger.println("Trying with safe trust manager, instead!"); client = HttpClientBuilder.create().build(); } } } else { client = HttpClientBuilder.create().build(); } ProxyConfiguration proxy = Jenkins.getInstance().proxy; if(proxy != null && !proxy.name.isEmpty() && !proxy.name.startsWith("http") && !isHostOnNoProxyList(proxy)){ SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", proxy.port, new PlainSocketFactory())); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy.name, proxy.port)); } return client; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private HttpClient getHttpClient(PrintStream logger) throws Exception { boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; String stashServer = stashServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); if ("".equals(stashServer) || stashServer == null) { stashServer = descriptor.getStashRootUrl(); } if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } URL url = new URL(stashServer); HttpClientBuilder builder = HttpClientBuilder.create(); if (url.getProtocol().equals("https") && ignoreUnverifiedSSL) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, easyStrategy) .useTLS().build(); SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslConnSocketFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnSocketFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } } // Configure the proxy, if needed // Using the Jenkins methods handles the noProxyHost settings ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; if (proxyConfig != null) { Proxy proxy = proxyConfig.createProxy(url.getHost()); if (proxy != null && proxy.type() == Proxy.Type.HTTP) { SocketAddress addr = proxy.address(); if (addr != null && addr instanceof InetSocketAddress) { InetSocketAddress proxyAddr = (InetSocketAddress) addr; HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort()); builder = builder.setProxy(proxyHost); String proxyUser = proxyConfig.getUserName(); if (proxyUser != null) { String proxyPass = proxyConfig.getPassword(); CredentialsProvider cred = new BasicCredentialsProvider(); cred.setCredentials(new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder = builder .setDefaultCredentialsProvider(cred) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } } return builder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { AppUtil appUtil = new AppUtil(); AService service = (AService) appUtil.getComponentInstance("aService"); AggregateRootA aggregateRootA = service.getAggregateRootA("11"); DomainMessage res = service.commandA("11", aggregateRootA, 100); long start = System.currentTimeMillis(); int result = 0; DomainMessage res1 = (DomainMessage) res.getBlockEventResult(); if (res1.getBlockEventResult() != null) result = (Integer) res1.getBlockEventResult(); long stop = System.currentTimeMillis(); Assert.assertEquals(result, 400); System.out.print("\n ok \n" + result + (stop - start)); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { AppUtil appUtil = new AppUtil(); AService service = (AService) appUtil.getComponentInstance("aService"); AggregateRootA aggregateRootA = service.getAggregateRootA("11"); DomainMessage res = service.commandA("11", aggregateRootA, 100); long start = System.currentTimeMillis(); int result = 0; DomainMessage res1 = (DomainMessage) res.getBlockEventResult(); if (res1 != null && res1.getBlockEventResult() != null) result = (Integer) res1.getBlockEventResult(); long stop = System.currentTimeMillis(); Assert.assertEquals(result, 400); System.out.print("\n ok \n" + result + " time:" + (stop - start)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean doExists(String name, Locale locale, String path) throws Exception { return file != null && file.exists() && new ZipFile(file).getEntry(name) != null; } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public boolean doExists(String name, Locale locale, String path) throws Exception { if (file != null && file.exists()) { ZipFile zipFile = new ZipFile(file); try { return zipFile.getEntry(name) != null; } finally { zipFile.close(); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getLastModified() { try { JarFile zipFile = new JarFile(file); return zipFile.getEntry(getName()).getTime(); } catch (Throwable e) { return super.getLastModified(); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public long getLastModified() { try { JarFile jarFile = new JarFile(file); return jarFile.getEntry(getName()).getTime(); } catch (Throwable e) { return super.getLastModified(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Template extend(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); if (locale == null) { locale = template.getLocale(); } } Template extend = engine.getTemplate(name); if (macro != null && macro.length() > 0) { extend = extend.getMacros().get(macro); } if (template != null && template == extend) { throw new IllegalStateException("The template " + template.getName() + " can not be recursive extending the self template."); } Context.getContext().putAll(template.getMacros()); return extend; } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code public Template extend(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); if (locale == null) { locale = template.getLocale(); } } Template extend = engine.getTemplate(name); if (macro != null && macro.length() > 0) { extend = extend.getMacros().get(macro); } if (template != null) { if (template == extend) { throw new IllegalStateException("The template " + template.getName() + " can not be recursive extending the self template."); } Context.getContext().putAll(template.getMacros()); } return extend; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Template parse(String name, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); } name = UrlUtils.cleanUrl(name.trim()); template = engine.getTemplate(name, encoding); if (macro != null && macro.length() > 0) { return template.getMacros().get(macro); } return template; } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public Template parse(String name, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); } template = engine.getTemplate(name, encoding); if (macro != null && macro.length() > 0) { return template.getMacros().get(macro); } return template; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean doExists(String name, Locale locale, String path) throws Exception { return file != null && file.exists() && new JarFile(file).getEntry(name) != null; } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public boolean doExists(String name, Locale locale, String path) throws Exception { if (file != null && file.exists()) { JarFile jarFile = new JarFile(file); try { return jarFile.getEntry(name) != null; } finally { jarFile.close(); } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Template include(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); if (locale == null) { locale = template.getLocale(); } } Template include = engine.getTemplate(name, locale, encoding); if (macro != null && macro.length() > 0) { include = include.getMacros().get(macro); } if (include == template) { throw new IllegalStateException("The template " + template.getName() + " can not be recursive including the self template."); } return include; } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code public Template include(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); if (locale == null) { locale = template.getLocale(); } } Template include = engine.getTemplate(name, locale, encoding); if (macro != null && macro.length() > 0) { include = include.getMacros().get(macro); } if (template != null && template == include) { throw new IllegalStateException("The template " + template.getName() + " can not be recursive including the self template."); } return include; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } #location 47 #vulnerability type NULL_DEREFERENCE
#fixed code public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try { if (bais != null) bais.close(); } finally { if (ois != null) ois.close(); } } // end finally return obj; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testException() throws Exception { boolean profile = "true".equals(System.getProperty("profile")); if (! profile) System.out.println("========httl-exception.properties========"); Engine engine = Engine.getEngine("httl-exception.properties"); String dir = engine.getProperty("template.directory", ""); if (dir.length() > 0 && dir.startsWith("/")) { dir = dir.substring(1); } if (dir.length() > 0 && ! dir.endsWith("/")) { dir += "/"; } File directory = new File(this.getClass().getClassLoader().getResource(dir + "templates/").getFile()); assertTrue(directory.isDirectory()); File[] files = directory.listFiles(); for (int i = 0, n = files.length; i < n; i ++) { File file = files[i]; System.out.println(file.getName()); URL url = this.getClass().getClassLoader().getResource(dir + "results/" + file.getName() + ".txt"); if (url == null) { throw new FileNotFoundException("Not found file: " + dir + "results/" + file.getName() + ".txt"); } File result = new File(url.getFile()); if (! result.exists()) { throw new FileNotFoundException("Not found file: " + result.getAbsolutePath()); } try { engine.getTemplate("/templates/" + file.getName()); fail(file.getName()); } catch (ParseException e) { if (! profile) { String message = e.getMessage(); assertTrue(StringUtils.isNotEmpty(message)); List<String> expected = IOUtils.readLines(new FileReader(result)); assertTrue(expected != null && expected.size() > 0); for (String part : expected) { assertTrue(StringUtils.isNotEmpty(part)); part = StringUtils.unescapeString(part).trim(); assertTrue(file.getName() + ", exception message: \"" + message + "\" not contains: \"" + part + "\"", message.contains(part)); } } } } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testException() throws Exception { boolean profile = "true".equals(System.getProperty("profile")); Engine engine = Engine.getEngine("httl-exception.properties"); String dir = engine.getProperty("template.directory", ""); if (dir.length() > 0 && dir.startsWith("/")) { dir = dir.substring(1); } if (dir.length() > 0 && ! dir.endsWith("/")) { dir += "/"; } URL url = this.getClass().getClassLoader().getResource(dir + "results/" + templateName + ".txt"); if (url == null) { throw new FileNotFoundException("Not found file: " + dir + "results/" + templateName + ".txt"); } File result = new File(url.getFile()); if (! result.exists()) { throw new FileNotFoundException("Not found file: " + result.getAbsolutePath()); } try { engine.getTemplate("/templates/" + templateName); fail(templateName); } catch (ParseException e) { if (! profile) { String message = e.getMessage(); assertTrue(StringUtils.isNotEmpty(message)); List<String> expected = IOUtils.readLines(new FileReader(result)); assertTrue(expected != null && expected.size() > 0); for (String part : expected) { assertTrue(StringUtils.isNotEmpty(part)); part = StringUtils.unescapeString(part).trim(); assertTrue(templateName + ", exception message: \"" + message + "\" not contains: \"" + part + "\"", message.contains(part)); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getLength() { try { JarFile jarFile = new JarFile(file); return jarFile.getEntry(getName()).getSize(); } catch (IOException e) { return super.getLength(); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public long getLength() { try { JarFile jarFile = new JarFile(file); try { return jarFile.getEntry(getName()).getSize(); } finally { jarFile.close(); } } catch (IOException e) { return super.getLength(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (config == null || config.length() == 0) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (StringUtils.isEmpty(config)) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try { if (oos != null) oos.close(); } finally { try { if (gzos != null) gzos.close(); } finally { try { if (b64os != null) b64os.close(); } finally { if (baos != null) baos.close(); } } } } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String getRefValue(Properties result, String v) { if (v != null) { while (v.startsWith(REF)) { String ref = v.substring(1); v = result.getProperty(ref); if (v == null) { v = System.getProperty(ref); } } } return v == null ? "" : v; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private static String getRefValue(Properties result, String v) { while (v != null && v.startsWith(REF)) { String ref = v.substring(1); v = result.getProperty(ref); if (v == null) { v = System.getProperty(ref); } } return v == null ? "" : v; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getLength() { try { ZipFile zipFile = new ZipFile(file); return zipFile.getEntry(getName()).getSize(); } catch (IOException e) { return super.getLength(); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public long getLength() { try { ZipFile zipFile = new ZipFile(file); try { return zipFile.getEntry(getName()).getSize(); } finally { zipFile.close(); } } catch (IOException e) { return super.getLength(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (config == null || config.length() == 0) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (StringUtils.isEmpty(config)) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } #location 50 #vulnerability type NULL_DEREFERENCE
#fixed code public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try { if (baos != null) baos.close(); } finally { try { if (gzis != null) gzis.close(); } finally { if (bais != null) bais.close(); } } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean doExists(String name, Locale locale, String path) throws Exception { InputStream in = new URL(path).openStream(); try { return in != null; } finally { in.close(); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean doExists(String name, Locale locale, String path) throws Exception { InputStream in = new URL(path).openStream(); try { return in != null; } finally { if (in != null) in.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { defaultFilterVariable = "$" + filterVariable; defaultFormatterVariable = "$" + formatterVariable; if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } if (importMethods != null && importMethods.length > 0) { for (String method : importMethods) { Class<?> cls = ClassUtils.forName(importPackages, method); Object ins; try { ins = cls.newInstance(); } catch (Exception e) { ins = cls; } this.functions.put(cls, ins); } } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code public void init() { defaultFilterVariable = "$" + filterVariable; defaultFormatterVariable = "$" + formatterVariable; if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Object parseXbean(String xml) { if (xml == null) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xd = new XMLDecoder(bi); return xd.readObject(); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public static Object parseXbean(String xml) { if (xml == null) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xd = new XMLDecoder(bi); try { return xd.readObject(); } finally { xd.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } #location 43 #vulnerability type NULL_DEREFERENCE
#fixed code public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try { if (gzos != null) gzos.close(); } finally { try { if (b64os != null) b64os.close(); } finally { if (baos != null) baos.close(); } } } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() { if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } if (importMethods != null && importMethods.length > 0) { for (String method : importMethods) { Class<?> cls = ClassUtils.forName(importPackages, method); Object ins; try { ins = cls.newInstance(); } catch (Exception e) { ins = cls; } this.functions.put(cls, ins); } } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public void init() { if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public InputStream getInputStream() throws IOException { // 注:JarFile与File的设计是不一样的,File相当于C#的FileInfo,只持有信息, // 而JarFile构造时即打开流,所以每次读取数据时,重新new新的实例,而不作为属性字段持有。 JarFile zipFile = new JarFile(file); return zipFile.getInputStream(zipFile.getEntry(getName())); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public InputStream getInputStream() throws IOException { // 注:JarFile与File的设计是不一样的,File相当于C#的FileInfo,只持有信息, // 而JarFile构造时即打开流,所以每次读取数据时,重新new新的实例,而不作为属性字段持有。 JarFile jarFile = new JarFile(file); return jarFile.getInputStream(jarFile.getEntry(getName())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final OutputStream os = System.out; final HttpServletResponse response = Context.get().getResponse(); final InputStream actualStream = WroTestUtils.convertToInputStream(os); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(os)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), actualStream); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Context.get().getResponse(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(out)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); //compare written bytes to output stream with the content from specified css. WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), new ByteArrayInputStream(out.toByteArray())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { System.out.println("BOM:"); // using ReaderInputStream instead of ByteArrayInputStream, cause processing to freeze final InputStream is = new BomStripperInputStream(new ByteArrayInputStream(IOUtils.toByteArray(reader))); IOUtils.copy(is, writer, Context.get().getConfig().getEncoding()); System.out.println("END BOM"); } finally { reader.close(); writer.close(); } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { // using ReaderInputStream instead of ByteArrayInputStream, cause processing to freeze final String encoding = Context.get().getConfig().getEncoding(); final InputStream is = new BomStripperInputStream(new ByteArrayInputStream(IOUtils.toByteArray(reader, encoding))); IOUtils.copy(is, writer, encoding); } finally { reader.close(); writer.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void destroy() { //kill running threads executorService.shutdownNow(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void destroy() { //kill running threads scheduler.shutdownNow(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try { // add request, response & servletContext to thread local Context.set(Context.webContext(request, response, filterConfig)); final ByteArrayOutputStream os = new ByteArrayOutputStream(); HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(req, wrappedResponse); final Reader reader = new StringReader(new String(os.toByteArray(), Context.get().getConfig().getEncoding())); doProcess(reader, response.getWriter()); response.flushBuffer(); } catch (final RuntimeException e) { onRuntimeException(e, response, chain); } finally { Context.unset(); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; try { // add request, response & servletContext to thread local Context.set(Context.webContext(request, response, filterConfig)); IOUtils.write("\nBefore chain!\n", response.getOutputStream()); final ByteArrayOutputStream os = new ByteArrayOutputStream(); System.out.println(response.getOutputStream()); final HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(request, wrappedResponse); final Reader reader = new StringReader(new String(os.toByteArray(), Context.get().getConfig().getEncoding())); doProcess(reader, new OutputStreamWriter(os)); IOUtils.write(os.toByteArray(), response.getOutputStream()); response.flushBuffer(); response.getOutputStream().close(); } catch (final RuntimeException e) { onRuntimeException(e, response, chain); } finally { Context.unset(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final OutputStream os = System.out; final HttpServletResponse response = Context.get().getResponse(); final InputStream actualStream = WroTestUtils.convertToInputStream(os); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(os)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), actualStream); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Context.get().getResponse(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(out)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); //compare written bytes to output stream with the content from specified css. WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), new ByteArrayInputStream(out.toByteArray())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); final OutputStream os = new ByteArrayOutputStream(); HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(Context.get().getRequest(), wrappedResponse); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); chain.doFilter(Context.get().getRequest(), response); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private InputStream locateStreamFromJar(final String uri, final File jarPath) throws IOException { LOG.debug("\t\tLocating stream from jar"); String classPath = FilenameUtils.getPath(uri); final String wildcard = FilenameUtils.getName(uri); if (classPath.startsWith(ClasspathUriLocator.PREFIX)) { classPath = StringUtils.substringAfter(classPath, ClasspathUriLocator.PREFIX); } final JarFile file = open(jarPath); List<JarEntry> jarEntryList = Collections.list(file.entries()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); for (JarEntry entry : jarEntryList) { if (entry.getName().startsWith(classPath) && accept(entry, wildcard)) { final InputStream is = file.getInputStream(entry); IOUtils.copy(is, out); is.close(); } } return new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code private InputStream locateStreamFromJar(final String uri, final File jarPath) throws IOException { LOG.debug("\t\tLocating stream from jar"); String classPath = FilenameUtils.getPath(uri); final String wildcard = FilenameUtils.getName(uri); if (classPath.startsWith(ClasspathUriLocator.PREFIX)) { classPath = StringUtils.substringAfter(classPath, ClasspathUriLocator.PREFIX); } final JarFile file = open(jarPath); final List<JarEntry> jarEntryList = Collections.list(file.entries()); final List<JarEntry> filteredJarEntryList = new ArrayList<JarEntry>(); for (final JarEntry entry : jarEntryList) { final boolean isSupportedEntry = entry.getName().startsWith(classPath) && accept(entry, wildcard); if (isSupportedEntry) { filteredJarEntryList.add(entry); } } final ByteArrayOutputStream out = new ByteArrayOutputStream(); for (final JarEntry entry : filteredJarEntryList) { final InputStream is = file.getInputStream(entry); IOUtils.copy(is, out); is.close(); } return new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); final OutputStream os = new ByteArrayOutputStream(); HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); chain.doFilter(Context.get().getRequest(), wrappedResponse); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { LOG.debug("RuntimeException occured", e); try { LOG.debug("Cannot process. Proceeding with chain execution."); chain.doFilter(Context.get().getRequest(), response); } catch (final Exception ex) { // should never happen LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void process(final Reader reader, final Writer writer) throws IOException { final StopWatch watch = new StopWatch(); watch.start("pack"); final InputStream is = new ByteArrayInputStream(IOUtils.toByteArray(reader)); try { final JavaScriptCompressor compressor = new JavaScriptCompressor(new InputStreamReader(is), new YUIErrorReporter()); compressor.compress(writer, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations); } catch (final RuntimeException e) { LOG.error("Problem while applying YUI compressor", e); //keep js unchanged if it contains errors -> this should be configurable LOG.debug("Leave resource unchanged..."); is.reset(); IOUtils.copy(is, writer); //throw new WroRuntimeException("Problem while applying YUI compressor", e); } finally { is.close(); reader.close(); writer.close(); watch.stop(); LOG.debug(watch.prettyPrint()); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void process(final Reader reader, final Writer writer) throws IOException { final StopWatch watch = new StopWatch(); watch.start("pack"); final String content = IOUtils.toString(reader); try { final JavaScriptCompressor compressor = new JavaScriptCompressor(new StringReader(content), new YUIErrorReporter()); compressor.compress(writer, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations); } catch (final RuntimeException e) { LOG.error("Problem while applying YUI compressor", e); //keep js unchanged if it contains errors -> this should be configurable LOG.debug("Leave resource unchanged..."); IOUtils.copy(new StringReader(content), writer); //throw new WroRuntimeException("Problem while applying YUI compressor", e); } finally { reader.close(); writer.close(); watch.stop(); LOG.debug(watch.prettyPrint()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response, final String location) throws IOException { Validate.notNull(request); Validate.notNull(response); // where to write the bytes of the stream final ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean warnOnEmptyStream = false; // preserve context, in case it is unset during dispatching final Context originalContext = Context.get(); try { final RequestDispatcher dispatcher = request.getRequestDispatcher(location); if (dispatcher == null) { // happens when dynamic servlet context relative resources are included outside of the request cycle (inside // the thread responsible for refreshing resources) // Returns the part URL from the protocol name up to the query string and contextPath. final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), ""); final String absolutePath = servletContextPath + location; return getLocationStream(absolutePath); } // Wrap request final ServletRequest wrappedRequest = getWrappedServletRequest(request, location); // Wrap response final ServletResponse wrappedResponse = getWrappedServletResponse(response, os); LOG.debug("dispatching request to location: " + location); // use dispatcher dispatcher.include(wrappedRequest, wrappedResponse); warnOnEmptyStream = true; // force flushing - the content will be written to // BytArrayOutputStream. Otherwise exactly 32K of data will be // written. wrappedResponse.getWriter().flush(); os.close(); } catch (final Exception e) { // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are // included. LOG.debug("[FAIL] Error while dispatching the request for location {}", location); throw new IOException("Error while dispatching the request for location " + location); } finally { if (warnOnEmptyStream && os.size() == 0) { LOG.warn("Wrong or empty resource with location: {}", location); } // Put the context back if (!Context.isContextSet()) { Context.set(originalContext); } } return new ByteArrayInputStream(os.toByteArray()); } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code public InputStream getInputStream(final HttpServletRequest request, final HttpServletResponse response, final String location) throws IOException { Validate.notNull(request); Validate.notNull(response); // where to write the bytes of the stream final ByteArrayOutputStream os = new ByteArrayOutputStream(); boolean warnOnEmptyStream = false; // preserve context, in case it is unset during dispatching final Context originalContext = Context.get(); try { final RequestDispatcher dispatcher = request.getRequestDispatcher(location); if (dispatcher == null) { // happens when dynamic servlet context relative resources are included outside of the request cycle (inside // the thread responsible for refreshing resources) // Returns the part URL from the protocol name up to the query string and contextPath. final String servletContextPath = request.getRequestURL().toString().replace(request.getServletPath(), ""); final String absolutePath = servletContextPath + location; return externalResourceLocator.locate(absolutePath); } // Wrap request final ServletRequest servletRequest = getWrappedServletRequest(request, location); // Wrap response final ServletResponse servletResponse = new RedirectedStreamServletResponseWrapper(os, response); LOG.debug("dispatching request to location: " + location); // use dispatcher dispatcher.include(servletRequest, servletResponse); warnOnEmptyStream = true; // force flushing - the content will be written to // BytArrayOutputStream. Otherwise exactly 32K of data will be // written. servletResponse.getWriter().flush(); os.close(); } catch (final Exception e) { // Not only servletException can be thrown, also dispatch.include can throw NPE when the scheduler runs outside // of the request cycle, thus connection is unavailable. This is caused mostly when invalid resources are // included. LOG.debug("[FAIL] Error while dispatching the request for location {}", location); throw new IOException("Error while dispatching the request for location " + location); } finally { if (warnOnEmptyStream && os.size() == 0) { LOG.warn("Wrong or empty resource with location: {}", location); } // Put the context back if (!Context.isContextSet()) { Context.set(originalContext); } } return new ByteArrayInputStream(os.toByteArray()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void onModelPeriodChanged() { //force scheduler to reload initScheduler(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void onModelPeriodChanged() { //force scheduler to reload model = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getScalarValue(String key) throws ConfiguratorException { return get(key).asScalar().getValue(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public String getScalarValue(String key) throws ConfiguratorException { return remove(key).asScalar().getValue(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object configure(Object c) throws Exception { final ExtensionList list = Jenkins.getInstance().getExtensionList(target); if (list.size() != 1) { throw new IllegalStateException(); } final Object o = list.get(0); if (c instanceof Map) { Map config = (Map) c; final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); if (config.containsKey(name)) { final Object value = Configurator.lookup(attribute.getType()).configure(config.get(name)); attribute.setValue(o, value); } } } return o; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object configure(Object c) throws Exception { final ExtensionList list = Jenkins.getInstance().getExtensionList(target); if (list.size() != 1) { throw new IllegalStateException(); } final Object o = list.get(0); if (c instanceof Map) { Map config = (Map) c; final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); if (config.containsKey(name)) { final Class k = attribute.getType(); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+ k); final Object value = configurator.configure(config.get(name)); attribute.setValue(o, value); } } } return o; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object configure(Object c) throws Exception { Map config = c instanceof Map ? (Map) c : Collections.EMPTY_MAP; final Constructor constructor = getDataBoundConstructor(target); if (constructor == null) { throw new IllegalStateException(target.getName() + " is missing a @DataBoundConstructor"); } final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); Object[] args = new Object[names.length]; if (parameters.length > 0) { // Many jenkins components haven't been migrated to @DataBoundSetter vs @NotNull constructor parameters // as a result it might be valid to reference a describable without parameters for (int i = 0; i < names.length; i++) { final Object value = config.remove(names[i]); if (value == null && parameters[i].getAnnotation(Nonnull.class) != null) { throw new IllegalArgumentException(names[i] + " is required to configure " + target); } final Class t = parameters[i].getType(); if (value != null) { if (Collection.class.isAssignableFrom(t)) { if (!(value instanceof List)) { throw new IllegalArgumentException(names[i] + " should be a list"); } final Type pt = parameters[i].getParameterizedType(); final Configurator lookup = Configurator.lookup(pt); final ArrayList<Object> list = new ArrayList<>(); for (Object o : (List) value) { list.add(lookup.configure(o)); } args[i] = list; } else { final Type pt = parameters[i].getParameterizedType(); final Type k = pt != null ? pt : t; final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); args[i] = configurator.configure(value); } System.out.println("Setting " + target + "." + names[i] + " = " + value); } else if (t.isPrimitive()) { args[i] = Defaults.defaultValue(t); } } } final Object object; try { object = constructor.newInstance(args); } catch (IllegalArgumentException ex) { List<String> argumentTypes = new ArrayList<>(args.length); for (Object arg : args) { argumentTypes.add(arg != null ? arg.getClass().getName() : "null"); } throw new IOException("Failed to construct instance of " + target + ". Constructor: " + constructor.toString() + ". Arguments: " + argumentTypes, ex); } final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Configurator lookup = Configurator.lookup(attribute.getType()); if (config.containsKey(name)) { final Object yaml = config.get(name); Object value; if (attribute.isMultiple()) { List l = new ArrayList<>(); for (Object o : (List) yaml) { l.add(lookup.configure(o)); } value = l; } else { value = lookup.configure(config.get(name)); } attribute.setValue(object, value); } } return object; } #location 81 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object configure(Object c) throws Exception { Map config = c instanceof Map ? (Map) c : Collections.EMPTY_MAP; final Constructor constructor = getDataBoundConstructor(target); if (constructor == null) { throw new IllegalStateException(target.getName() + " is missing a @DataBoundConstructor"); } final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); Object[] args = new Object[names.length]; if (parameters.length > 0) { // Many jenkins components haven't been migrated to @DataBoundSetter vs @NotNull constructor parameters // as a result it might be valid to reference a describable without parameters for (int i = 0; i < names.length; i++) { final Object value = config.remove(names[i]); if (value == null && parameters[i].getAnnotation(Nonnull.class) != null) { throw new IllegalArgumentException(names[i] + " is required to configure " + target); } final Class t = parameters[i].getType(); if (value != null) { if (Collection.class.isAssignableFrom(t)) { if (!(value instanceof List)) { throw new IllegalArgumentException(names[i] + " should be a list"); } final Type pt = parameters[i].getParameterizedType(); final Configurator lookup = Configurator.lookup(pt); final ArrayList<Object> list = new ArrayList<>(); for (Object o : (List) value) { list.add(lookup.configure(o)); } args[i] = list; } else { final Type pt = parameters[i].getParameterizedType(); final Type k = pt != null ? pt : t; final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); args[i] = configurator.configure(value); } System.out.println("Setting " + target + "." + names[i] + " = " + value); } else if (t.isPrimitive()) { args[i] = Defaults.defaultValue(t); } } } final Object object; try { object = constructor.newInstance(args); } catch (IllegalArgumentException ex) { List<String> argumentTypes = new ArrayList<>(args.length); for (Object arg : args) { argumentTypes.add(arg != null ? arg.getClass().getName() : "null"); } throw new IOException("Failed to construct instance of " + target + ". Constructor: " + constructor.toString() + ". Arguments: " + argumentTypes, ex); } final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Configurator lookup = Configurator.lookup(attribute.getType()); if (config.containsKey(name)) { final Object yaml = config.get(name); Object value; if (attribute.isMultiple()) { List l = new ArrayList<>(); for (Object o : (List) yaml) { l.add(lookup.configure(o)); } value = l; } else { value = lookup.configure(config.get(name)); } attribute.setValue(object, value); } } for (Method method : target.getMethods()) { if (method.getParameterCount() == 0 && method.getAnnotation(PostConstruct.class) != null) { method.invoke(object, null); } } return object; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = Configurator.lookup(attribute.getType()).configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = Configurator.lookup(attribute.getType()).configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { final Class k = attribute.getType(); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = configurator.configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = configurator.configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Nonnull private static RoleMap retrieveRoleMap(@Nonnull CNode config, @Nonnull String name, Configurator<RoleDefinition> configurator) throws ConfiguratorException { Mapping map = config.asMapping(); final Sequence c = map.get(name).asSequence(); TreeMap<Role, Set<String>> resMap = new TreeMap<>(); if (c == null) { // we cannot return emptyMap here due to the Role Strategy code return new RoleMap(resMap); } for (CNode entry : c) { RoleDefinition definition = configurator.configure(entry); resMap.put(definition.getRole(), definition.getAssignments()); } return new RoleMap(resMap); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Nonnull private static RoleMap retrieveRoleMap(@Nonnull CNode config, @Nonnull String name, Configurator<RoleDefinition> configurator) throws ConfiguratorException { Mapping map = config.asMapping(); final CNode c = map.get(name); TreeMap<Role, Set<String>> resMap = new TreeMap<>(); if (c == null || c.asSequence() == null) { // we cannot return emptyMap here due to the Role Strategy code return new RoleMap(resMap); } for (CNode entry : c.asSequence()) { RoleDefinition definition = configurator.configure(entry); resMap.put(definition.getRole(), definition.getAssignments()); } return new RoleMap(resMap); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Describable configure(Object config) throws Exception { String shortname; Object subconfig = null; if (config instanceof String) { shortname = (String) config; } else if (config instanceof Map) { Map<String, ?> map = (Map) config; if (map.size() != 1) { throw new IllegalArgumentException("single entry map expected to configure a "+target.getName()); } final Map.Entry<String, ?> next = map.entrySet().iterator().next(); shortname = next.getKey(); subconfig = next.getValue(); } else { throw new IllegalArgumentException("Unexpected configuration type "+config); } final List<Descriptor> candidates = Jenkins.getInstance().getDescriptorList(target); Class<? extends Describable> k = findDescribableBySymbol(shortname, candidates); return (Describable) Configurator.lookup(k).configure(subconfig); } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Describable configure(Object config) throws Exception { String shortname; Object subconfig = null; if (config instanceof String) { shortname = (String) config; } else if (config instanceof Map) { Map<String, ?> map = (Map) config; if (map.size() != 1) { throw new IllegalArgumentException("single entry map expected to configure a "+target.getName()); } final Map.Entry<String, ?> next = map.entrySet().iterator().next(); shortname = next.getKey(); subconfig = next.getValue(); } else { throw new IllegalArgumentException("Unexpected configuration type "+config); } final List<Descriptor> candidates = Jenkins.getInstance().getDescriptorList(target); Class<? extends Describable> k = findDescribableBySymbol(shortname, candidates); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); return (Describable) configurator.configure(subconfig); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(target); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); if (args[i] == null) continue; mapping.put(names[i], attributes[i].describe(args[i])); } return mapping; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); if (args[i] == null) continue; mapping.put(names[i], attributes[i].describe(args[i])); } return mapping; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Nonnull @Override public T configure(CNode c, ConfigurationContext context) throws ConfiguratorException { final Mapping mapping = (c != null ? c.asMapping() : Mapping.EMPTY); final T instance = instance(mapping, context); if (instance instanceof Saveable) { BulkChange bc = new BulkChange((Saveable) instance); configure(mapping, instance, false, context); try { bc.commit(); } catch (IOException e) { throw new ConfiguratorException("Failed to save "+instance, e); } } else { configure(mapping, instance, false, context); } return instance; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Nonnull @Override public T configure(CNode c, ConfigurationContext context) throws ConfiguratorException { final Mapping mapping = (c != null ? c.asMapping() : Mapping.EMPTY); final T instance = instance(mapping, context); if (instance instanceof Saveable) { try (BulkChange bc = new BulkChange((Saveable) instance) ){ configure(mapping, instance, false, context); bc.commit(); } catch (IOException e) { throw new ConfiguratorException("Failed to save "+instance, e); } } else { configure(mapping, instance, false, context); } return instance; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ProjectMatrixAuthorizationStrategy configure(Object config) throws Exception { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookup(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configure(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } ProjectMatrixAuthorizationStrategy gms = new ProjectMatrixAuthorizationStrategy(); for(Map.Entry<Permission,Set<String>> permission : grantedPermissions.entrySet()) { for(String sid : permission.getValue()) { gms.add(permission.getKey(), sid); } } return gms; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ProjectMatrixAuthorizationStrategy configure(Object config) throws ConfiguratorException { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookupOrFail(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configureNonNull(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } ProjectMatrixAuthorizationStrategy gms = new ProjectMatrixAuthorizationStrategy(); for(Map.Entry<Permission,Set<String>> permission : grantedPermissions.entrySet()) { for(String sid : permission.getValue()) { gms.add(permission.getKey(), sid); } } return gms; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @POST public FormValidation doCheckNewSource(@QueryParameter String newSource) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String normalizedSource = Util.fixEmptyAndTrim(newSource); File file = new File(Util.fixNull(normalizedSource)); if (normalizedSource == null) { return FormValidation.ok(); // empty, do nothing } if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) { return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist."); } try { final Map<Source, String> issues = collectIssues(normalizedSource); final JSONArray errors = collectProblems(issues, "error"); if (!errors.isEmpty()) { return FormValidation.error(errors.toString()); } final JSONArray warnings = collectProblems(issues, "warning"); if (!warnings.isEmpty()) { return FormValidation.warning(warnings.toString()); } return FormValidation.okWithMarkup("The configuration can be applied"); } catch (ConfiguratorException | IllegalArgumentException e) { return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @POST public FormValidation doCheckNewSource(@QueryParameter String newSource) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); String normalizedSource = Util.fixEmptyAndTrim(newSource); File file = new File(Util.fixNull(normalizedSource)); if (normalizedSource == null) { return FormValidation.ok(); // empty, do nothing } if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) { return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist."); } List<YamlSource> yamlSources = Collections.emptyList(); try { List<String> sources = Collections.singletonList(normalizedSource); yamlSources = getConfigFromSources(sources); final Map<Source, String> issues = checkWith(yamlSources); final JSONArray errors = collectProblems(issues, "error"); if (!errors.isEmpty()) { return FormValidation.error(errors.toString()); } final JSONArray warnings = collectProblems(issues, "warning"); if (!warnings.isEmpty()) { return FormValidation.warning(warnings.toString()); } return FormValidation.okWithMarkup("The configuration can be applied"); } catch (ConfiguratorException | IllegalArgumentException e) { return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage()); } finally { closeSources(yamlSources); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean equals(O o1, O o2) throws Exception { final Object v1 = getValue(o1); final Object v2 = getValue(o2); if (v1 == null && v2 == null) return true; return (v1.equals(v2)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean equals(O o1, O o2) throws Exception { final Object v1 = getValue(o1); final Object v2 = getValue(o2); if (v1 == null && v2 == null) return true; return (v1 != null && v1.equals(v2)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public GlobalMatrixAuthorizationStrategy configure(Object config) throws Exception { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookup(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configure(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } //TODO: Once change is in place for GlobalMatrixAuthentication. Switch away from reflection GlobalMatrixAuthorizationStrategy gms = new GlobalMatrixAuthorizationStrategy(); Field f = gms.getClass().getDeclaredField("grantedPermissions"); f.setAccessible(true); f.set(gms, grantedPermissions); return gms; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public GlobalMatrixAuthorizationStrategy configure(Object config) throws ConfiguratorException { Map map = (Map) config; Collection o = (Collection<?>)map.get("grantedPermissions"); Configurator<GroupPermissionDefinition> permissionConfigurator = Configurator.lookupOrFail(GroupPermissionDefinition.class); Map<Permission,Set<String>> grantedPermissions = new HashMap<>(); for(Object entry : o) { GroupPermissionDefinition gpd = permissionConfigurator.configureNonNull(entry); //We transform the linear list to a matrix (Where permission is the key instead) gpd.grantPermission(grantedPermissions); } //TODO: Once change is in place for GlobalMatrixAuthentication. Switch away from reflection GlobalMatrixAuthorizationStrategy gms = new GlobalMatrixAuthorizationStrategy(); try { Field f = gms.getClass().getDeclaredField("grantedPermissions"); f.setAccessible(true); f.set(gms, grantedPermissions); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new ConfiguratorException(this, "Cannot set GlobalMatrixAuthorizationStrategy#grantedPermissions via reflection", ex); } return gms; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(target); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); mapping.put(names[i], c.describe(args[i])); } return mapping; } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor parameters for sure are part of the description, others // need to be compared with default values. // Build same object with only constructor parameters final Constructor constructor = getDataBoundConstructor(target); final Parameter[] parameters = constructor.getParameters(); final String[] names = ClassDescriptor.loadParameterNames(constructor); final Attribute[] attributes = new Attribute[parameters.length]; final Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { final Parameter p = parameters[i]; final Attribute a = detectActualType(names[i], p.getParameterizedType()); args[i] = a.getValue(instance); attributes[i] = a; } T ref = (T) constructor.newInstance(args); // compare instance with this "default" object Mapping mapping = compare(instance, ref); // add constructor parameters for (int i = 0; i < parameters.length; i++) { final Configurator c = Configurator.lookup(attributes[i].getType()); if (args[i] == null) continue; mapping.put(names[i], attributes[i].describe(args[i])); } return mapping; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = Configurator.lookup(attribute.getType()).configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = Configurator.lookup(attribute.getType()).configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code protected void configure(Map config, T instance) throws Exception { final Set<Attribute> attributes = describe(); for (Attribute attribute : attributes) { final String name = attribute.getName(); final Object sub = removeIgnoreCase(config, name); if (sub != null) { final Class k = attribute.getType(); final Configurator configurator = Configurator.lookup(k); if (configurator == null) throw new IllegalStateException("No configurator implementation to manage "+k); if (attribute.isMultiple()) { List values = new ArrayList<>(); for (Object o : (List) sub) { Object value = configurator.configure(o); values.add(value); } attribute.setValue(instance, values); } else { Object value = configurator.configure(sub); attribute.setValue(instance, value); } } } if (!config.isEmpty()) { final String invalid = StringUtils.join(config.keySet(), ','); throw new IllegalArgumentException("Invalid configuration elements for type " + instance.getClass() + " : " + invalid); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should < %d", index, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dataSbr.release(); return dLegerEntry; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dataSbr.release(); return dLegerEntry; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); //get leger begin index ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); tmpBuffer.getInt(); //magic tmpBuffer.getInt(); //size legerBeginIndex = byteBuffer.getLong(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; } #location 140 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); reviseLegerBeginIndex(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void changeRoleToCandidate(long term) { logger.info("[{}][ChangeRoleToCandidate] from term: {} and currterm: {}", memberState.getSelfId(), term, memberState.currTerm()); memberState.changeToCandidate(term); nextTimeToRequestVote = -1; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void changeRoleToCandidate(long term) { logger.info("[{}][ChangeRoleToCandidate] from term: {} and currterm: {}", memberState.getSelfId(), term, memberState.currTerm()); memberState.changeToCandidate(term); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); //get leger begin index ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); tmpBuffer.getInt(); //magic tmpBuffer.getInt(); //size legerBeginIndex = byteBuffer.getLong(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; } #location 133 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); reviseLegerBeginIndex(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long append(byte[] data, int pos, int len, boolean useBlank) { MmapFile mappedFile = getLastMappedFile(); if (null == mappedFile || mappedFile.isFull()) { mappedFile = getLastMappedFile(0); } if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } int blank = useBlank ? MIN_BLANK_LEN : 0; if (len + blank > mappedFile.getFileSize() - mappedFile.getWrotePosition()) { if (blank < MIN_BLANK_LEN) { logger.error("Blank {} should ge {}", blank, MIN_BLANK_LEN); return -1; } else { ByteBuffer byteBuffer = ByteBuffer.allocate(mappedFile.getFileSize() - mappedFile.getWrotePosition()); byteBuffer.putInt(BLANK_MAGIC_CODE); byteBuffer.putInt(mappedFile.getFileSize() - mappedFile.getWrotePosition()); if (mappedFile.appendMessage(byteBuffer.array())) { //need to set the wrote position mappedFile.setWrotePosition(mappedFile.getFileSize()); } else { logger.error("Append blank error for {}", storePath); return -1; } mappedFile = getLastMappedFile(0); if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } } } long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; } #location 34 #vulnerability type RESOURCE_LEAK
#fixed code public long append(byte[] data, int pos, int len, boolean useBlank) { if (preAppend(len, useBlank) == -1) { return -1; } MmapFile mappedFile = getLastMappedFile(); long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public CompletableFuture<HeartBeatResponse> handleHeartBeat(HeartBeatRequest request) throws Exception { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } } //abnormal case //hold the lock to get the latest term and leaderId synchronized (memberState) { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (memberState.getLeaderId() == null) { changeRoleToFollower(request.getTerm(), request.getLeaderId()); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else { //this should not happen, but if happened logger.error("[{}][BUG] currterm {} has leader {}, but received leader {}", memberState.getSelfId(), memberState.currTerm(), memberState.getLeaderId(), request.getLeaderId()); return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().code(DLegerResponseCode.INTERNAL_ERROR.getCode())); } } else { //To make it simple, for larger term, do not change to follower immediately //first change to candidate, and notify the state-maintainer thread changeRoleToCandidate(request.getTerm()); //TOOD notify return CompletableFuture.completedFuture(new HeartBeatResponse()); } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public CompletableFuture<HeartBeatResponse> handleHeartBeat(HeartBeatRequest request) throws Exception { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } } //abnormal case //hold the lock to get the latest term and leaderId synchronized (memberState) { if (request.getTerm() < memberState.currTerm()) { return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().term(memberState.currTerm()).code(DLegerResponseCode.EXPIRED_TERM.getCode())); } else if (request.getTerm() == memberState.currTerm()) { if (memberState.getLeaderId() == null) { changeRoleToFollower(request.getTerm(), request.getLeaderId()); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else if (request.getLeaderId().equals(memberState.getLeaderId())) { lastLeaderHeartBeatTime = System.currentTimeMillis(); return CompletableFuture.completedFuture(new HeartBeatResponse()); } else { //this should not happen, but if happened logger.error("[{}][BUG] currterm {} has leader {}, but received leader {}", memberState.getSelfId(), memberState.currTerm(), memberState.getLeaderId(), request.getLeaderId()); return CompletableFuture.completedFuture((HeartBeatResponse) new HeartBeatResponse().code(DLegerResponseCode.INCONSISTENT_LEADER.getCode())); } } else { //To make it simple, for larger term, do not change to follower immediately //first change to candidate, and notify the state-maintainer thread changeRoleToCandidate(request.getTerm()); //TOOD notify return CompletableFuture.completedFuture(new HeartBeatResponse()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long append(byte[] data, int pos, int len, boolean useBlank) { MmapFile mappedFile = getLastMappedFile(); if (null == mappedFile || mappedFile.isFull()) { mappedFile = getLastMappedFile(0); } if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } int blank = useBlank ? MIN_BLANK_LEN : 0; if (len + blank > mappedFile.getFileSize() - mappedFile.getWrotePosition()) { if (blank < MIN_BLANK_LEN) { logger.error("Blank {} should ge {}", blank, MIN_BLANK_LEN); return -1; } else { ByteBuffer byteBuffer = ByteBuffer.allocate(mappedFile.getFileSize() - mappedFile.getWrotePosition()); byteBuffer.putInt(BLANK_MAGIC_CODE); byteBuffer.putInt(mappedFile.getFileSize() - mappedFile.getWrotePosition()); if (mappedFile.appendMessage(byteBuffer.array())) { //need to set the wrote position mappedFile.setWrotePosition(mappedFile.getFileSize()); } else { logger.error("Append blank error for {}", storePath); return -1; } mappedFile = getLastMappedFile(0); if (null == mappedFile) { logger.error("Create mapped file for {}", storePath); return -1; } } } long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public long append(byte[] data, int pos, int len, boolean useBlank) { if (preAppend(len, useBlank) == -1) { return -1; } MmapFile mappedFile = getLastMappedFile(); long currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition(); if (!mappedFile.appendMessage(data, pos, len)) { logger.error("Append error for {}", storePath); return -1; } return currPosition; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dataSbr.release(); return dLegerEntry; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId()); SelectMmapBufferResult indexSbr = indexFileQueue.getData(index * INDEX_NUIT_SIZE, INDEX_NUIT_SIZE); PreConditions.check(indexSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); indexSbr.getByteBuffer().getInt(); //magic long pos = indexSbr.getByteBuffer().getLong(); int size = indexSbr.getByteBuffer().getInt(); indexSbr.release(); SelectMmapBufferResult dataSbr = dataFileQueue.getData(pos, size); PreConditions.check(dataSbr.getByteBuffer() != null, DLegerException.Code.DISK_ERROR, null); DLegerEntry dLegerEntry = DLegerEntryCoder.decode(dataSbr.getByteBuffer()); dLegerEntry.setPos(pos); dataSbr.release(); return dLegerEntry; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testThressServer() throws Exception { String group = UUID.randomUUID().toString(); String peers = "n0-localhost:10012;n1-localhost:10013;n2-localhost:10014"; List<DLegerServer> servers = new ArrayList<>(); servers.add(launchServer(group, peers, "n0")); servers.add(launchServer(group, peers, "n1")); servers.add(launchServer(group, peers, "n2")); Thread.sleep(1000); AtomicInteger leaderNum = new AtomicInteger(0); AtomicInteger followerNum = new AtomicInteger(0); DLegerServer leaderServer = parseServers(servers, leaderNum, followerNum); Assert.assertEquals(1, leaderNum.get()); Assert.assertEquals(2, followerNum.get()); Assert.assertNotNull(leaderServer); for (int i = 0; i < 10; i++) { long maxTerm = servers.stream().max((o1, o2) -> { if (o1.getMemberState().currTerm() < o2.getMemberState().currTerm()) { return -1; } else if (o1.getMemberState().currTerm() > o2.getMemberState().currTerm()) { return 1; } else { return 0; } }).get().getMemberState().currTerm(); DLegerServer candidate = servers.get( i % servers.size()); candidate.getdLegerLeaderElector().revote(maxTerm + 1); Thread.sleep(100); leaderNum.set(0); followerNum.set(0); leaderServer = parseServers(servers, leaderNum, followerNum); Assert.assertEquals(1, leaderNum.get()); Assert.assertEquals(2, followerNum.get()); Assert.assertNotNull(leaderServer); Assert.assertTrue(candidate == leaderServer); } //write some data for (int i = 0; i < 5; i++) { AppendEntryRequest appendEntryRequest = new AppendEntryRequest(); appendEntryRequest.setRemoteId(leaderServer.getMemberState().getSelfId()); appendEntryRequest.setBody("Hello Three Server".getBytes()); AppendEntryResponse appendEntryResponse = leaderServer.getdLegerRpcService().append(appendEntryRequest).get(); Assert.assertEquals(DLegerResponseCode.SUCCESS.getCode(), appendEntryResponse.getCode()); } } #location 41 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testThressServer() throws Exception { String group = UUID.randomUUID().toString(); String peers = "n0-localhost:10012;n1-localhost:10013;n2-localhost:10014"; List<DLegerServer> servers = new ArrayList<>(); servers.add(launchServer(group, peers, "n0")); servers.add(launchServer(group, peers, "n1")); servers.add(launchServer(group, peers, "n2")); Thread.sleep(1000); AtomicInteger leaderNum = new AtomicInteger(0); AtomicInteger followerNum = new AtomicInteger(0); DLegerServer leaderServer = parseServers(servers, leaderNum, followerNum); Assert.assertEquals(1, leaderNum.get()); Assert.assertEquals(2, followerNum.get()); Assert.assertNotNull(leaderServer); for (int i = 0; i < 10; i++) { long maxTerm = servers.stream().max((o1, o2) -> { if (o1.getMemberState().currTerm() < o2.getMemberState().currTerm()) { return -1; } else if (o1.getMemberState().currTerm() > o2.getMemberState().currTerm()) { return 1; } else { return 0; } }).get().getMemberState().currTerm(); DLegerServer candidate = servers.get( i % servers.size()); candidate.getdLegerLeaderElector().testRevote(maxTerm + 1); Thread.sleep(100); leaderNum.set(0); followerNum.set(0); leaderServer = parseServers(servers, leaderNum, followerNum); Assert.assertEquals(1, leaderNum.get()); Assert.assertEquals(2, followerNum.get()); Assert.assertNotNull(leaderServer); Assert.assertTrue(candidate == leaderServer); } //write some data for (int i = 0; i < 5; i++) { AppendEntryRequest appendEntryRequest = new AppendEntryRequest(); appendEntryRequest.setRemoteId(leaderServer.getMemberState().getSelfId()); appendEntryRequest.setBody("Hello Three Server".getBytes()); AppendEntryResponse appendEntryResponse = leaderServer.getdLegerRpcService().append(appendEntryRequest).get(); Assert.assertEquals(DLegerResponseCode.SUCCESS.getCode(), appendEntryResponse.getCode()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; } #location 133 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; } int index = mappedFiles.size() - 3; if (index < 0) { index = 0; } long firstEntryIndex = -1; for (int i = index; i >= 0; i--) { index = i; MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); try { int magic = byteBuffer.getInt(); int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); PreConditions.check(magic != MmapFileQueue.BLANK_MAGIC_CODE && magic >= MAGIC_1 && MAGIC_1 <= CURRENT_MAGIC, DLegerException.Code.DISK_ERROR, "unknown magic is " + magic); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(posFromIndex == mappedFile.getFileFromOffset(), DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); firstEntryIndex = entryIndex; break; } catch (Throwable t) { logger.warn("Pre check data and index failed {}", mappedFile.getFileName(), t); } } MmapFile mappedFile = mappedFiles.get(index); ByteBuffer byteBuffer = mappedFile.sliceByteBuffer(); logger.info("Begin to recover data from entryIndex: {} fileIndex: {} fileSize: {} fileName:{} ", firstEntryIndex, index, mappedFiles.size(), mappedFile.getFileName()); long lastEntryIndex = -1; long lastEntryTerm = -1; long processOffset = mappedFile.getFileFromOffset(); boolean needWriteIndex = false; while (true) { try { int relativePos = byteBuffer.position(); long absolutePos = mappedFile.getFileFromOffset() + relativePos; int magic = byteBuffer.getInt(); if (magic == MmapFileQueue.BLANK_MAGIC_CODE) { processOffset = mappedFile.getFileFromOffset() + mappedFile.getFileSize(); index++; if (index >= mappedFiles.size()) { logger.info("Recover data file over, the last file {}", mappedFile.getFileName()); break; } else { mappedFile = mappedFiles.get(index); byteBuffer = mappedFile.sliceByteBuffer(); processOffset = mappedFile.getFileFromOffset(); logger.info("Trying to recover index file {}", mappedFile.getFileName()); continue; } } int size = byteBuffer.getInt(); long entryIndex = byteBuffer.getLong(); long entryTerm = byteBuffer.get(); byteBuffer.position(relativePos + size); String message = String.format("pos: %d size: %d magic:%d index:%d term:%d", absolutePos, size, magic, entryIndex, entryTerm); PreConditions.check(magic <= CURRENT_MAGIC && magic >= MAGIC_1, DLegerException.Code.DISK_ERROR, String.format("%s currMagic: %d", message, CURRENT_MAGIC)); if (lastEntryIndex != -1) { PreConditions.check(entryIndex == lastEntryIndex + 1, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryIndex: %d", message, lastEntryIndex)); } PreConditions.check(entryTerm >= lastEntryTerm, DLegerException.Code.DISK_ERROR, String.format("%s lastEntryTerm: ", message, lastEntryTerm)); PreConditions.check(size > DLegerEntry.HEADER_SIZE, DLegerException.Code.DISK_ERROR, String.format("Size %d should greater than %d", size, DLegerEntry.HEADER_SIZE) ); if (!needWriteIndex) { try { SelectMmapBufferResult indexSbr = indexFileQueue.getData(entryIndex * INDEX_NUIT_SIZE); PreConditions.check(indexSbr != null, DLegerException.Code.DISK_ERROR, String.format("index: %d pos: %d", entryIndex, entryIndex * INDEX_NUIT_SIZE)); indexSbr.release(); ByteBuffer indexByteBuffer = indexSbr.getByteBuffer(); int magicFromIndex = indexByteBuffer.getInt(); long posFromIndex = indexByteBuffer.getLong(); int sizeFromIndex = indexByteBuffer.getInt(); long indexFromIndex = indexByteBuffer.getLong(); long termFromIndex = indexByteBuffer.get(); PreConditions.check(magic == magicFromIndex, DLegerException.Code.DISK_ERROR, String.format("magic %d != %d", magic, magicFromIndex)); PreConditions.check(size == sizeFromIndex, DLegerException.Code.DISK_ERROR, String.format("size %d != %d", size, sizeFromIndex)); PreConditions.check(entryIndex == indexFromIndex, DLegerException.Code.DISK_ERROR, String.format("index %d != %d", entryIndex, indexFromIndex)); PreConditions.check(entryTerm == termFromIndex, DLegerException.Code.DISK_ERROR, String.format("term %d != %d", entryTerm, termFromIndex)); PreConditions.check(absolutePos == posFromIndex, DLegerException.Code.DISK_ERROR, String.format("pos %d != %d", mappedFile.getFileFromOffset(), posFromIndex)); } catch (Exception e) { logger.warn("Compare data to index failed {}", mappedFile.getFileName()); indexFileQueue.truncateDirtyFiles(entryIndex * INDEX_NUIT_SIZE); if (indexFileQueue.getMaxWrotePosition() != entryIndex * INDEX_NUIT_SIZE) { logger.warn("Unexpected wrote position in index file {} != {}", indexFileQueue.getMaxWrotePosition(), entryIndex * INDEX_NUIT_SIZE); indexFileQueue.truncateDirtyFiles(0); } if (indexFileQueue.getMappedFiles().isEmpty()) { indexFileQueue.getLastMappedFile(entryIndex * INDEX_NUIT_SIZE); } needWriteIndex = true; } } if (needWriteIndex) { ByteBuffer indexBuffer = localIndexBuffer.get(); DLegerEntryCoder.encodeIndex(absolutePos, size, magic, entryIndex, entryTerm, indexBuffer); long indexPos = indexFileQueue.append(indexBuffer.array(), 0, indexBuffer.remaining()); PreConditions.check(indexPos == entryIndex * INDEX_NUIT_SIZE, DLegerException.Code.DISK_ERROR, String.format("Write index failed index: %d", entryIndex)); } lastEntryIndex = entryIndex; lastEntryTerm = entryTerm; processOffset += size; } catch (Throwable t) { logger.info("Recover data file to the end of {} ", mappedFile.getFileName(), t); break; } } logger.info("Recover data to the end entryIndex:{} processOffset:{}", lastEntryIndex, processOffset); legerEndIndex = lastEntryIndex; legerEndTerm = lastEntryTerm; if (lastEntryIndex != -1) { DLegerEntry entry = get(lastEntryIndex); PreConditions.check(entry != null, DLegerException.Code.DISK_ERROR, "recheck get null entry"); PreConditions.check(entry.getIndex() == lastEntryIndex, DLegerException.Code.DISK_ERROR, String.format("recheck index %d != %d", entry.getIndex(), lastEntryIndex)); //get leger begin index ByteBuffer tmpBuffer = dataFileQueue.getFirstMappedFile().sliceByteBuffer(); tmpBuffer.getInt(); //magic tmpBuffer.getInt(); //size legerBeginIndex = byteBuffer.getLong(); } else { processOffset = 0; } this.dataFileQueue.updateWherePosition(processOffset); this.dataFileQueue.truncateDirtyFiles(processOffset); long indexProcessOffset = (lastEntryIndex + 1) * INDEX_NUIT_SIZE; this.indexFileQueue.updateWherePosition(indexProcessOffset); this.indexFileQueue.truncateDirtyFiles(indexProcessOffset); return; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private InputStream buildWrappedInputStream(InputStream downloadInputStream) throws TransformerException, IOException { // Pass the download input stream through a transformer that removes the XML // declaration. Transformer omitXmlDeclarationTransformer = getTransformer(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(outputStream); Source xmlSource = new StreamSource(downloadInputStream); omitXmlDeclarationTransformer.transform(xmlSource, streamResult); return ByteSource.concat( ByteSource.wrap(SOAP_START_BODY.getBytes()), ByteSource.wrap(outputStream.toByteArray()), ByteSource.wrap(SOAP_END_BODY.getBytes())).openStream(); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private InputStream buildWrappedInputStream(InputStream downloadInputStream) throws TransformerException, IOException { // Pass the download input stream through a Transformer that removes the XML // declaration. Create a new TransformerFactory and Transformer on each invocation // since these objects are <em>not</em> thread safe. Transformer omitXmlDeclarationTransformer = TransformerFactory.newInstance().newTransformer(); omitXmlDeclarationTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); omitXmlDeclarationTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); omitXmlDeclarationTransformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", INDENT_AMOUNT); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(outputStream); Source xmlSource = new StreamSource(downloadInputStream); omitXmlDeclarationTransformer.transform(xmlSource, streamResult); return ByteSource.concat( ByteSource.wrap(SOAP_START_BODY.getBytes()), ByteSource.wrap(outputStream.toByteArray()), ByteSource.wrap(SOAP_END_BODY.getBytes())).openStream(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMarkNotSupported() throws Exception { byte[] plaintext = getRandomBytes(1); final String password = "Testing1234"; JNCryptor cryptor = new AES256JNCryptor(); byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( data), password.toCharArray()); assertFalse(in.markSupported()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testMarkNotSupported() throws Exception { byte[] plaintext = getRandomBytes(1); final String password = "Testing1234"; JNCryptor cryptor = new AES256JNCryptor(); byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( data), password.toCharArray()); assertFalse(in.markSupported()); in.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String getLine(File file, int line) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String msg = ""; for (int i = 0; i <= line; i++) msg = reader.readLine(); reader.close(); return msg; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private static String getLine(File file, int line) throws IOException { BufferedReader reader = Files.newBufferedReader(file.toPath(), Options.encoding); String msg = ""; for (int i = 0; i <= line; i++) msg = reader.readLine(); reader.close(); return msg; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected static ClassInfo guessPackageAndClass(File lexFile) throws FileNotFoundException, IOException { assert lexFile.isAbsolute() : lexFile; LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); ClassInfo classInfo = new ClassInfo(); while (classInfo.className == null || classInfo.packageName == null) { String line = reader.readLine(); if (line == null) break; if (classInfo.packageName == null) { int index = line.indexOf("package"); if (index >= 0) { index += 7; int end = line.indexOf(';', index); if (end >= index) { classInfo.packageName = line.substring(index, end); classInfo.packageName = classInfo.packageName.trim(); } } } if (classInfo.className == null) { int index = line.indexOf("%class"); if (index >= 0) { index += 6; classInfo.className = line.substring(index); classInfo.className = classInfo.className.trim(); } } } if (classInfo.className == null) { classInfo.className = DEFAULT_NAME; } return classInfo; } #location 38 #vulnerability type RESOURCE_LEAK
#fixed code protected static ClassInfo guessPackageAndClass(File lexFile) throws FileNotFoundException, IOException { assert lexFile.isAbsolute() : lexFile; LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); try { ClassInfo classInfo = new ClassInfo(); while (classInfo.className == null || classInfo.packageName == null) { String line = reader.readLine(); if (line == null) break; if (classInfo.packageName == null) { int index = line.indexOf("package"); if (index >= 0) { index += 7; int end = line.indexOf(';', index); if (end >= index) { classInfo.packageName = line.substring(index, end); classInfo.packageName = classInfo.packageName.trim(); } } } if (classInfo.className == null) { int index = line.indexOf("%class"); if (index >= 0) { index += 6; classInfo.className = line.substring(index); classInfo.className = classInfo.className.trim(); } } } if (classInfo.className == null) { classInfo.className = DEFAULT_NAME; } return classInfo; } finally { reader.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String getPageContent(URL url) throws IOException { InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private String getPageContent(URL url) throws IOException { try(InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8")) { StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void runNext() throws TestFailException { // Get first file and remove it from vector InputOutput current = inputOutput.remove(0); // Create List with only first input in List<String> param = new ArrayList<String>(); param.add(current.getName() + ".input"); // Excute Main on that input classExecResult = Exec.execClass (className, testPath.toString(), new ArrayList<String>(), param, Main.jflexTestVersion); if (Main.verbose) { System.out.println("Running scanner on [" + current.getName() + "]"); } // check for output conformance File expected = new File(current.getName() + ".output"); if (expected.exists()) { DiffStream check = new DiffStream(); String diff; try { diff = check.diff(jflexDiff, new StringReader(classExecResult.getOutput()), new FileReader(expected)); } catch (FileNotFoundException e) { System.out.println("Error opening file " + expected); throw new TestFailException(); } if (diff != null) { System.out.println("Test failed, unexpected output: " + diff); System.out.println("Test output: " + classExecResult.getOutput()); throw new TestFailException(); } } else { System.out.println("Warning: no file for expected output [" + expected + "]"); } // System.out.println(classExecResult); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public void runNext() throws TestFailException, UnsupportedEncodingException { // Get first file and remove it from vector InputOutput current = inputOutput.remove(0); // Create List with only first input in List<String> param = new ArrayList<String>(); param.add(current.getName() + ".input"); // Excute Main on that input classExecResult = Exec.execClass (className, testPath.toString(), new ArrayList<String>(), param, Main.jflexTestVersion, outputFileEncoding); if (Main.verbose) { System.out.println("Running scanner on [" + current.getName() + "]"); } // check for output conformance File expected = new File(current.getName() + ".output"); if (expected.exists()) { DiffStream check = new DiffStream(); String diff; try { diff = check.diff(jflexDiff, new StringReader(classExecResult.getOutput()), new InputStreamReader(new FileInputStream(expected), outputFileEncoding)); } catch (FileNotFoundException e) { System.out.println("Error opening file " + expected); throw new TestFailException(); } catch (UnsupportedEncodingException e) { System.out.println("Unsupported encoding '" + outputFileEncoding + "'"); throw new TestFailException(); } if (diff != null) { System.out.println("Test failed, unexpected output: " + diff); System.out.println("Test output: " + classExecResult.getOutput()); throw new TestFailException(); } } else { System.out.println("Warning: no file for expected output [" + expected + "]"); } // System.out.println(classExecResult); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) return null; size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) return null; byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) { zipFile.close(); return null; } size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) { zipFile.close(); return null; } byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void findPackageAndClass() throws IOException { // find name of the package and class in jflex source file packageName = null; className = null; LineNumberReader reader = new LineNumberReader(new FileReader(inputFile)); while (className == null || packageName == null) { String line = reader.readLine(); if (line == null) break; if (packageName == null) { Matcher matcher = PACKAGE_PATTERN.matcher(line); if (matcher.find()) { packageName = matcher.group(1); } } if (className == null) { Matcher matcher = CLASS_PATTERN.matcher(line); if (matcher.find()) { className = matcher.group(1); } } } // package name may be null, but class name not if (className == null) className = "Yylex"; } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code public void findPackageAndClass() throws IOException { // find name of the package and class in jflex source file packageName = null; className = null; LineNumberReader reader = new LineNumberReader(new FileReader(inputFile)); try { while (className == null || packageName == null) { String line = reader.readLine(); if (line == null) break; if (packageName == null) { Matcher matcher = PACKAGE_PATTERN.matcher(line); if (matcher.find()) { packageName = matcher.group(1); } } if (className == null) { Matcher matcher = CLASS_PATTERN.matcher(line); if (matcher.find()) { className = matcher.group(1); } } } // package name may be null, but class name not if (className == null) { className = "Yylex"; } } finally { reader.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) return null; size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) return null; byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) { zipFile.close(); return null; } size = (int) entry.getSize(); } catch (IOException io) { return null; } InputStream stream = null; try { stream = zipFile.getInputStream(entry); if (stream == null) { zipFile.close(); return null; } byte[] data = new byte[size]; int pos = 0; while (pos < size) { int n = stream.read(data, pos, data.length - pos); pos += n; } zipFile.close(); return data; } catch (IOException e) { } finally { try { if (stream != null) stream.close(); } catch (IOException e) { } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void read(String skeletonFilename) throws Exception { ClassLoader loader = UnicodePropertiesSkeleton.class.getClassLoader(); URL url = loader.getResource(skeletonFilename); if (null == url) { throw new Exception("Cannot locate '" + skeletonFilename + "' - aborting."); } String line; StringBuilder section = new StringBuilder(); BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream(), "UTF-8")); while (null != (line = reader.readLine())) { if (line.startsWith("---")) { sections.add(section.toString()); section.setLength(0); } else { section.append(line); section.append(NL); } } if (section.length() > 0) { sections.add(section.toString()); } if (sections.size() != size) { throw new Exception("Skeleton file '" + skeletonFilename + "' has " + sections.size() + " static sections, but " + size + " were expected."); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public void read(String skeletonFilename) throws Exception { ClassLoader loader = UnicodePropertiesSkeleton.class.getClassLoader(); URL url = loader.getResource(skeletonFilename); if (null == url) { throw new Exception("Cannot locate '" + skeletonFilename + "' - aborting."); } String line; StringBuilder section = new StringBuilder(); try (BufferedReader reader = new BufferedReader (new InputStreamReader(url.openStream(), "UTF-8"))) { while (null != (line = reader.readLine())) { if (line.startsWith("---")) { sections.add(section.toString()); section.setLength(0); } else { section.append(line); section.append(NL); } } if (section.length() > 0) { sections.add(section.toString()); } if (sections.size() != size) { throw new Exception("Skeleton file '" + skeletonFilename + "' has " + sections.size() + " static sections, but " + size + " were expected."); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private InputStream getZipEntryStream(String file, String entryName) { try { ZipFile zip = new ZipFile(new File(file)); ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code private InputStream getZipEntryStream(String file, String entryName) { try (ZipFile zip = new ZipFile(new File(file))) { ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String getPageContent(URL url) throws IOException { InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8"); StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private String getPageContent(URL url) throws IOException { try(InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8")) { StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int charsRead; while ((charsRead = reader.read(buf)) > 0) { builder.append(buf, 0, charsRead); } return builder.toString(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private InputStream getZipEntryStream(String file, String entryName) { try { ZipFile zip = new ZipFile(new File(file)); ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code private InputStream getZipEntryStream(String file, String entryName) { try (ZipFile zip = new ZipFile(new File(file))) { ZipEntry entry = zip.getEntry(entryName); if (entry == null) return null; return zip.getInputStream(entry); } catch (IOException e) { return null; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected static ClassInfo guessPackageAndClass(File lexFile) throws FileNotFoundException, IOException { assert lexFile.isAbsolute() : lexFile; LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); ClassInfo classInfo = new ClassInfo(); while (classInfo.className == null || classInfo.packageName == null) { String line = reader.readLine(); if (line == null) break; if (classInfo.packageName == null) { int index = line.indexOf("package"); if (index >= 0) { index += 7; int end = line.indexOf(';', index); if (end >= index) { classInfo.packageName = line.substring(index, end); classInfo.packageName = classInfo.packageName.trim(); } } } if (classInfo.className == null) { int index = line.indexOf("%class"); if (index >= 0) { index += 6; classInfo.className = line.substring(index); classInfo.className = classInfo.className.trim(); } } } if (classInfo.className == null) { classInfo.className = DEFAULT_NAME; } return classInfo; } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code protected static ClassInfo guessPackageAndClass(File lexFile) throws FileNotFoundException, IOException { assert lexFile.isAbsolute() : lexFile; LineNumberReader reader = new LineNumberReader(new FileReader(lexFile)); try { ClassInfo classInfo = new ClassInfo(); while (classInfo.className == null || classInfo.packageName == null) { String line = reader.readLine(); if (line == null) break; if (classInfo.packageName == null) { int index = line.indexOf("package"); if (index >= 0) { index += 7; int end = line.indexOf(';', index); if (end >= index) { classInfo.packageName = line.substring(index, end); classInfo.packageName = classInfo.packageName.trim(); } } } if (classInfo.className == null) { int index = line.indexOf("%class"); if (index >= 0) { index += 6; classInfo.className = line.substring(index); classInfo.className = classInfo.className.trim(); } } } if (classInfo.className == null) { classInfo.className = DEFAULT_NAME; } return classInfo; } finally { reader.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void copyTo(Wire wire) { while (bytes.remaining() > 0) { int code = bytes.readUnsignedByte(); switch (code >> 4) { case NUM0: case NUM1: case NUM2: case NUM3: case NUM4: case NUM5: case NUM6: case NUM7: writeValue.uint8(code); break; case CONTROL: break; case FLOAT: double d = readFloat(code); writeValue.float64(d); break; case INT: long l = readInt(code); writeValue.int64(l); break; case SPECIAL: copySpecial(code); break; case FIELD0: case FIELD1: StringBuilder fsb = readField(code, Wires.acquireStringBuilder()); writeField(fsb); break; case STR0: case STR1: StringBuilder sb = readText(code, Wires.acquireStringBuilder()); writeValue.text(sb); break; } } } #location 37 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void copyTo(Wire wire) { while (bytes.remaining() > 0) { int code = bytes.readUnsignedByte(); switch (code >> 4) { case NUM0: case NUM1: case NUM2: case NUM3: case NUM4: case NUM5: case NUM6: case NUM7: wire.writeValue().uint8(code); break; case CONTROL: break; case FLOAT: double d = readFloat(code); wire.writeValue().float64(d); break; case INT: long l = readInt(code); wire.writeValue().int64(l); break; case SPECIAL: copySpecial(wire, code); break; case FIELD0: case FIELD1: bytes.skip(-1); StringBuilder fsb = readField(code, Wires.acquireStringBuilder()); wire.write(fsb, null); break; case STR0: case STR1: bytes.skip(-1); StringBuilder sb = readText(code, Wires.acquireStringBuilder()); wire.writeValue().text(sb); break; } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean readOne() { for (; ; ) { try (DocumentContext context = in.readingDocument()) { if (!context.isPresent()) return false; if (context.isMetaData()) { StringBuilder sb = Wires.acquireStringBuilder(); long r = context.wire().bytes().readPosition(); try { context.wire().readEventName(sb); for (String s : metaIgnoreList) { // we wish to ignore our system meta data field if (s.contentEquals(sb)) return false; } } finally { // roll back position to where is was before we read the SB context.wire().bytes().readPosition(r); } wireParser.accept(context.wire()); return true; } if (!context.isData()) continue; MessageHistory history = messageHistory; history.reset(context.sourceId(), context.index()); wireParser.accept(context.wire()); } return true; } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean readOne() { try (DocumentContext context = in.readingDocument()) { if (!context.isPresent()) return false; if (context.isMetaData()) return readOneMetaData(context); assert context.isData(); messageHistory.reset(context.sourceId(), context.index()); wireParser.accept(context.wire()); } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setupOrTeardown(DbUnitTestContext testContext, boolean isSetup, Collection<AnnotationAttributes> annotations) throws Exception { IDatabaseConnection connection = testContext.getConnection(); DatabaseOperation lastOperation = null; for (AnnotationAttributes annotation : annotations) { for (String dataSetLocation : annotation.getValue()) { DatabaseOperation operation = annotation.getType(); org.dbunit.operation.DatabaseOperation dbUnitDatabaseOperation = getDbUnitDatabaseOperation( testContext, operation, lastOperation); IDataSet dataSet = loadDataset(testContext, dataSetLocation); if (dataSet != null) { if (logger.isDebugEnabled()) { logger.debug("Executing " + (isSetup ? "Setup" : "Teardown") + " of @DatabaseTest using " + operation + " on " + dataSetLocation); } dbUnitDatabaseOperation.execute(connection, dataSet); lastOperation = operation; } } } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code private void setupOrTeardown(DbUnitTestContext testContext, boolean isSetup, Collection<AnnotationAttributes> annotations) throws Exception { IDatabaseConnection connection = testContext.getConnection(); for (AnnotationAttributes annotation : annotations) { List<IDataSet> datasets = loadDataSets(testContext, annotation); DatabaseOperation operation = annotation.getType(); org.dbunit.operation.DatabaseOperation dbUnitOperation = getDbUnitDatabaseOperation(testContext, operation); if (!datasets.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("Executing " + (isSetup ? "Setup" : "Teardown") + " of @DatabaseTest using " + operation + " on " + datasets.toString()); } IDataSet dataSet = new CompositeDataSet(datasets.toArray(new IDataSet[datasets.size()])); dbUnitOperation.execute(connection, dataSet); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ListenableFuture<IBigQueue> queueReadyForDequeue() { futureLock.lock(); if (dequeueFuture == null || dequeueFuture.isDone() || dequeueFuture.isCancelled()) { dequeueFuture = SettableFuture.create(); } futureLock.unlock(); return dequeueFuture; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public ListenableFuture<IBigQueue> queueReadyForDequeue() { initializeFutureIfNecessary(); return dequeueFuture; }
Below is the vulnerable code, please generate the patch based on the following information.