input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); int i = 0; BufferedReader input = new BufferedReader(new InputStreamReader(stream, ASCII)); CharacterReader reader = new CharacterReader(input); while (!reader.isEmpty()) { // NotNestedLessLess=10913,824;1887 final String name = reader.consumeTo('='); reader.advance(); final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix); final char codeDelim = reader.current(); reader.advance(); final int cp2; if (codeDelim == ',') { cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix); reader.advance(); } else { cp2 = empty; } String indexS = reader.consumeTo('\n'); // default git checkout on windows will add a \r there, so remove if (indexS.charAt(indexS.length() - 1) == '\r') { indexS = indexS.substring(0, indexS.length() - 1); } final int index = Integer.parseInt(indexS, codepointRadix); reader.advance(); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file); } #location 48 #vulnerability type RESOURCE_LEAK
#fixed code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); int i = 0; BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(stream, ASCII)); CharacterReader reader = new CharacterReader(input); while (!reader.isEmpty()) { // NotNestedLessLess=10913,824;1887 final String name = reader.consumeTo('='); reader.advance(); final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix); final char codeDelim = reader.current(); reader.advance(); final int cp2; if (codeDelim == ',') { cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix); reader.advance(); } else { cp2 = empty; } String indexS = reader.consumeTo('\n'); // default git checkout on windows will add a \r there, so remove if (indexS.charAt(indexS.length() - 1) == '\r') { indexS = indexS.substring(0, indexS.length() - 1); } final int index = Integer.parseInt(indexS, codepointRadix); reader.advance(); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } } finally { try { if (input != null) { input.close(); } } catch (IOException e1) { //ignore exception } } Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void outerHtml(StringBuilder accum) { new NodeTraversor(new OuterHtmlVisitor(accum, ownerDocument().outputSettings())).traverse(this); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code protected void outerHtml(StringBuilder accum) { new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings())).traverse(this); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean matchesWord() { return !isEmpty() && Character.isLetterOrDigit(peek()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean matchesWord() { return !isEmpty() && Character.isLetterOrDigit(queue.charAt(pos)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); Element element1 = doc.getElementById("c"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNull(elementSiblings1); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<ul id='ul'>" + "<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>" + "</ul>" + "<div id='div'>" + "<li id='d'>d</li>" + "</div>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); assertEquals("b", elementSiblings.get(0).id()); assertEquals("c", elementSiblings.get(1).id()); Element element1 = doc.getElementById("b"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNotNull(elementSiblings1); assertEquals(1, elementSiblings1.size()); assertEquals("c", elementSiblings1.get(0).id()); Element element2 = doc.getElementById("c"); List<Element> elementSiblings2 = element2.nextElementSiblings(); assertEquals(0, elementSiblings2.size()); Element ul = doc.getElementById("ul"); List<Element> elementSiblings3 = ul.nextElementSiblings(); assertNotNull(elementSiblings3); assertEquals(1, elementSiblings3.size()); assertEquals("div", elementSiblings3.get(0).id()); Element div = doc.getElementById("div"); List<Element> elementSiblings4 = div.nextElementSiblings(); try { Element elementSibling = elementSiblings4.get(0); fail("This element should has no next siblings"); } catch (IndexOutOfBoundsException e) { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(select("html").first()); normalise(this); return this; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public Document normalise() { Element htmlEl = findFirstElementByTagName("html", this); if (htmlEl == null) htmlEl = appendElement("html"); if (head() == null) htmlEl.prependElement("head"); if (body() == null) htmlEl.appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(htmlEl); normalise(this); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void removeChild(Node out) { Validate.isTrue(out.parentNode == this); int index = indexInList(out, childNodes); childNodes.remove(index); out.parentNode = null; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code protected void removeChild(Node out) { Validate.isTrue(out.parentNode == this); int index = out.siblingIndex(); childNodes.remove(index); reindexChildren(); out.parentNode = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); Element element1 = doc.getElementById("c"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNull(elementSiblings1); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testNextElementSiblings() { Document doc = Jsoup.parse("<ul id='ul'>" + "<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>" + "</ul>" + "<div id='div'>" + "<li id='d'>d</li>" + "</div>"); Element element = doc.getElementById("a"); List<Element> elementSiblings = element.nextElementSiblings(); assertNotNull(elementSiblings); assertEquals(2, elementSiblings.size()); assertEquals("b", elementSiblings.get(0).id()); assertEquals("c", elementSiblings.get(1).id()); Element element1 = doc.getElementById("b"); List<Element> elementSiblings1 = element1.nextElementSiblings(); assertNotNull(elementSiblings1); assertEquals(1, elementSiblings1.size()); assertEquals("c", elementSiblings1.get(0).id()); Element element2 = doc.getElementById("c"); List<Element> elementSiblings2 = element2.nextElementSiblings(); assertEquals(0, elementSiblings2.size()); Element ul = doc.getElementById("ul"); List<Element> elementSiblings3 = ul.nextElementSiblings(); assertNotNull(elementSiblings3); assertEquals(1, elementSiblings3.size()); assertEquals("div", elementSiblings3.get(0).id()); Element div = doc.getElementById("div"); List<Element> elementSiblings4 = div.nextElementSiblings(); try { Element elementSibling = elementSiblings4.get(0); fail("This element should has no next siblings"); } catch (IndexOutOfBoundsException e) { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); int i = 0; BufferedReader input = new BufferedReader(new InputStreamReader(stream, ASCII)); CharacterReader reader = new CharacterReader(input); while (!reader.isEmpty()) { // NotNestedLessLess=10913,824;1887 final String name = reader.consumeTo('='); reader.advance(); final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix); final char codeDelim = reader.current(); reader.advance(); final int cp2; if (codeDelim == ',') { cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix); reader.advance(); } else { cp2 = empty; } String indexS = reader.consumeTo('\n'); // default git checkout on windows will add a \r there, so remove if (indexS.charAt(indexS.length() - 1) == '\r') { indexS = indexS.substring(0, indexS.length() - 1); } final int index = Integer.parseInt(indexS, codepointRadix); reader.advance(); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); int i = 0; BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(stream, ASCII)); CharacterReader reader = new CharacterReader(input); while (!reader.isEmpty()) { // NotNestedLessLess=10913,824;1887 final String name = reader.consumeTo('='); reader.advance(); final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix); final char codeDelim = reader.current(); reader.advance(); final int cp2; if (codeDelim == ',') { cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix); reader.advance(); } else { cp2 = empty; } String indexS = reader.consumeTo('\n'); // default git checkout on windows will add a \r there, so remove if (indexS.charAt(indexS.length() - 1) == '\r') { indexS = indexS.substring(0, indexS.length() - 1); } final int index = Integer.parseInt(indexS, codepointRadix); reader.advance(); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } } finally { try { if (input != null) { input.close(); } } catch (IOException e1) { //ignore exception } } Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void insert(Token.Character characterToken) { final Node node; final Element el = currentElement(); final String tagName = el.normalName(); final String data = characterToken.getData(); if (characterToken.isCData()) node = new CDataNode(data); else if (tagName.equals("script") || tagName.equals("style")) node = new DataNode(data); else node = new TextNode(data); el.appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code ParseSettings defaultSettings() { return ParseSettings.htmlDefault; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void outerHtml(StringBuilder accum) { String html = StringEscapeUtils.escapeHtml(getWholeText()); if (parent() instanceof Element && !((Element) parent()).preserveWhitespace()) { html = normaliseWhitespace(html); } if (siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().canContainBlock() && !isBlank()) indent(accum); accum.append(html); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code void outerHtmlHead(StringBuilder accum, int depth) { String html = StringEscapeUtils.escapeHtml(getWholeText()); if (parent() instanceof Element && !((Element) parent()).preserveWhitespace()) { html = normaliseWhitespace(html); } if (siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().canContainBlock() && !isBlank()) indent(accum, depth); accum.append(html); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Document load(File in, String charsetName, String baseUri) throws IOException { InputStream inStream = new FileInputStream(in); ByteBuffer byteData = readToByteBuffer(inStream); Document doc = parseByteData(byteData, charsetName, baseUri); inStream.close(); return doc; } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public static Document load(File in, String charsetName, String baseUri) throws IOException { InputStream inStream = null; try { inStream = new FileInputStream(in); ByteBuffer byteData = readToByteBuffer(inStream); return parseByteData(byteData, charsetName, baseUri); } finally { if (inStream != null) inStream.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String consumeCssIdentifier() { StringBuilder accum = new StringBuilder(); Character c = peek(); while (!isEmpty() && (Character.isLetterOrDigit(c) || c.equals('-') || c.equals('_'))) { accum.append(consume()); c = peek(); } return accum.toString(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public String consumeCssIdentifier() { int start = pos; while (!isEmpty() && (matchesWord() || matchesAny('-', '_'))) pos++; return queue.substring(start, pos); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void replaceChild(Node out, Node in) { Validate.isTrue(out.parentNode == this); Validate.notNull(in); if (in.parentNode != null) in.parentNode.removeChild(in); Integer index = indexInList(out, childNodes); childNodes.set(index, in); in.parentNode = this; out.parentNode = null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code protected void replaceChild(Node out, Node in) { Validate.isTrue(out.parentNode == this); Validate.notNull(in); if (in.parentNode != null) in.parentNode.removeChild(in); Integer index = out.siblingIndex(); childNodes.set(index, in); in.parentNode = this; in.setSiblingIndex(index); out.parentNode = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void addChildren(int index, Node... children) { Validate.noNullElements(children); final List<Node> nodes = ensureChildNodes(); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code protected void addChildren(int index, Node... children) { Validate.notNull(children); if (children.length == 0) { return; } final List<Node> nodes = ensureChildNodes(); // fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace final Node firstParent = children[0].parent(); if (firstParent != null && firstParent.childNodeSize() == children.length) { boolean sameList = true; final List<Node> firstParentNodes = firstParent.childNodes(); // identity check contents to see if same int i = children.length; while (i-- > 0) { if (children[i] != firstParentNodes.get(i)) { sameList = false; break; } } firstParent.empty(); nodes.addAll(index, Arrays.asList(children)); i = children.length; while (i-- > 0) { children[i].parentNode = this; } reindexChildren(index); return; } Validate.noNullElements(children); for (Node child : children) { reparentChild(child); } nodes.addAll(index, Arrays.asList(children)); reindexChildren(index); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);? StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } // skip } else { String name = m.group(1).toLowerCase(); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { // out of range String c = Character.toString((char) charval); m.appendReplacement(accum, c); } else { m.appendReplacement(accum, m.group(0)); // replace with original string } } m.appendTail(accum); return accum.toString(); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);? StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } // skip } else { String name = m.group(1); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { // out of range String c = Character.toString((char) charval); m.appendReplacement(accum, c); } else { m.appendReplacement(accum, m.group(0)); // replace with original string } } m.appendTail(accum); return accum.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String entry; int i = 0; try { while ((entry = reader.readLine()) != null) { // NotNestedLessLess=10913,824;1887 final Matcher match = entityPattern.matcher(entry); if (match.find()) { final String name = match.group(1); final int cp1 = Integer.parseInt(match.group(2), codepointRadix); final int cp2 = match.group(3) != null ? Integer.parseInt(match.group(3), codepointRadix) : empty; final int index = Integer.parseInt(match.group(4), codepointRadix); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } } reader.close(); } catch (IOException err) { throw new IllegalStateException("Error reading resource " + file); } } #location 36 #vulnerability type RESOURCE_LEAK
#fixed code private static void load(EscapeMode e, String file, int size) { e.nameKeys = new String[size]; e.codeVals = new int[size]; e.codeKeys = new int[size]; e.nameVals = new String[size]; InputStream stream = Entities.class.getResourceAsStream(file); if (stream == null) throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName()); int i = 0; try { ByteBuffer bytes = DataUtil.readToByteBuffer(stream, 0); String contents = Charset.forName("ascii").decode(bytes).toString(); CharacterReader reader = new CharacterReader(contents); while (!reader.isEmpty()) { // NotNestedLessLess=10913,824;1887 final String name = reader.consumeTo('='); reader.advance(); final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix); final char codeDelim = reader.current(); reader.advance(); final int cp2; if (codeDelim == ',') { cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix); reader.advance(); } else { cp2 = empty; } final int index = Integer.parseInt(reader.consumeTo('\n'), codepointRadix); reader.advance(); e.nameKeys[i] = name; e.codeVals[i] = cp1; e.codeKeys[index] = cp1; e.nameVals[index] = name; if (cp2 != empty) { multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2)); } i++; } } catch (IOException err) { throw new IllegalStateException("Error reading resource " + file); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void parseStartTag() { tq.consume("<"); Attributes attributes = new Attributes(); String tagName = tq.consumeWord(); while (!tq.matches("<") && !tq.matches("/>") && !tq.matches(">") && !tq.isEmpty()) { Attribute attribute = parseAttribute(); if (attribute != null) attributes.put(attribute); } Tag tag = Tag.valueOf(tagName); StartTag startTag = new StartTag(tag, attributes); Element child = new Element(startTag); boolean emptyTag; if (tq.matchChomp("/>")) { // empty tag, don't add to stack emptyTag = true; } else { tq.matchChomp(">"); // safe because checked above (or ran out of data) emptyTag = false; } // pc data only tags (textarea, script): chomp to end tag, add content as text node if (tag.isData()) { String data = tq.chompTo("</" + tagName); tq.chompTo(">"); TextNode textNode = TextNode.createFromEncoded(data); child.addChild(textNode); if (tag.equals(titleTag)) doc.setTitle(child.text()); } // switch between html, head, body, to preserve doc structure if (tag.equals(htmlTag)) { doc.getAttributes().mergeAttributes(attributes); } else if (tag.equals(headTag)) { doc.getHead().getAttributes().mergeAttributes(attributes); // head is on stack from start, no action required } else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) { // switch to body stack.removeLast(); stack.addLast(doc.getBody()); last().addChild(child); if (!emptyTag) stack.addLast(child); } else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) { doc.getBody().getAttributes().mergeAttributes(attributes); stack.removeLast(); stack.addLast(doc.getBody()); } else { Element parent = popStackToSuitableContainer(tag); parent.addChild(child); if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head stack.addLast(child); } } #location 54 #vulnerability type NULL_DEREFERENCE
#fixed code private void parseStartTag() { tq.consume("<"); Attributes attributes = new Attributes(); String tagName = tq.consumeWord(); while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) { Attribute attribute = parseAttribute(); if (attribute != null) attributes.put(attribute); } Tag tag = Tag.valueOf(tagName); StartTag startTag = new StartTag(tag, attributes); Element child = new Element(startTag); boolean emptyTag; if (tq.matchChomp("/>")) { // empty tag, don't add to stack emptyTag = true; } else { tq.matchChomp(">"); // safe because checked above (or ran out of data) emptyTag = false; } // pc data only tags (textarea, script): chomp to end tag, add content as text node if (tag.isData()) { String data = tq.chompTo("</" + tagName); tq.chompTo(">"); TextNode textNode = TextNode.createFromEncoded(data); // TODO: maybe have this be another data type? So doesn't come back in text()? child.addChild(textNode); if (tag.equals(titleTag)) doc.setTitle(child.text()); } // switch between html, head, body, to preserve doc structure if (tag.equals(htmlTag)) { doc.getAttributes().mergeAttributes(attributes); } else if (tag.equals(headTag)) { doc.getHead().getAttributes().mergeAttributes(attributes); // head is on stack from start, no action required } else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) { // switch to body stack.removeLast(); stack.addLast(doc.getBody()); last().addChild(child); if (!emptyTag) stack.addLast(child); } else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) { doc.getBody().getAttributes().mergeAttributes(attributes); stack.removeLast(); stack.addLast(doc.getBody()); } else { Element parent = popStackToSuitableContainer(tag); parent.addChild(child); if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head stack.addLast(child); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String ihVal(String key, Document doc) { return doc.select("th:contains(" + key + ") + td").first().text(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code private static String ihVal(String key, Document doc) { final Element first = doc.select("th:contains(" + key + ") + td").first(); return first != null ? first.text() : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException { if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) )) indent(accum, depth, out); boolean normaliseWhite = out.prettyPrint() && !Element.preserveWhitespace(parent()); Entities.escape(accum, coreValue(), out, false, normaliseWhite, false); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException { final boolean prettyPrint = out.prettyPrint(); if (prettyPrint && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) )) indent(accum, depth, out); final boolean normaliseWhite = prettyPrint && !Element.preserveWhitespace(parentNode); final boolean stripWhite = prettyPrint && parentNode instanceof Document; Entities.escape(accum, coreValue(), out, false, normaliseWhite, stripWhite); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNamespace() throws Exception { final String namespace = "TestNamespace"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); client.start(); try { String actualPath = client.create().forPath("/test", new byte[0]); Assert.assertEquals(actualPath, "/test"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false)); Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/test", false)); actualPath = client.nonNamespaceView().create().forPath("/non", new byte[0]); Assert.assertEquals(actualPath, "/non"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/non", false)); client.create().forPath("/test/child", "hey".getBytes()); byte[] bytes = client.getData().forPath("/test/child"); Assert.assertEquals(bytes, "hey".getBytes()); bytes = client.nonNamespaceView().getData().forPath("/" + namespace + "/test/child"); Assert.assertEquals(bytes, "hey".getBytes()); } finally { client.close(); } } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNamespace() throws Exception { final String namespace = "TestNamespace"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); client.start(); try { String actualPath = client.create().forPath("/test"); Assert.assertEquals(actualPath, "/test"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false)); Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/test", false)); actualPath = client.nonNamespaceView().create().forPath("/non"); Assert.assertEquals(actualPath, "/non"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/non", false)); client.create().forPath("/test/child", "hey".getBytes()); byte[] bytes = client.getData().forPath("/test/child"); Assert.assertEquals(bytes, "hey".getBytes()); bytes = client.nonNamespaceView().getData().forPath("/" + namespace + "/test/child"); Assert.assertEquals(bytes, "hey".getBytes()); } finally { client.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.EXISTS ) { queue.put(event.getPath()); } } }; client.getCuratorListenable().addListener(listener); client.create().forPath("/base", new byte[0]); client.checkExists().inBackground().forPath("/base"); String path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); client.getCuratorListenable().removeListener(listener); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); } finally { client.close(); } } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); CuratorListener listener = new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { if ( event.getType() == CuratorEventType.EXISTS ) { queue.put(event.getPath()); } } }; client.getCuratorListenable().addListener(listener); client.create().forPath("/base"); client.checkExists().inBackground().forPath("/base"); String path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); client.getCuratorListenable().removeListener(listener); BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); Assert.assertEquals(path, "/base"); } finally { client.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event.getPath()); } catch ( InterruptedException e ) { throw new Error(e); } } }; client.create().forPath("/base", new byte[0]); client.getChildren().usingWatcher(watcher).forPath("/base"); client.create().forPath("/base/child", new byte[0]); String path = queue.take(); Assert.assertEquals(path, "/base"); } finally { client.close(); } } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); client.start(); try { final SynchronousQueue<String> queue = new SynchronousQueue<String>(); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { try { queue.put(event.getPath()); } catch ( InterruptedException e ) { throw new Error(e); } } }; client.create().forPath("/base"); client.getChildren().usingWatcher(watcher).forPath("/base"); client.create().forPath("/base/child"); String path = queue.take(); Assert.assertEquals(path, "/base"); } finally { client.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setNonce(trytes.substring(2592, 2673)); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setObsoleteTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setTag(trytes.substring(2592, 2619)); this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000); this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911))); this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938))); this.setNonce(trytes.substring(2646, 2673)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); return GetTransferResponse.create(bundles); } return null; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { // validate & if needed pad seed if ( (seed = InputValidator.validateSeed(seed)) == null) { throw new IllegalStateException("Invalid Seed"); } start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } StopWatch sw = new StopWatch(); sw.start(); System.out.println("GetTransfer started"); GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { System.out.println("GetTransfers after getNewAddresses " + sw.getTime() + " ms"); Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); System.out.println("GetTransfers after bundlesFromAddresses " + sw.getTime() + " ms"); sw.stop(); return GetTransferResponse.create(bundles); } sw.stop(); return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setNonce(trytes.substring(2592, 2673)); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code public void transactionObject(final String trytes) { if (StringUtils.isEmpty(trytes)) { log.warn("Warning: empty trytes in input for transactionObject"); return; } // validity check for (int i = 2279; i < 2295; i++) { if (trytes.charAt(i) != '9') { log.warn("Trytes {} does not seem a valid tryte", trytes); return; } } int[] transactionTrits = Converter.trits(trytes); int[] hash = new int[243]; ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81); // generate the correct transaction hash curl.reset(); curl.absorb(transactionTrits, 0, transactionTrits.length); curl.squeeze(hash, 0, hash.length); this.setHash(Converter.trytes(hash)); this.setSignatureFragments(trytes.substring(0, 2187)); this.setAddress(trytes.substring(2187, 2268)); this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837))); this.setObsoleteTag(trytes.substring(2295, 2322)); this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993))); this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020))); this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047))); this.setBundle(trytes.substring(2349, 2430)); this.setTrunkTransaction(trytes.substring(2430, 2511)); this.setBranchTransaction(trytes.substring(2511, 2592)); this.setTag(trytes.substring(2592, 2619)); this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000); this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911))); this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938))); this.setNonce(trytes.substring(2646, 2673)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); return GetTransferResponse.create(bundles); } return null; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException { // validate & if needed pad seed if ( (seed = InputValidator.validateSeed(seed)) == null) { throw new IllegalStateException("Invalid Seed"); } start = start != null ? 0 : start; end = end == null ? null : end; inclusionStates = inclusionStates != null ? inclusionStates : null; if (start > end || end > (start + 500)) { throw new ArgumentException(); } StopWatch sw = new StopWatch(); sw.start(); System.out.println("GetTransfer started"); GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true); if (gnr != null && gnr.getAddresses() != null) { System.out.println("GetTransfers after getNewAddresses " + sw.getTime() + " ms"); Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates); System.out.println("GetTransfers after bundlesFromAddresses " + sw.getTime() + " ms"); sw.stop(); return GetTransferResponse.create(bundles); } sw.stop(); return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private synchronized boolean send(byte[] bytes) { // buffering if (pendings.position() + bytes.length > pendings.capacity()) { LOG.severe("Cannot send logs to " + server.toString()); return false; } pendings.put(bytes); try { // suppress reconnection burst if (!reconnector.enableReconnection(System.currentTimeMillis())) { return true; } // check whether connection is established or not reconnect(); // write data out.write(getBuffer()); out.flush(); clearBuffer(); } catch (IOException e) { // close socket close(); } return true; } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code private synchronized boolean send(byte[] bytes) { // buffering if (pendings.position() + bytes.length > pendings.capacity()) { LOG.severe("Cannot send logs to " + server.toString()); return false; } pendings.put(bytes); try { // suppress reconnection burst if (!reconnector.enableReconnection(System.currentTimeMillis())) { return true; } // send pending data flush(); } catch (IOException e) { // close socket close(); } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } props.remove(Config.FLUENT_SENDER_CLASS); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() throws IOException { Socket socket = serverSock.accept(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // TODO } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void run() { try { final Socket socket = serverSocket.accept(); Thread th = new Thread() { public void run() { try { process.process(msgpack, socket); } catch (IOException e) { // ignore } } }; th.start(); } catch (IOException e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } props.remove(Config.FLUENT_SENDER_CLASS); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private synchronized boolean send(byte[] bytes) { // buffering if (pendings.position() + bytes.length > pendings.capacity()) { LOG.severe("Cannot send logs to " + server.toString()); return false; } pendings.put(bytes); try { // suppress reconnection burst if (!reconnector.enableReconnection(System.currentTimeMillis())) { return true; } // send pending data flush(); } catch (IOException e) { // close socket close(); } return true; } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code private synchronized boolean send(byte[] bytes) { // buffering if (pendings.position() + bytes.length > pendings.capacity()) { LOG.severe("Cannot send logs to " + server.toString()); return false; } pendings.put(bytes); // suppress reconnection burst if (!reconnector.enableReconnection(System.currentTimeMillis())) { return true; } // send pending data flush(); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testClose() throws Exception { // use NullSender Properties props = System.getProperties(); props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName()); // create logger objects FluentLogger.getLogger("tag1"); FluentLogger.getLogger("tag2"); FluentLogger.getLogger("tag3"); Map<String, FluentLogger> loggers; { loggers = FluentLogger.getLoggers(); assertEquals(3, loggers.size()); } // close and delete FluentLogger.close(); { loggers = FluentLogger.getLoggers(); assertEquals(0, loggers.size()); } props.remove(Config.FLUENT_SENDER_CLASS); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { while (!finished.get()) { try { final Socket socket = serverSocket.accept(); Runnable r = new Runnable() { public void run() { try { MessagePack msgpack = new MessagePack(); msgpack.register(Event.class, MockEventTemplate.INSTANCE); process.process(msgpack, socket); } catch (IOException e) { // ignore } } }; new Thread(r).start(); } catch (IOException e) { // ignore } } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code public void run() { while (!finished.get()) { try { final Socket socket = serverSocket.accept(); socket.setSoLinger(true, 0); clientSockets.add(socket); Runnable r = new Runnable() { public void run() { try { MessagePack msgpack = new MessagePack(); msgpack.register(Event.class, MockEventTemplate.INSTANCE); process.process(msgpack, socket); } catch (IOException e) { // ignore } } }; new Thread(r).start(); } catch (IOException e) { // ignore } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() throws IOException { Socket socket = serverSock.accept(); BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // TODO } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void run() { try { final Socket socket = serverSocket.accept(); Thread th = new Thread() { public void run() { try { process.process(msgpack, socket); } catch (IOException e) { // ignore } } }; th.start(); } catch (IOException e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRenderMultipleObjects() { TestObject testObject = new TestObject(); // step 1: add one object. Result result = new Result(200); result.render(testObject); assertEquals(testObject, result.getRenderable()); // step 2: add a second object (string is just a dummy) // => we expect to get a map from the result now... String string = new String("test"); result.render(string); assertTrue(result.getRenderable() instanceof Map); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(string, resultMap.get("string")); assertEquals(testObject, resultMap.get("testObject")); // step 3: add same object => we expect an illegal argument exception as the map // cannot handle that case: TestObject anotherObject = new TestObject(); boolean gotException = false; try { result.render(anotherObject); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); // step 4: add an entry Entry<String, Object> entry = new AbstractMap.SimpleImmutableEntry<String, Object>("anotherObject", anotherObject); result.render(entry); resultMap = (Map) result.getRenderable(); assertEquals(3, resultMap.size()); assertEquals(anotherObject, resultMap.get("anotherObject")); // step 5: add another map and check that conversion works: Map<String, Object> mapToRender = Maps.newHashMap(); String anotherString = new String("anotherString"); TestObject anotherTestObject = new TestObject(); mapToRender.put("anotherString", anotherString); mapToRender.put("anotherTestObject", anotherTestObject); result.render(mapToRender); resultMap = (Map) result.getRenderable(); assertEquals(5, resultMap.size()); assertEquals(anotherString, resultMap.get("anotherString")); assertEquals(anotherTestObject, resultMap.get("anotherTestObject")); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRenderMultipleObjects() { TestObject testObject = new TestObject(); // step 1: add one object. Result result = new Result(200); result.render(testObject); assertEquals(testObject, result.getRenderable()); // step 2: add a second object (string is just a dummy) // => we expect to get a map from the result now... String string = new String("test"); result.render(string); assertTrue(result.getRenderable() instanceof Map); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(string, resultMap.get("string")); assertEquals(testObject, resultMap.get("testObject")); // step 3: add same object => we expect an illegal argument exception as the map // cannot handle that case: TestObject anotherObject = new TestObject(); boolean gotException = false; try { result.render(anotherObject); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); // step 4: add an entry Entry<String, Object> entry = new AbstractMap.SimpleImmutableEntry<String, Object>("anotherObject", anotherObject); result.render(entry); resultMap = (Map) result.getRenderable(); assertEquals(3, resultMap.size()); assertEquals(anotherObject, resultMap.get("anotherObject")); // step 5: add another map and check that conversion works: Map<String, Object> mapToRender = Maps.newHashMap(); String anotherString = new String("anotherString"); TestObject anotherTestObject = new TestObject(); mapToRender.put("anotherString", anotherString); mapToRender.put("anotherTestObject", anotherTestObject); result.render(mapToRender); resultMap = (Map) result.getRenderable(); assertEquals(2, resultMap.size()); assertEquals(anotherString, resultMap.get("anotherString")); assertEquals(anotherTestObject, resultMap.get("anotherTestObject")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRenderingOfStringObjectPairsWorks() { String object1 = new String("stringy1"); String object2 = new String("stringy2"); // step 1: add one object. Result result = new Result(200); result.render("object1", object1); result.render("object2", object2); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(object1, resultMap.get("object1")); assertEquals(object2, resultMap.get("object2")); /////////////////////////////////////////////////////////////////////// // check that empty render throws exception /////////////////////////////////////////////////////////////////////// boolean gotException = false; try { // will throw exception result.render(); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); /////////////////////////////////////////////////////////////////////// // check that too many arguments in render(...) throws exception /////////////////////////////////////////////////////////////////////// gotException = false; try { // will throw exception result.render(object1, object2, new String("three")); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); /////////////////////////////////////////////////////////////////////// // check that "correct" two string render throws exception // when first parameter is not a string /////////////////////////////////////////////////////////////////////// gotException = false; try { // will throw exception result.render(new TestObject(), object2); } catch (IllegalArgumentException e) { gotException = true; } assertTrue(gotException); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRenderingOfStringObjectPairsWorks() { String object1 = new String("stringy1"); String object2 = new String("stringy2"); // step 1: add one object. Result result = new Result(200); result.render("object1", object1); result.render("object2", object2); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(object1, resultMap.get("object1")); assertEquals(object2, resultMap.get("object2")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String makeJsonRequest(String url) { StringBuffer sb = new StringBuffer(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/json"); HttpResponse response; response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { sb.append(output); } httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code public static String makeJsonRequest(String url) { Map<String, String> headers = Maps.newHashMap(); headers.put("accept", "application/json"); return makeRequest(url, headers); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void parse() { Map<String,RouteParameter> params; RouteParameter param; // no named parameters is null params = RouteParameter.parse("/user"); assertThat(params, is(nullValue())); params = RouteParameter.parse("/user/{id}/{email: [0-9]+}"); param = params.get("id"); assertThat(param.getName(), is("id")); assertThat(param.getToken(), is("{id}")); assertThat(param.getRegex(), is(nullValue())); param = params.get("email"); assertThat(param.getName(), is("email")); assertThat(param.getToken(), is("{email: [0-9]+}")); assertThat(param.getRegex(), is("[0-9]+")); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void parse() { Map<String,RouteParameter> params; RouteParameter param; // no named parameters is null params = RouteParameter.parse("/user"); assertThat(params, aMapWithSize(0)); params = RouteParameter.parse("/user/{id}/{email: [0-9]+}"); param = params.get("id"); assertThat(param.getName(), is("id")); assertThat(param.getToken(), is("{id}")); assertThat(param.getRegex(), is(nullValue())); param = params.get("email"); assertThat(param.getName(), is("email")); assertThat(param.getToken(), is("{email: [0-9]+}")); assertThat(param.getRegex(), is("[0-9]+")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRenderEntryAndMakeSureMapIsCreated() { String stringy = new String("stringy"); Entry<String, Object> entry = new SimpleImmutableEntry("stringy", stringy); // step 1: add one object. Result result = new Result(200); result.render(entry); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(stringy, resultMap.get("stringy")); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRenderEntryAndMakeSureMapIsCreated() { String stringy = new String("stringy"); // step 1: add one object. Result result = new Result(200); result.render("stringy", stringy); Map<String, Object> resultMap = (Map) result.getRenderable(); assertEquals(stringy, resultMap.get("stringy")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static private SourceSnippet readFromInputStream(InputStream is, URI source, int lineFrom, int lineTo) throws IOException { if (lineTo <= 0) { throw new IllegalArgumentException("lineTo was <= 0"); } // just zero this out if (lineFrom < 0) { lineFrom = 0; } if (lineTo < lineFrom) { throw new IllegalArgumentException("lineTo was < lineFrom"); } BufferedReader in = new BufferedReader( new InputStreamReader(is)); List<String> lines = new ArrayList<>(); int i = 0; String line; while ((line = in.readLine()) != null) { i++; // lines index are 1-based if (i >= lineFrom) { if (i <= lineTo) { lines.add(line); } else { break; } } } if (lines.isEmpty()) { return null; } // since file may not contain enough lines for requested lineTo -- // we caclulate the actual range here by number read "from" line. return new SourceSnippet(source, lines, lineFrom, lineFrom + lines.size()); } #location 42 #vulnerability type RESOURCE_LEAK
#fixed code static private SourceSnippet readFromInputStream(InputStream is, URI source, int lineFrom, int lineTo) throws IOException { // did the user provide a strange range (e.g. negative values)? // this sometimes may happen when a range is provided like an error // on line 3 and you want 5 before and 5 after if (lineFrom < 1 && lineTo > 0) { // calculate intended range int intendedRange = lineTo - lineFrom; lineFrom = 1; lineTo = lineFrom + intendedRange; } else if (lineFrom < 0 && lineTo < 0) { if (lineFrom < lineTo) { int intendedRange = -1 * (lineFrom - lineTo); lineFrom = 1; lineTo = lineFrom + intendedRange; } else { // giving up return null; } } BufferedReader in = new BufferedReader( new InputStreamReader(is)); List<String> lines = new ArrayList<>(); int i = 0; String line; while ((line = in.readLine()) != null) { i++; // lines index are 1-based if (i >= lineFrom) { if (i <= lineTo) { lines.add(line); } else { break; } } } if (lines.isEmpty()) { return null; } // since file may not contain enough lines for requested lineTo -- // we caclulate the actual range here by number read "from" line // since we are inclusive and not zero based we adjust the "from" by 1 return new SourceSnippet(source, lines, lineFrom, lineFrom + lines.size() - 1); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String makeRequest(String url, Map<String, String> headers) { StringBuffer sb = new StringBuffer(); try { HttpGet getRequest = new HttpGet(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { getRequest.addHeader(header.getKey(), header.getValue()); } } HttpResponse response; response = httpClient.execute(getRequest); BufferedReader br = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } getRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } return sb.toString(); } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code public String makeRequest(String url, Map<String, String> headers) { StringBuffer sb = new StringBuffer(); BufferedReader br = null; try { HttpGet getRequest = new HttpGet(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { getRequest.addHeader(header.getKey(), header.getValue()); } } HttpResponse response; response = httpClient.execute(getRequest); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } getRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOG.error("Failed to close resource", e); } } } return sb.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleTemplateException(TemplateException te, Environment env, Writer out) { if (ninjaProperties.isProd()) { PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println( "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>"); pw.println("<b style='font-size:medium'>Ooops. A really strange error occurred. Please contact admin if error persists.</b>"); pw.println("</div></html>"); pw.flush(); pw.close(); logger.log(Level.SEVERE, "Templating error. This should not happen in production", te); } else { // print out full stacktrace if we are in test or dev mode PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>" + "<b style='font-size:medium'>FreeMarker template error!</b>" + "<pre><xmp>"); te.printStackTrace(pw); pw.println("</xmp></pre></div></html>"); pw.flush(); pw.close(); logger.log(Level.SEVERE, "Templating error.", te); } } #location 62 #vulnerability type RESOURCE_LEAK
#fixed code public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException { if (!ninjaProperties.isProd()) { // print out full stacktrace if we are in test or dev mode PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out : new PrintWriter(out); pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "<script language=javascript>//\"></script>" + "<script language=javascript>//\'></script>" + "</title></xmp></script></noscript></style></object>" + "</head></pre></table>" + "</form></table></table></table></a></u></i></b>" + "<div align=left " + "style='background-color:#FFFF00; color:#FF0000; " + "display:block; border-top:double; padding:2pt; " + "font-size:medium; font-family:Arial,sans-serif; " + "font-style: normal; font-variant: normal; " + "font-weight: normal; text-decoration: none; " + "text-transform: none'>" + "<b style='font-size:medium'>FreeMarker template error!</b>" + "<pre><xmp>"); te.printStackTrace(pw); pw.println("</xmp></pre></div></html>"); pw.flush(); pw.close(); logger.error("Templating error.", te); } // Let the exception bubble up to the central handlers // so the application can return the correct error page // or perform some other application specific action. throw te; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object invoke(MethodInvocation invocation) throws Throwable { final UnitOfWork unitOfWork; // Only start a new unit of work if the entitymanager is empty // otherwise someone else has started the unit of work already // and we do nothing // Please compare to com.google.inject.persist.jpa.JpaLocalTxnInterceptor // we just mimick that interceptor // // IMPORTANT: // Nesting of begin() end() of unitOfWork is NOT allowed. Contrary to // the documentation of Google Guice as of March 2014. // Related Ninja issue: https://github.com/ninjaframework/ninja/issues/157 if (entityManagerProvider.get() == null) { unitOfWork = unitOfWorkProvider.get(); unitOfWork.begin(); didWeStartWork.set(Boolean.TRUE); } else { // If unit of work already started we don't do anything here... // another UnitOfWorkInterceptor point point will take care... // This happens if you are nesting your calls. return invocation.proceed(); } try { return invocation.proceed(); } finally { if (null != didWeStartWork.get()) { didWeStartWork.remove(); unitOfWork.end(); } } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object invoke(MethodInvocation invocation) throws Throwable { if (null == didWeStartWork.get()) { unitOfWork.begin(); didWeStartWork.set(Boolean.TRUE); } else { // If unit of work already started we don't do anything here... // another UnitOfWorkInterceptor point point will take care... // This happens if you are nesting your calls. return invocation.proceed(); } try { return invocation.proceed(); } finally { if (null != didWeStartWork.get()) { didWeStartWork.remove(); unitOfWork.end(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String makePostRequestWithFormParameters(String url, Map<String, String> headers, Map<String, String> formParameters) { StringBuffer sb = new StringBuffer(); try { HttpPost postRequest = new HttpPost(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { postRequest.addHeader(header.getKey(), header.getValue()); } } // add form parameters: List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); if (formParameters != null) { for (Entry<String, String> parameter : formParameters .entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); postRequest.setEntity(entity); HttpResponse response; response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } postRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } return sb.toString(); } #location 49 #vulnerability type RESOURCE_LEAK
#fixed code public String makePostRequestWithFormParameters(String url, Map<String, String> headers, Map<String, String> formParameters) { StringBuffer sb = new StringBuffer(); BufferedReader br = null; try { HttpPost postRequest = new HttpPost(url); if (headers != null) { // add all headers for (Entry<String, String> header : headers.entrySet()) { postRequest.addHeader(header.getKey(), header.getValue()); } } // add form parameters: List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>(); if (formParameters != null) { for (Entry<String, String> parameter : formParameters .entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); postRequest.setEntity(entity); HttpResponse response; response = httpClient.execute(postRequest); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String output; while ((output = br.readLine()) != null) { sb.append(output); } postRequest.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { LOG.error("Failed to close resource", e); } } } return sb.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAllConstants() { Configuration configuration = SwissKnife.loadConfigurationFromClasspathInUtf8("conf/all_constants.conf", this .getClass()); assertEquals("LANGUAGES", configuration.getString(NinjaConstant.applicationLanguages)); assertEquals("PREFIX", configuration.getString(NinjaConstant.applicationCookiePrefix)); assertEquals("NAME", configuration.getString(NinjaConstant.applicationName)); assertEquals("SECRET", configuration.getString(NinjaConstant.applicationSecret)); assertEquals("SERVER_NAME", configuration.getString(NinjaConstant.serverName)); assertEquals(9999, configuration.getInt(NinjaConstant.sessionExpireTimeInSeconds)); assertEquals(false, configuration.getBoolean(NinjaConstant.sessionSendOnlyIfChanged)); assertEquals(false, configuration.getBoolean(NinjaConstant.sessionTransferredOverHttpsOnly)); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAllConstants() { Configuration configuration = SwissKnife.loadConfigurationInUtf8("conf/all_constants.conf"); assertEquals("LANGUAGES", configuration.getString(NinjaConstant.applicationLanguages)); assertEquals("PREFIX", configuration.getString(NinjaConstant.applicationCookiePrefix)); assertEquals("NAME", configuration.getString(NinjaConstant.applicationName)); assertEquals("SECRET", configuration.getString(NinjaConstant.applicationSecret)); assertEquals("SERVER_NAME", configuration.getString(NinjaConstant.serverName)); assertEquals(9999, configuration.getInt(NinjaConstant.sessionExpireTimeInSeconds)); assertEquals(false, configuration.getBoolean(NinjaConstant.sessionSendOnlyIfChanged)); assertEquals(false, configuration.getBoolean(NinjaConstant.sessionTransferredOverHttpsOnly)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean runSteps(FlowSpec scenario, FlowStepStatusNotifier flowStepStatusNotifier) { ScenarioExecutionState scenarioExecutionState = new ScenarioExecutionState(); for(Step thisStep : scenario.getSteps()){ // Another way to get the String // String requestJson = objectMapper.valueToTree(thisStep.getRequest()).toString(); final String requestJsonAsString = thisStep.getRequest().toString(); LOGGER.info(String.format("\n###RAW: Journey:%s, Step:%s", scenario.getFlowName(), thisStep.getName())); StepExecutionState stepExecutionState = new StepExecutionState(); stepExecutionState.addStep(thisStep.getName()); String resolvedRequestJson = jsonTestProcesor.resolveRequestJson( requestJsonAsString, scenarioExecutionState.getResolvedScenarioState() ); stepExecutionState.addRequest(resolvedRequestJson); String executionResult; try{ String serviceName = thisStep.getUrl(); String operationName = thisStep.getOperation(); // REST call execution Boolean isRESTCall = false; if( serviceName != null && serviceName.contains("/")) { isRESTCall = true; } if(isRESTCall) { serviceName = getFullyQualifiedRestUrl(serviceName); executionResult = serviceExecutor.executeRESTService(serviceName, operationName, resolvedRequestJson); } else { executionResult = serviceExecutor.executeJavaService(serviceName, operationName, resolvedRequestJson); } stepExecutionState.addResponse(executionResult); scenarioExecutionState.addStepState(stepExecutionState.getResolvedStep()); // Handle assertion section String resolvedAssertionJson = jsonTestProcesor.resolveRequestJson( thisStep.getAssertions().toString(), scenarioExecutionState.getResolvedScenarioState() ); LOGGER.info("\n---------> Assertion: <----------\n" + prettyPrintJson(resolvedAssertionJson)); // TODO: Collect the assertion result into this list, say field by field List<JsonAsserter> asserters = jsonTestProcesor.createAssertersFrom(resolvedAssertionJson); List<AssertionReport> failureResults = new ArrayList<>(); //<-- write code // TODO: During this step: if assertion failed if (!failureResults.isEmpty()) { return flowStepStatusNotifier.notifyFlowStepAssertionFailed(scenario.getFlowName(), thisStep.getName(), failureResults); } // TODO: Otherwise test passed //return flowStepStatusNotifier.notifyFlowStepExecutionPassed(scenario.getFlowName(), thisStep.getName()); } catch(Exception ex){ // During this step: if any exception occurred return flowStepStatusNotifier.notifyFlowStepExecutionException( scenario.getFlowName(), thisStep.getName(), new RuntimeException("Smart Step execution failed. Details:" + ex) ); } } /* * There were no steps to execute and the framework will display the test status as Green than Red. * Red symbolises failure, but nothing has failed here. */ return true; } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean runSteps(FlowSpec scenario, FlowStepStatusNotifier flowStepStatusNotifier) { LOGGER.info("\n-------------------------- Scenario:{} -------------------------\n", scenario.getFlowName()); ScenarioExecutionState scenarioExecutionState = new ScenarioExecutionState(); for(Step thisStep : scenario.getSteps()){ // Another way to get the String // String requestJson = objectMapper.valueToTree(thisStep.getRequest()).toString(); final String requestJsonAsString = thisStep.getRequest().toString(); StepExecutionState stepExecutionState = new StepExecutionState(); stepExecutionState.addStep(thisStep.getName()); String resolvedRequestJson = jsonTestProcesor.resolveStringJson( requestJsonAsString, scenarioExecutionState.getResolvedScenarioState() ); stepExecutionState.addRequest(resolvedRequestJson); String executionResult; final String logPrefixRelationshipId = createRelationshipId(); try{ String serviceName = thisStep.getUrl(); String operationName = thisStep.getOperation(); // Resolve the URL patterns if any serviceName = jsonTestProcesor.resolveStringJson( serviceName, scenarioExecutionState.getResolvedScenarioState() ); // logCorelationshipPrinter.aRequestBuilder() .relationshipId(logPrefixRelationshipId) .requestTimeStamp(LocalDateTime.now()) .step(thisStep.getName()) .url(serviceName) .method(operationName) .request(SmartUtils.prettyPrintJson(resolvedRequestJson)); // // REST call execution Boolean isRESTCall = false; if( serviceName != null && serviceName.contains("/")) { isRESTCall = true; } if(isRESTCall) { serviceName = getFullyQualifiedRestUrl(serviceName); executionResult = serviceExecutor.executeRESTService(serviceName, operationName, resolvedRequestJson); } else { executionResult = serviceExecutor.executeJavaService(serviceName, operationName, resolvedRequestJson); } // logCorelationshipPrinter.aResponseBuilder() .relationshipId(logPrefixRelationshipId) .responseTimeStamp(LocalDateTime.now()) .response(executionResult); // stepExecutionState.addResponse(executionResult); scenarioExecutionState.addStepState(stepExecutionState.getResolvedStep()); // Handle assertion section String resolvedAssertionJson = jsonTestProcesor.resolveStringJson( thisStep.getAssertions().toString(), scenarioExecutionState.getResolvedScenarioState() ); LOGGER.info("\n---------> Assertion: <----------\n{}", prettyPrintJson(resolvedAssertionJson)); List<JsonAsserter> asserters = jsonTestProcesor.createAssertersFrom(resolvedAssertionJson); List<AssertionReport> failureResults = jsonTestProcesor.assertAllAndReturnFailed(asserters, executionResult); //<-- write code // TODO: During this step: if assertion failed if (!failureResults.isEmpty()) { return flowStepStatusNotifier.notifyFlowStepAssertionFailed(scenario.getFlowName(), thisStep.getName(), failureResults); } // TODO: Otherwise test passed flowStepStatusNotifier.notifyFlowStepExecutionPassed(scenario.getFlowName(), thisStep.getName()); } catch(Exception ex){ logCorelationshipPrinter.aResponseBuilder() .relationshipId(logPrefixRelationshipId) .responseTimeStamp(LocalDateTime.now()) .response(ex.getMessage()); // During this step: if any exception occurred return flowStepStatusNotifier.notifyFlowStepExecutionException( scenario.getFlowName(), thisStep.getName(), new RuntimeException("Smart Step execution failed. Details:" + ex) ); } finally { logCorelationshipPrinter.print(); } } /* * There were no steps to execute and the framework will display the test status as Green than Red. * Red symbolises failure, but nothing has failed here. */ return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRawRecordingSpeed() throws Exception { Histogram histogram = new Histogram(highestTrackableValue, numberOfSignificantValueDigits); // Warm up: long startTime = System.nanoTime(); recordLoop(histogram, warmupLoopLength); long endTime = System.nanoTime(); long deltaUsec = (endTime - startTime) / 1000L; long rate = 1000000 * warmupLoopLength / deltaUsec; System.out.println("Warmup:\n" + warmupLoopLength + " value recordings completed in " + deltaUsec + " usec, rate = " + rate + " value recording calls per sec."); histogram.reset(); // Wait a bit to make sure compiler had a cache to do it's stuff: try { Thread.sleep(1000); } catch (InterruptedException e) { } startTime = System.nanoTime(); recordLoop(histogram, timingLoopCount); endTime = System.nanoTime(); deltaUsec = (endTime - startTime) / 1000L; rate = 1000000 * timingLoopCount / deltaUsec; System.out.println("Timing:"); System.out.println(timingLoopCount + " value recordings completed in " + deltaUsec + " usec, rate = " + rate + " value recording calls per sec."); rate = 1000000 * histogram.getHistogramData().getTotalCount() / deltaUsec; System.out.println(histogram.getHistogramData().getTotalCount() + " raw recorded entries completed in " + deltaUsec + " usec, rate = " + rate + " recorded values per sec."); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRawRecordingSpeed() throws Exception { testRawRecordingSpeedAtExpectedInterval(1000000000); testRawRecordingSpeedAtExpectedInterval(10000); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static synchronized List<Menu> loadJson() throws IOException { InputStream inStream = MenuJsonUtils.class.getResourceAsStream(config); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, Charset.forName("UTF-8"))); StringBuilder json = new StringBuilder(); String tmp; while ((tmp = reader.readLine()) != null) { json.append(tmp); } List<Menu> menus = JSONArray.parseArray(json.toString(), Menu.class); return menus; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private static synchronized List<Menu> loadJson() throws IOException { InputStream inStream = MenuJsonUtils.class.getResourceAsStream(config); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, Charset.forName("UTF-8"))); StringBuilder json = new StringBuilder(); String tmp; try { while ((tmp = reader.readLine()) != null) { json.append(tmp); } } catch (IOException e) { throw e; } finally { reader.close(); inStream.close(); } List<Menu> menus = JSONArray.parseArray(json.toString(), Menu.class); return menus; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView) throws Exception { PostVO ret = (PostVO) modelAndView.getModelMap().get("view"); Object editing = modelAndView.getModel().get("editing"); if (null == editing && ret != null) { PostVO post = new PostVO(); BeanUtils.copyProperties(ret, post); if (check(ret.getId(), ret.getAuthor().getId())) { post.setContent(replace(post.getContent())); } else { String c = post.getContent().replaceAll("&lt;hide&gt;", "<hide>"); c = c.replaceAll("&lt;/hide&gt;", "</hide>"); post.setContent(c); } modelAndView.getModelMap().put("view", post); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView) throws Exception { PostVO ret = (PostVO) modelAndView.getModelMap().get("view"); Object editing = modelAndView.getModel().get("editing"); if (null == editing && ret != null) { PostVO post = new PostVO(); BeanUtils.copyProperties(ret, post); if (check(ret.getId(), ret.getAuthor().getId())) { String c = post.getContent().replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", SHOW); post.setContent(c); } else { String c = post.getContent().replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", "$1"); post.setContent(c); } modelAndView.getModelMap().put("view", post); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { // STEP-1: read input parameters and validate them if (args.length < 2) { System.err.println("Usage: SecondarySortUsingGroupByKey <input> <output>"); System.exit(1); } String inputPath = args[0]; System.out.println("inputPath=" + inputPath); String outputPath = args[1]; System.out.println("outputPath=" + outputPath); // STEP-2: Connect to the Sark master by creating JavaSparkContext object final JavaSparkContext ctx = SparkUtil.createJavaSparkContext(); // STEP-3: Use ctx to create JavaRDD<String> // input record format: <name><,><time><,><value> JavaRDD<String> lines = ctx.textFile(inputPath, 1); // STEP-4: create (key, value) pairs from JavaRDD<String> where // key is the {name} and value is a pair of (time, value). // The resulting RDD will be JavaPairRDD<String, Tuple2<Integer, Integer>>. // convert each record into Tuple2(name, time, value) // PairFunction<T, K, V> T => Tuple2(K, V) where K=String and V=Tuple2<Integer, Integer> // input K V System.out.println("=== DEBUG STEP-4 ==="); JavaPairRDD<String, Tuple2<Integer, Integer>> pairs = lines.mapToPair(new PairFunction<String, String, Tuple2<Integer, Integer>>() { @Override public Tuple2<String, Tuple2<Integer, Integer>> call(String s) { String[] tokens = s.split(","); // x,2,5 System.out.println(tokens[0] + "," + tokens[1] + "," + tokens[2]); Tuple2<Integer, Integer> timevalue = new Tuple2<Integer, Integer>(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); return new Tuple2<String, Tuple2<Integer, Integer>>(tokens[0], timevalue); } }); // STEP-5: validate STEP-4, we collect all values from JavaPairRDD<> and print it. List<Tuple2<String, Tuple2<Integer, Integer>>> output = pairs.collect(); for (Tuple2 t : output) { Tuple2<Integer, Integer> timevalue = (Tuple2<Integer, Integer>) t._2; System.out.println(t._1 + "," + timevalue._1 + "," + timevalue._1); } // STEP-6: We group JavaPairRDD<> elements by the key ({name}). JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> groups = pairs.groupByKey(); // STEP-7: validate STEP-6, we collect all values from JavaPairRDD<> and print it. System.out.println("=== DEBUG STEP-6 ==="); List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output2 = groups.collect(); for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output2) { Iterable<Tuple2<Integer, Integer>> list = t._2; System.out.println(t._1); for (Tuple2<Integer, Integer> t2 : list) { System.out.println(t2._1 + "," + t2._2); } System.out.println("====="); } //STEP-8: Sort the reducer's values and this will give us the final output. // OPTION-1: worked // mapValues[U](f: (V) ⇒ U): JavaPairRDD[K, U] // Pass each value in the key-value pair RDD through a map function without changing the keys; // this also retains the original RDD's partitioning. JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> sorted = groups.mapValues(new Function<Iterable<Tuple2<Integer, Integer>>, // input Iterable<Tuple2<Integer, Integer>> // output >() { @Override public Iterable<Tuple2<Integer, Integer>> call(Iterable<Tuple2<Integer, Integer>> s) { List<Tuple2<Integer, Integer>> newList = new ArrayList<Tuple2<Integer, Integer>>(iterableToList(s)); Collections.sort(newList, SparkTupleComparator.INSTANCE); return newList; } }); // STEP-9: validate STEP-8, we collect all values from JavaPairRDD<> and print it. System.out.println("=== DEBUG STEP-8 ==="); List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output3 = sorted.collect(); for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output3) { Iterable<Tuple2<Integer, Integer>> list = t._2; System.out.println(t._1); for (Tuple2<Integer, Integer> t2 : list) { System.out.println(t2._1 + "," + t2._2); } System.out.println("====="); } sorted.saveAsTextFile(outputPath); System.exit(0); } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { // STEP-1: read input parameters and validate them if (args.length < 2) { System.err.println("Usage: SecondarySortUsingGroupByKey <input> <output>"); System.exit(1); } String inputPath = args[0]; System.out.println("inputPath=" + inputPath); String outputPath = args[1]; System.out.println("outputPath=" + outputPath); // STEP-2: Connect to the Spark master by creating JavaSparkContext object final JavaSparkContext ctx = SparkUtil.createJavaSparkContext("SecondarySorting"); // STEP-3: Use ctx to create JavaRDD<String> // input record format: <name><,><time><,><value> JavaRDD<String> lines = ctx.textFile(inputPath, 1); // STEP-4: create (key, value) pairs from JavaRDD<String> where // key is the {name} and value is a pair of (time, value). // The resulting RDD will be JavaPairRDD<String, Tuple2<Integer, Integer>>. // convert each record into Tuple2(name, time, value) // PairFunction<T, K, V> T => Tuple2(K, V) where K=String and V=Tuple2<Integer, Integer> // input K V System.out.println("=== DEBUG STEP-4 ==="); JavaPairRDD<String, Tuple2<Integer, Integer>> pairs = lines.mapToPair(new PairFunction<String, String, Tuple2<Integer, Integer>>() { @Override public Tuple2<String, Tuple2<Integer, Integer>> call(String s) { String[] tokens = s.split(","); // x,2,5 System.out.println(tokens[0] + "," + tokens[1] + "," + tokens[2]); Tuple2<Integer, Integer> timevalue = new Tuple2<Integer, Integer>(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); return new Tuple2<String, Tuple2<Integer, Integer>>(tokens[0], timevalue); } }); // STEP-5: validate STEP-4, we collect all values from JavaPairRDD<> and print it. List<Tuple2<String, Tuple2<Integer, Integer>>> output = pairs.collect(); for (Tuple2 t : output) { Tuple2<Integer, Integer> timevalue = (Tuple2<Integer, Integer>) t._2; System.out.println(t._1 + "," + timevalue._1 + "," + timevalue._2); } // STEP-6: We group JavaPairRDD<> elements by the key ({name}). JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> groups = pairs.groupByKey(); // STEP-7: validate STEP-6, we collect all values from JavaPairRDD<> and print it. System.out.println("=== DEBUG STEP-6 ==="); List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output2 = groups.collect(); for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output2) { Iterable<Tuple2<Integer, Integer>> list = t._2; System.out.println(t._1); for (Tuple2<Integer, Integer> t2 : list) { System.out.println(t2._1 + "," + t2._2); } System.out.println("====="); } //STEP-8: Sort the reducer's values and this will give us the final output. // OPTION-1: worked // mapValues[U](f: (V) ⇒ U): JavaPairRDD[K, U] // Pass each value in the key-value pair RDD through a map function without changing the keys; // this also retains the original RDD's partitioning. JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> sorted = groups.mapValues(new Function<Iterable<Tuple2<Integer, Integer>>, // input Iterable<Tuple2<Integer, Integer>> // output >() { @Override public Iterable<Tuple2<Integer, Integer>> call(Iterable<Tuple2<Integer, Integer>> s) { List<Tuple2<Integer, Integer>> newList = new ArrayList<Tuple2<Integer, Integer>>(iterableToList(s)); Collections.sort(newList, SparkTupleComparator.INSTANCE); return newList; } }); // STEP-9: validate STEP-8, we collect all values from JavaPairRDD<> and print it. System.out.println("=== DEBUG STEP-8 ==="); List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output3 = sorted.collect(); for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output3) { Iterable<Tuple2<Integer, Integer>> list = t._2; System.out.println(t._1); for (Tuple2<Integer, Integer> t2 : list) { System.out.println(t2._1 + "," + t2._2); } System.out.println("====="); } sorted.saveAsTextFile(outputPath); System.exit(0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Map<String, String> readService(String path) throws IOException { InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path)); BufferedReader br = new BufferedReader(fr); String line = ""; Map<String, String> result = new HashMap<String, String>(); while ((line = br.readLine()) != null) { String sl = line.trim(); if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) { continue; } String[] kv = sl.split("="); if (kv == null || kv.length != 2) { close(br, fr); throw new RuntimeException("Illegal flow config:" + path + ", sl"); } result.put(kv[0].trim(), kv[1].trim()); } close(br, fr); return result; } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public static Map<String, String> readService(String path) throws IOException { InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path),Constant.ENCODING_UTF_8); BufferedReader br = new BufferedReader(fr); String line; Map<String, String> result = new HashMap<String, String>(); while ((line = br.readLine()) != null) { String sl = line.trim(); if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) { continue; } String[] kv = sl.split("="); if (kv == null || kv.length != 2) { close(br, fr); throw new RuntimeException("Illegal flow config:" + path + ", sl"); } result.put(kv[0].trim(), kv[1].trim()); } close(br, fr); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static CacheManager get() { if (instance == null) { synchronized (log) { if (instance == null) { instance = new CacheManager(); } } } return instance; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static CacheManager get() { return get(defaultCacheManager); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings({"unchecked", "rawtypes"}) public void onReceive(ServiceContext serviceContext) throws Throwable { FlowMessage fm = serviceContext.getFlowMessage(); if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) { syncActors.putIfAbsent(serviceContext.getId(), getSender()); } // TODO 没有必要设置默认值,下面执行异常就会抛出异常 Object result = null;// DefaultMessage.getMessage();// set default try { this.service = ServiceFactory.getService(serviceName); result = ((Service) service).process(fm.getMessage(), serviceContext); } catch (Throwable e) { Web web = serviceContext.getWeb(); if (web != null) { web.complete(); } throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e); } if (serviceContext.isSync() && !hasChildActor()) { syncActors.get(serviceContext.getId()).tell(result, getSelf()); syncActors.remove(serviceContext.getId()); return; } Web web = serviceContext.getWeb(); if (service instanceof Complete) { // FlowContext.removeServiceContext(fm.getTransactionId()); } if (web != null) { if (service instanceof Flush) { web.flush(); } if (service instanceof HttpComplete || service instanceof Complete) { web.complete(); } } if (result == null)// for joint service return; if (hasChildActor()) { for (RefType refType : nextServiceActors) { ServiceContext context = serviceContext.newInstance(); context.getFlowMessage().setMessage(result); // if (refType.isJoint()) { // FlowMessage flowMessage1 = CloneUtil.clone(fm); // flowMessage1.setMessage(result); // context.setFlowMessage(flowMessage1); // } // condition fork for one-service to multi-service if (refType.getMessageType().isInstance(result)) { if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String) || stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) { refType.getActorRef().tell(context, getSelf()); } } } } else { } } #location 45 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings({"unchecked", "rawtypes"}) public void onReceive(ServiceContext serviceContext) throws Throwable { FlowMessage fm = serviceContext.getFlowMessage(); if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) { syncActors.putIfAbsent(serviceContext.getId(), getSender()); } // TODO 没有必要设置默认值,下面执行异常就会抛出异常 Object result = null;// DefaultMessage.getMessage();// set default try { this.service = ServiceFactory.getService(serviceName); result = ((Service) service).process(fm.getMessage(), serviceContext); } catch (Throwable e) { Web web = serviceContext.getWeb(); if (web != null) { web.complete(); } throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e); } logger.info("同步处理 : {}, hasChild : {}", serviceContext.isSync(), hasChildActor()); if (serviceContext.isSync() && !hasChildActor()) { logger.info("返回响应 {}", result); ActorRef actor = syncActors.get(serviceContext.getId()); if(actor !=null) { actor.tell(result, getSelf()); syncActors.remove(serviceContext.getId()); } return; } Web web = serviceContext.getWeb(); if (service instanceof Complete) { // FlowContext.removeServiceContext(fm.getTransactionId()); } if (web != null) { if (service instanceof Flush) { web.flush(); } if (service instanceof HttpComplete || service instanceof Complete) { web.complete(); } } if (result == null)// for joint service return; if (hasChildActor()) { for (RefType refType : nextServiceActors) { ServiceContext context = serviceContext.newInstance(); context.getFlowMessage().setMessage(result); // if (refType.isJoint()) { // FlowMessage flowMessage1 = CloneUtil.clone(fm); // flowMessage1.setMessage(result); // context.setFlowMessage(flowMessage1); // } // condition fork for one-service to multi-service if (refType.getMessageType().isInstance(result)) { if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String) || stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) { refType.getActorRef().tell(context, getSelf()); } } } } else { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ServiceFlow [\r\n\tflowName = "); builder.append(flowName); builder.append("\r\n\t"); Set<ServiceConfig> nextServices = servicesOfFlow.get(getHeadServiceConfig().getServiceName()); builder.append(getHeadServiceConfig().getSimpleDesc()); builder.append(" --> "); getHeadServiceConfig().getNextServiceConfigs().forEach(item -> { builder.append(item.getSimpleDesc()).append(","); }); if (nextServices != null) { for (Map.Entry<String, Set<ServiceConfig>> entry : servicesOfFlow.entrySet()) { if (getHeadServiceConfig().getServiceName().equals(entry.getKey())) { continue; } builder.append("\r\n\t"); builder.append(getServiceConfig(entry.getKey()).getSimpleDesc()); builder.append(" -- > "); entry.getValue().forEach(item -> { builder.append(item.getSimpleDesc()).append(", "); }); } } builder.append("\n]"); return builder.toString(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ServiceFlow [ flowName = "); builder.append(flowName); builder.append("\r\n\t"); ServiceConfig hh = header; buildString(hh, builder); builder.append("\n]"); return builder.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void onServiceContextReceived(ServiceContext serviceContext) throws Throwable { FlowMessage flowMessage = serviceContext.getFlowMessage(); if (serviceContext.isSync()) { CacheManager.get(serviceActorCachePrefix + serviceContext.getFlowName()).add(serviceContext.getId(), getSender(), defaultTimeToLive); } Serializer serializer = ExtensionLoader.load(Serializer.class).load(serviceContext.getCodec()); Object result = null; Object param = null; try { ServiceContextUtil.fillServiceContext(serviceContext); String pType = getParamType(serviceContext); if (flowMessage.getMessage() != null && ClassUtil.exists(flowMessage.getMessageType())) { pType = flowMessage.getMessageType(); } param = serializer.decode(flowMessage.getMessage(), pType); if (getFilter(serviceContext) != null) { getFilter(serviceContext).filter(param, serviceContext); } // logger.info("服务参数类型 {} : {}", pType, getService(serviceContext)); result = ((Service) getService(serviceContext)).process(param, serviceContext); } catch (Throwable e) { handleException(serviceContext, e, param, serializer); } if (result != null && result instanceof CompletableFuture) { final Object tempParam = param; ((CompletableFuture<Object>) result).whenComplete((r, e) -> { if (e != null) { handleException(serviceContext, e, tempParam, serializer); return; } handleNextServices(serviceContext, r, flowMessage.getTransactionId(), serializer); }); } else { handleNextServices(serviceContext, result, flowMessage.getTransactionId(), serializer); } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void onServiceContextReceived(ServiceContext serviceContext) throws Throwable { FlowMessage flowMessage = serviceContext.getFlowMessage(); if (serviceContext.isSync()) { CacheManager.get(serviceActorCachePrefix + serviceContext.getFlowName()).add(serviceContext.getId(), getSender(), defaultTimeToLive); } Serializer serializer = ExtensionLoader.load(Serializer.class).load(serviceContext.getCodec()); Object result = null; Object param = null; try { ServiceContextUtil.fillServiceContext(serviceContext); param = getAndDecodeParam(serviceContext); if (getFilter(serviceContext) != null) { getFilter(serviceContext).filter(param, serviceContext); } // logger.info("服务参数类型 {} : {}", pType, getService(serviceContext)); result = ((Service) getService(serviceContext)).process(param, serviceContext); } catch (Throwable e) { handleException(serviceContext, e, param, serializer); } if (result != null && result instanceof CompletableFuture) { final Object tempParam = param; ((CompletableFuture<Object>) result).whenComplete((r, e) -> { if (e != null) { handleException(serviceContext, e, tempParam, serializer); return; } handleNextServices(serviceContext, r, flowMessage.getTransactionId(), serializer); }); } else { handleNextServices(serviceContext, result, flowMessage.getTransactionId(), serializer); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void doStartup(String configLocation) { ClassPathXmlApplicationContext applicationContext = null; try { applicationContext = new ClassPathXmlApplicationContext(configLocation); applicationContext.start(); } catch (Exception e) { if (applicationContext != null) { applicationContext.close(); } logger.error("", e); } logger.info("spring初始化完成"); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void doStartup(String configLocation) throws Throwable { Class<?> applicationContextClazz = Class.forName("org.springframework.context.support.ClassPathXmlApplicationContext", true, getClassLoader()); Object flowerFactory = applicationContextClazz.getConstructor(String.class).newInstance(configLocation); Method startMethod = applicationContextClazz.getMethod("start"); startMethod.invoke(flowerFactory); logger.info("spring初始化完成"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<Pair<String, String>> readFlow(String path) throws IOException { InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path)); BufferedReader br = new BufferedReader(fr); String line = ""; List<Pair<String, String>> flow = new ArrayList<>(); while ((line = br.readLine()) != null) { String sl = line.trim(); if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) { continue; } String[] connection = sl.split("->"); if (connection == null || connection.length != 2) { close(br, fr); throw new RuntimeException("Illegal flow config:" + path); } else { flow.add(new Pair<String, String>(connection[0].trim(), connection[1].trim())); } } close(br, fr); return flow; } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code public static List<Pair<String, String>> readFlow(String path) throws IOException { InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path),Constant.ENCODING_UTF_8); BufferedReader br = new BufferedReader(fr); String line; List<Pair<String, String>> flow = new ArrayList<>(); while ((line = br.readLine()) != null) { String sl = line.trim(); if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) { continue; } String[] connection = sl.split("->"); if (connection == null || connection.length != 2) { close(br, fr); throw new RuntimeException("Illegal flow config:" + path); } else { flow.add(new Pair<String, String>(connection[0].trim(), connection[1].trim())); } } close(br, fr); return flow; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isEquivalentTo(JSType otherType) { if (!(otherType instanceof FunctionType)) { return false; } FunctionType that = (FunctionType) otherType; if (!that.isFunctionType()) { return false; } if (this.isConstructor()) { if (that.isConstructor()) { return this == that; } return false; } if (this.isInterface()) { if (that.isInterface()) { return this.getReferenceName().equals(that.getReferenceName()); } return false; } if (that.isInterface()) { return false; } return this.typeOfThis.isEquivalentTo(that.typeOfThis) && this.call.isEquivalentTo(that.call); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean isEquivalentTo(JSType otherType) { FunctionType that = JSType.toMaybeFunctionType(otherType.toMaybeFunctionType()); if (that == null) { return false; } if (this.isConstructor()) { if (that.isConstructor()) { return this == that; } return false; } if (this.isInterface()) { if (that.isInterface()) { return this.getReferenceName().equals(that.getReferenceName()); } return false; } if (that.isInterface()) { return false; } return this.typeOfThis.isEquivalentTo(that.typeOfThis) && this.call.isEquivalentTo(that.call); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code FunctionTypeBuilder inferThisType(JSDocInfo info, @Nullable Node owner) { ObjectType maybeThisType = null; if (info != null && info.hasThisType()) { maybeThisType = ObjectType.cast( info.getThisType().evaluate(scope, typeRegistry)); } if (maybeThisType != null) { thisType = maybeThisType; thisType.setValidator(new ThisTypeValidator()); } else if (owner != null && (info == null || !info.hasType())) { // If the function is of the form: // x.prototype.y = function() {} // then we can assume "x" is the @this type. On the other hand, // if it's of the form: // /** @type {Function} */ x.prototype.y; // then we should not give it a @this type. String ownerTypeName = owner.getQualifiedName(); ObjectType ownerType = ObjectType.cast( typeRegistry.getForgivingType( scope, ownerTypeName, sourceName, owner.getLineno(), owner.getCharno())); if (ownerType != null) { thisType = ownerType; } } return this; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code FunctionTypeBuilder(String fnName, AbstractCompiler compiler, Node errorRoot, String sourceName, Scope scope) { Preconditions.checkNotNull(errorRoot); this.fnName = fnName == null ? "" : fnName; this.codingConvention = compiler.getCodingConvention(); this.typeRegistry = compiler.getTypeRegistry(); this.errorRoot = errorRoot; this.sourceName = sourceName; this.compiler = compiler; this.scope = scope; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private EnvTypePair analyzeLooseCallNodeBwd( Node callNode, TypeEnv outEnv, JSType retType) { Preconditions.checkArgument(callNode.isCall()); Preconditions.checkNotNull(retType); Node callee = callNode.getFirstChild(); TypeEnv tmpEnv = outEnv; FunctionTypeBuilder builder = new FunctionTypeBuilder(); for (int i = callNode.getChildCount() - 2; i >= 0; i--) { Node arg = callNode.getChildAtIndex(i + 1); tmpEnv = analyzeExprBwd(arg, tmpEnv).env; // Wait until FWD to get more precise argument types. builder.addReqFormal(JSType.BOTTOM); } JSType looseRetType = retType.isUnknown() ? JSType.BOTTOM : retType; JSType looseFunctionType = builder.addRetType(looseRetType).addLoose().buildType(); looseFunctionType.getFunType().checkValid(); println("loose function type is ", looseFunctionType); EnvTypePair calleePair = analyzeExprBwd(callee, tmpEnv, looseFunctionType); return new EnvTypePair(calleePair.env, retType); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private EnvTypePair analyzeLooseCallNodeBwd( Node callNode, TypeEnv outEnv, JSType retType) { Preconditions.checkArgument(callNode.isCall()); Preconditions.checkNotNull(retType); Node callee = callNode.getFirstChild(); TypeEnv tmpEnv = outEnv; FunctionTypeBuilder builder = new FunctionTypeBuilder(); for (int i = callNode.getChildCount() - 2; i >= 0; i--) { Node arg = callNode.getChildAtIndex(i + 1); tmpEnv = analyzeExprBwd(arg, tmpEnv).env; // Wait until FWD to get more precise argument types. builder.addReqFormal(JSType.BOTTOM); } JSType looseRetType = retType.isUnknown() ? JSType.BOTTOM : retType; JSType looseFunctionType = builder.addRetType(looseRetType).addLoose().buildType(); println("loose function type is ", looseFunctionType); EnvTypePair calleePair = analyzeExprBwd(callee, tmpEnv, looseFunctionType); return new EnvTypePair(calleePair.env, retType); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<JSSourceFile> getDefaultExterns() { try { InputStream input = Compiler.class.getResourceAsStream( "/externs.zip"); ZipInputStream zip = new ZipInputStream(input); List<JSSourceFile> externs = Lists.newLinkedList(); for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) { LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize()); externs.add( JSSourceFile.fromInputStream(entry.getName(), entryStream)); } return externs; } catch (IOException e) { throw new BuildException(e); } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code private List<JSSourceFile> getDefaultExterns() { try { return CommandLineRunner.getDefaultExterns(); } catch (IOException e) { throw new BuildException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node tryOptimizeSwitch(Node n) { Preconditions.checkState(n.getType() == Token.SWITCH); Node defaultCase = findDefaultCase(n); if (defaultCase != null && isUselessCase(defaultCase)) { NodeUtil.redeclareVarsInsideBranch(defaultCase); n.removeChild(defaultCase); reportCodeChange(); defaultCase = null; } // Removing cases when there exists a default case is not safe. // TODO(johnlenz): Allow this if the same code is executed. if (defaultCase == null) { Node next = null; // The first child is the switch conditions skip it. for (Node c = n.getFirstChild().getNext(); c != null; c = next) { next = c.getNext(); if (!mayHaveSideEffects(c.getFirstChild()) && isUselessCase(c)) { NodeUtil.redeclareVarsInsideBranch(c); n.removeChild(c); reportCodeChange(); } } } if (n.hasOneChild()) { Node condition = n.removeFirstChild(); Node parent = n.getParent(); Node replacement = new Node(Token.EXPR_RESULT, condition) .copyInformationFrom(n); parent.replaceChild(n, replacement); reportCodeChange(); return replacement; } return null; } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private Node tryOptimizeSwitch(Node n) { Preconditions.checkState(n.getType() == Token.SWITCH); Node defaultCase = tryOptimizeDefaultCase(n); // Removing cases when there exists a default case is not safe. if (defaultCase == null) { Node next = null; Node prev = null; // The first child is the switch conditions skip it. for (Node c = n.getFirstChild().getNext(); c != null; c = next) { next = c.getNext(); if (!mayHaveSideEffects(c.getFirstChild()) && isUselessCase(c, prev)) { removeCase(n, c); } else { prev = c; } } } // Remove the switch if there are no remaining cases. if (n.hasOneChild()) { Node condition = n.removeFirstChild(); Node parent = n.getParent(); Node replacement = new Node(Token.EXPR_RESULT, condition) .copyInformationFrom(n); parent.replaceChild(n, replacement); reportCodeChange(); return replacement; } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeResult(String source) { if (this.outputFile.getParentFile().mkdirs()) { log("Created missing parent directory " + this.outputFile.getParentFile(), Project.MSG_DEBUG); } try { FileWriter out = new FileWriter(this.outputFile); out.append(source); out.close(); } catch (IOException e) { throw new BuildException(e); } log("Compiled javascript written to " + this.outputFile.getAbsolutePath(), Project.MSG_DEBUG); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code private void writeResult(String source) { if (this.outputFile.getParentFile().mkdirs()) { log("Created missing parent directory " + this.outputFile.getParentFile(), Project.MSG_DEBUG); } try { OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(this.outputFile), outputEncoding); out.append(source); out.flush(); out.close(); } catch (IOException e) { throw new BuildException(e); } log("Compiled javascript written to " + this.outputFile.getAbsolutePath(), Project.MSG_DEBUG); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Writer fileNameToOutputWriter(String fileName) throws IOException { if (fileName == null) { return null; } if (testMode) { return new StringWriter(); } return streamToOutputWriter(new FileOutputStream(fileName)); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code private Writer fileNameToOutputWriter(String fileName) throws IOException { if (fileName == null) { return null; } if (testMode) { return new StringWriter(); } return streamToOutputWriter(filenameToOutputStream(fileName)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) { Preconditions.checkArgument(inputs.containsAll(roots)); Set<INPUT> included = Sets.newHashSet(); Deque<INPUT> worklist = new ArrayDeque<INPUT>(roots); while (!worklist.isEmpty()) { INPUT current = worklist.pop(); if (included.add(current)) { for (String req : current.getRequires()) { INPUT dep = provideMap.get(req); if (dep != null) { worklist.add(dep); } } } } ImmutableList.Builder<INPUT> builder = ImmutableList.builder(); for (INPUT current : sortedList) { if (included.contains(current)) { builder.add(current); } } return builder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) { return getDependenciesOf(roots, true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (value.getType() != Token.THIS && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, Node.newString(Token.NAME, newName) .copyInformationFromForTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (!value.isThis() && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, Node.newString(Token.NAME, newName) .copyInformationFromForTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.isScript()) { this.inExterns = n.getStaticSourceFile().isExtern(); } return true; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Set<String> getOwnPropertyNames() { return ImmutableSet.of(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code public Set<String> getOwnPropertyNames() { return getPropertyMap().getOwnPropertyNames(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void enterScope(NodeTraversal t) { new GraphReachability<Node, ControlFlowGraph.Branch>( t.getControlFlowGraph(), new ReachablePredicate()).compute( t.getControlFlowGraph().getEntry().getValue()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void enterScope(NodeTraversal t) { scopeNeedsInit = true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initEdgeEnvsFwd() { // TODO(user): Revisit what we throw away after the bwd analysis DiGraphNode<Node, ControlFlowGraph.Branch> entry = cfg.getEntry(); DiGraphEdge<Node, ControlFlowGraph.Branch> entryOutEdge = cfg.getOutEdges(entry.getValue()).get(0); TypeEnv entryEnv = envs.get(entryOutEdge); initEdgeEnvs(new TypeEnv()); // For function scopes, add the formal parameters and the free variables // from outer scopes to the environment. if (currentScope.isFunction()) { Set<String> formalsAndOuters = currentScope.getOuterVars(); formalsAndOuters.addAll(currentScope.getFormals()); if (currentScope.hasThis()) { formalsAndOuters.add("this"); } for (String name : formalsAndOuters) { JSType declType = currentScope.getDeclaredTypeOf(name); JSType initType; if (declType == null) { initType = envGetType(entryEnv, name); } else if (declType.getFunTypeIfSingletonObj() != null && declType.getFunTypeIfSingletonObj().isConstructor()) { initType = declType.getFunTypeIfSingletonObj().createConstructorObject(); } else { initType = declType; } entryEnv = envPutType(entryEnv, name, initType.withLocation(name)); } entryEnv = envPutType(entryEnv, RETVAL_ID, JSType.UNDEFINED); } // For all scopes, add local variables and (local) function definitions // to the environment. for (String local : currentScope.getLocals()) { entryEnv = envPutType(entryEnv, local, JSType.UNDEFINED); } for (String fnName : currentScope.getLocalFunDefs()) { JSType summaryType = summaries.get(currentScope.getScope(fnName)); FunctionType fnType = summaryType.getFunType(); if (fnType.isConstructor()) { summaryType = fnType.createConstructorObject(); } else { summaryType = summaryType.withProperty("prototype", JSType.TOP_OBJECT); } entryEnv = envPutType(entryEnv, fnName, summaryType); } println("Keeping env: ", entryEnv); envs.put(entryOutEdge, entryEnv); } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code private void initEdgeEnvsFwd() { // TODO(user): Revisit what we throw away after the bwd analysis DiGraphNode<Node, ControlFlowGraph.Branch> entry = cfg.getEntry(); DiGraphEdge<Node, ControlFlowGraph.Branch> entryOutEdge = cfg.getOutEdges(entry.getValue()).get(0); TypeEnv entryEnv = envs.get(entryOutEdge); initEdgeEnvs(new TypeEnv()); // For function scopes, add the formal parameters and the free variables // from outer scopes to the environment. if (currentScope.isFunction()) { Set<String> formalsAndOuters = currentScope.getOuterVars(); formalsAndOuters.addAll(currentScope.getFormals()); if (currentScope.hasThis()) { formalsAndOuters.add("this"); } for (String name : formalsAndOuters) { JSType declType = currentScope.getDeclaredTypeOf(name); JSType initType; if (declType == null) { initType = envGetType(entryEnv, name); } else if (declType.getFunTypeIfSingletonObj() != null && declType.getFunTypeIfSingletonObj().isConstructor()) { initType = declType.getFunTypeIfSingletonObj().createConstructorObject(); } else { initType = declType; } entryEnv = envPutType(entryEnv, name, initType.withLocation(name)); } entryEnv = envPutType(entryEnv, RETVAL_ID, JSType.UNDEFINED); } // For all scopes, add local variables and (local) function definitions // to the environment. for (String local : currentScope.getLocals()) { entryEnv = envPutType(entryEnv, local, JSType.UNDEFINED); } for (String fnName : currentScope.getLocalFunDefs()) { JSType summaryType = summaries.get(currentScope.getScope(fnName)); FunctionType fnType = summaryType.getFunType(); if (fnType.isConstructor()) { summaryType = fnType.createConstructorObject(); } else { summaryType = summaryType.withProperty( new QualifiedName("prototype"), JSType.TOP_OBJECT); } entryEnv = envPutType(entryEnv, fnName, summaryType); } println("Keeping env: ", entryEnv); envs.put(entryOutEdge, entryEnv); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void removeUnreferencedVars() { CodingConvention convention = compiler.getCodingConvention(); for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) { Var var = it.next(); // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. removeAllAssigns(var); compiler.addToDebugLog("Unreferenced var: " + var.name); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); Node parent = toRemove.getParent(); Preconditions.checkState( toRemove.getType() == Token.VAR || toRemove.getType() == Token.FUNCTION || toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION, "We should only declare vars and functions and function args"); if (toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION) { // Don't remove function arguments here. That's a special case // that's taken care of in removeUnreferencedFunctionArgs. } else if (NodeUtil.isFunctionExpression(toRemove)) { if (!preserveFunctionExpressionNames) { toRemove.getFirstChild().setString(""); compiler.reportCodeChange(); } // Don't remove bleeding functions. } else if (parent != null && parent.getType() == Token.FOR && parent.getChildCount() < 4) { // foreach iterations have 3 children. Leave them alone. } else if (toRemove.getType() == Token.VAR && nameNode.hasChildren() && NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) { // If this is a single var declaration, we can at least remove the // declaration itself and just leave the value, e.g., // var a = foo(); => foo(); if (toRemove.getChildCount() == 1) { parent.replaceChild(toRemove, new Node(Token.EXPR_RESULT, nameNode.removeFirstChild())); compiler.reportCodeChange(); } } else if (toRemove.getType() == Token.VAR && toRemove.getChildCount() > 1) { // For var declarations with multiple names (i.e. var a, b, c), // only remove the unreferenced name toRemove.removeChild(nameNode); compiler.reportCodeChange(); } else if (parent != null) { NodeUtil.removeChild(parent, toRemove); compiler.reportCodeChange(); } } } #location 45 #vulnerability type NULL_DEREFERENCE
#fixed code private void removeUnreferencedVars() { CodingConvention convention = codingConvention; for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) { Var var = it.next(); // Remove calls to inheritance-defining functions where the unreferenced // class is the subclass. for (Node exprCallNode : inheritsCalls.get(var)) { NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode); compiler.reportCodeChange(); } // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. removeAllAssigns(var); compiler.addToDebugLog("Unreferenced var: " + var.name); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); Node parent = toRemove.getParent(); Preconditions.checkState( toRemove.getType() == Token.VAR || toRemove.getType() == Token.FUNCTION || toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION, "We should only declare vars and functions and function args"); if (toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION) { // Don't remove function arguments here. That's a special case // that's taken care of in removeUnreferencedFunctionArgs. } else if (NodeUtil.isFunctionExpression(toRemove)) { if (!preserveFunctionExpressionNames) { toRemove.getFirstChild().setString(""); compiler.reportCodeChange(); } // Don't remove bleeding functions. } else if (parent != null && parent.getType() == Token.FOR && parent.getChildCount() < 4) { // foreach iterations have 3 children. Leave them alone. } else if (toRemove.getType() == Token.VAR && nameNode.hasChildren() && NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) { // If this is a single var declaration, we can at least remove the // declaration itself and just leave the value, e.g., // var a = foo(); => foo(); if (toRemove.getChildCount() == 1) { parent.replaceChild(toRemove, new Node(Token.EXPR_RESULT, nameNode.removeFirstChild())); compiler.reportCodeChange(); } } else if (toRemove.getType() == Token.VAR && toRemove.getChildCount() > 1) { // For var declarations with multiple names (i.e. var a, b, c), // only remove the unreferenced name toRemove.removeChild(nameNode); compiler.reportCodeChange(); } else if (parent != null) { NodeUtil.removeChild(parent, toRemove); compiler.reportCodeChange(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (value.getType() != Token.THIS && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, Node.newString(Token.NAME, newName) .copyInformationFromForTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void outputTracerReport() { OutputStreamWriter output = new OutputStreamWriter(this.err); try { int runtime = 0; int runs = 0; int changes = 0; int diff = 0; int gzDiff = 0; // header output.write("Summary:\n"); output.write("pass,runtime,runs,chancingRuns,reduction,gzReduction\n"); Map<String, Stats> runtimeMap = compiler.tracker.getStats(); for (Entry<String, Stats> entry : runtimeMap.entrySet()) { String key = entry.getKey(); Stats stats = entry.getValue(); output.write(key); output.write(","); output.write(String.valueOf(stats.runtime)); runtime += stats.runtime; output.write(","); output.write(String.valueOf(stats.runs)); runs += stats.runs; output.write(","); output.write(String.valueOf(stats.changes)); changes += stats.changes; output.write(","); output.write(String.valueOf(stats.diff)); diff += stats.diff; output.write(","); output.write(String.valueOf(stats.gzDiff)); gzDiff += stats.gzDiff; output.write("\n"); } output.write("TOTAL"); output.write(","); output.write(String.valueOf(runtime)); output.write(","); output.write(String.valueOf(runs)); output.write(","); output.write(String.valueOf(changes)); output.write(","); output.write(String.valueOf(diff)); output.write(","); output.write(String.valueOf(gzDiff)); output.write("\n"); output.write("\n"); output.write("Log:\n"); output.write( "pass,runtime,runs,chancingRuns,reduction,gzReduction,size,gzSize\n"); List<Stats> runtimeLog = compiler.tracker.getLog(); for (Stats stats : runtimeLog) { output.write(stats.pass); output.write(","); output.write(String.valueOf(stats.runtime)); output.write(","); output.write(String.valueOf(stats.runs)); output.write(","); output.write(String.valueOf(stats.changes)); output.write(","); output.write(String.valueOf(stats.diff)); output.write(","); output.write(String.valueOf(stats.gzDiff)); output.write(","); output.write(String.valueOf(stats.size)); output.write(","); output.write(String.valueOf(stats.gzSize)); output.write("\n"); } output.write("\n"); output.close(); } catch (IOException e) { e.printStackTrace(); } } #location 74 #vulnerability type RESOURCE_LEAK
#fixed code private void outputTracerReport() { JvmMetrics.maybeWriteJvmMetrics(this.err, "verbose:pretty:all"); OutputStreamWriter output = new OutputStreamWriter(this.err); try { int runtime = 0; int runs = 0; int changes = 0; int diff = 0; int gzDiff = 0; // header output.write("Summary:\n"); output.write("pass,runtime,runs,chancingRuns,reduction,gzReduction\n"); Map<String, Stats> runtimeMap = compiler.tracker.getStats(); for (Entry<String, Stats> entry : runtimeMap.entrySet()) { String key = entry.getKey(); Stats stats = entry.getValue(); output.write(key); output.write(","); output.write(String.valueOf(stats.runtime)); runtime += stats.runtime; output.write(","); output.write(String.valueOf(stats.runs)); runs += stats.runs; output.write(","); output.write(String.valueOf(stats.changes)); changes += stats.changes; output.write(","); output.write(String.valueOf(stats.diff)); diff += stats.diff; output.write(","); output.write(String.valueOf(stats.gzDiff)); gzDiff += stats.gzDiff; output.write("\n"); } output.write("TOTAL"); output.write(","); output.write(String.valueOf(runtime)); output.write(","); output.write(String.valueOf(runs)); output.write(","); output.write(String.valueOf(changes)); output.write(","); output.write(String.valueOf(diff)); output.write(","); output.write(String.valueOf(gzDiff)); output.write("\n"); output.write("\n"); output.write("Log:\n"); output.write( "pass,runtime,runs,chancingRuns,reduction,gzReduction,size,gzSize\n"); List<Stats> runtimeLog = compiler.tracker.getLog(); for (Stats stats : runtimeLog) { output.write(stats.pass); output.write(","); output.write(String.valueOf(stats.runtime)); output.write(","); output.write(String.valueOf(stats.runs)); output.write(","); output.write(String.valueOf(stats.changes)); output.write(","); output.write(String.valueOf(stats.diff)); output.write(","); output.write(String.valueOf(stats.gzDiff)); output.write(","); output.write(String.valueOf(stats.size)); output.write(","); output.write(String.valueOf(stats.gzSize)); output.write("\n"); } output.write("\n"); output.close(); } catch (IOException e) { e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void escapeParameters(MustDef output) { for (Iterator<Var> i = jsScope.getVars(); i.hasNext();) { Var v = i.next(); if (v.getParentNode().getType() == Token.LP) { // Assume we no longer know where the parameter comes from // anymore. output.reachingDef.put(v, null); } } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private void escapeParameters(MustDef output) { for (Iterator<Var> i = jsScope.getVars(); i.hasNext();) { Var v = i.next(); if (isParameter(v)) { // Assume we no longer know where the parameter comes from // anymore. output.reachingDef.put(v, null); } } // Also, assume we no longer know anything that depends on a parameter. for (Entry<Var, Definition> pair: output.reachingDef.entrySet()) { Definition value = pair.getValue(); if (value == null) { continue; } for (Var dep : value.depends) { if (isParameter(dep)) { output.reachingDef.put(pair.getKey(), null); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void enterScope(NodeTraversal t) { Scope scope = t.getScope(); // Computes the control flow graph. ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false); cfa.process(null, scope.getRootNode()); cfgStack.push(curCfg); curCfg = cfa.getCfg(); new GraphReachability<Node, ControlFlowGraph.Branch>(curCfg) .compute(curCfg.getEntry().getValue()); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void enterScope(NodeTraversal t) {}
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void enterScope(NodeTraversal t) { // TODO(user): We CAN do this in the global scope, just need to be // careful when something is exported. Liveness uses bit-vector for live // sets so I don't see compilation time will be a problem for running this // pass in the global scope. if (t.inGlobalScope()) { return; } Scope scope = t.getScope(); ControlFlowGraph<Node> cfg = t.getControlFlowGraph(); LiveVariablesAnalysis liveness = new LiveVariablesAnalysis(cfg, scope, compiler); // If the function has exactly 2 params, mark them as escaped. This is // a work-around for an IE bug where it throws an exception if you // write to the parameters of the callback in a sort(). See: // http://code.google.com/p/closure-compiler/issues/detail?id=58 if (scope.getRootNode().getFirstChild().getNext().getChildCount() == 2) { liveness.markAllParametersEscaped(); } liveness.analyze(); UndiGraph<Var, Void> interferenceGraph = computeVariableNamesInterferenceGraph( t, cfg, liveness.getEscapedLocals()); GraphColoring<Var, Void> coloring = new GreedyGraphColoring<Var, Void>(interferenceGraph, coloringTieBreaker); coloring.color(); colorings.push(coloring); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void enterScope(NodeTraversal t) { Scope scope = t.getScope(); if (!shouldOptimizeScope(scope)) { return; } ControlFlowGraph<Node> cfg = t.getControlFlowGraph(); LiveVariablesAnalysis liveness = new LiveVariablesAnalysis(cfg, scope, compiler); // If the function has exactly 2 params, mark them as escaped. This is // a work-around for an IE bug where it throws an exception if you // write to the parameters of the callback in a sort(). See: // http://code.google.com/p/closure-compiler/issues/detail?id=58 if (scope.getRootNode().getFirstChild().getNext().getChildCount() == 2) { liveness.markAllParametersEscaped(); } liveness.analyze(); UndiGraph<Var, Void> interferenceGraph = computeVariableNamesInterferenceGraph( t, cfg, liveness.getEscapedLocals()); GraphColoring<Var, Void> coloring = new GreedyGraphColoring<Var, Void>(interferenceGraph, coloringTieBreaker); coloring.color(); colorings.push(coloring); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String getFunctionAnnotation(Node fnNode) { Preconditions.checkState(fnNode.getType() == Token.FUNCTION); StringBuilder sb = new StringBuilder("/**\n"); JSType type = fnNode.getJSType(); if (type == null || type.isUnknownType()) { return ""; } FunctionType funType = type.toMaybeFunctionType(); // We need to use the child nodes of the function as the nodes for the // parameters of the function type do not have the real parameter names. // FUNCTION // NAME // LP // NAME param1 // NAME param2 if (fnNode != null) { Node paramNode = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); // Param types for (Node n : funType.getParameters()) { // Bail out if the paramNode is not there. if (paramNode == null) { break; } sb.append(" * @param {" + getParameterNodeJSDocType(n) + "} "); sb.append(paramNode.getString()); sb.append("\n"); paramNode = paramNode.getNext(); } } // Return type JSType retType = funType.getReturnType(); if (retType != null && !retType.isUnknownType() && !retType.isEmptyType()) { sb.append(" * @return {" + retType + "}\n"); } // Constructor/interface if (funType.isConstructor() || funType.isInterface()) { FunctionType superConstructor = funType.getSuperClassConstructor(); if (superConstructor != null) { ObjectType superInstance = funType.getSuperClassConstructor().getInstanceType(); if (!superInstance.toString().equals("Object")) { sb.append(" * @extends {" + superInstance + "}\n"); } } if (funType.isInterface()) { for (ObjectType interfaceType : funType.getExtendedInterfaces()) { sb.append(" * @extends {" + interfaceType + "}\n"); } } // Avoid duplicates, add implemented type to a set first Set<String> interfaces = Sets.newTreeSet(); for (ObjectType interfaze : funType.getImplementedInterfaces()) { interfaces.add(interfaze.toString()); } for (String interfaze : interfaces) { sb.append(" * @implements {" + interfaze + "}\n"); } if (funType.isConstructor()) { sb.append(" * @constructor\n"); } else if (funType.isInterface()) { sb.append(" * @interface\n"); } } if (fnNode != null && fnNode.getBooleanProp(Node.IS_DISPATCHER)) { sb.append(" * @javadispatch\n"); } sb.append(" */\n"); return sb.toString(); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private String getFunctionAnnotation(Node fnNode) { Preconditions.checkState(fnNode.getType() == Token.FUNCTION); StringBuilder sb = new StringBuilder("/**\n"); JSType type = fnNode.getJSType(); if (type == null || type.isUnknownType()) { return ""; } FunctionType funType = (FunctionType) fnNode.getJSType(); // We need to use the child nodes of the function as the nodes for the // parameters of the function type do not have the real parameter names. // FUNCTION // NAME // LP // NAME param1 // NAME param2 if (fnNode != null) { Node paramNode = NodeUtil.getFunctionParameters(fnNode).getFirstChild(); // Param types for (Node n : funType.getParameters()) { // Bail out if the paramNode is not there. if (paramNode == null) { break; } sb.append(" * @param {" + getParameterNodeJSDocType(n) + "} "); sb.append(paramNode.getString()); sb.append("\n"); paramNode = paramNode.getNext(); } } // Return type JSType retType = funType.getReturnType(); if (retType != null && !retType.isUnknownType() && !retType.isEmptyType()) { sb.append(" * @return {" + retType + "}\n"); } // Constructor/interface if (funType.isConstructor() || funType.isInterface()) { FunctionType superConstructor = funType.getSuperClassConstructor(); if (superConstructor != null) { ObjectType superInstance = funType.getSuperClassConstructor().getInstanceType(); if (!superInstance.toString().equals("Object")) { sb.append(" * @extends {" + superInstance + "}\n"); } } if (funType.isInterface()) { for (ObjectType interfaceType : funType.getExtendedInterfaces()) { sb.append(" * @extends {" + interfaceType + "}\n"); } } // Avoid duplicates, add implemented type to a set first Set<String> interfaces = Sets.newTreeSet(); for (ObjectType interfaze : funType.getImplementedInterfaces()) { interfaces.add(interfaze.toString()); } for (String interfaze : interfaces) { sb.append(" * @implements {" + interfaze + "}\n"); } if (funType.isConstructor()) { sb.append(" * @constructor\n"); } else if (funType.isInterface()) { sb.append(" * @interface\n"); } } if (fnNode != null && fnNode.getBooleanProp(Node.IS_DISPATCHER)) { sb.append(" * @javadispatch\n"); } sb.append(" */\n"); return sb.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( null, safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code FunctionTypeBuilder inferThisType(JSDocInfo info, @Nullable Node owner) { ObjectType maybeThisType = null; if (info != null && info.hasThisType()) { maybeThisType = ObjectType.cast( info.getThisType().evaluate(scope, typeRegistry)); } if (maybeThisType != null) { // TODO(user): Doing an instanceof check here is too // restrictive as (Date,Error) is, for instance, an object type // even though its implementation is a UnionType. Would need to // create interfaces JSType, ObjectType, FunctionType etc and have // separate implementation instead of the class hierarchy, so that // union types can also be object types, etc. thisType = maybeThisType; } else if (owner != null && (info == null || !info.hasType())) { // If the function is of the form: // x.prototype.y = function() {} // then we can assume "x" is the @this type. On the other hand, // if it's of the form: // /** @type {Function} */ x.prototype.y; // then we should not give it a @this type. String ownerTypeName = owner.getQualifiedName(); ObjectType ownerType = ObjectType.cast( typeRegistry.getType( scope, ownerTypeName, sourceName, owner.getLineno(), owner.getCharno())); if (ownerType != null) { thisType = ownerType; } } return this; } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code FunctionTypeBuilder(String fnName, AbstractCompiler compiler, Node errorRoot, String sourceName, Scope scope) { Preconditions.checkNotNull(errorRoot); this.fnName = fnName == null ? "" : fnName; this.codingConvention = compiler.getCodingConvention(); this.typeRegistry = compiler.getTypeRegistry(); this.errorRoot = errorRoot; this.sourceName = sourceName; this.compiler = compiler; this.scope = scope; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createPropertyScopeFor(Symbol s) { // In order to build a property scope for s, we will need to build // a property scope for all its implicit prototypes first. This means // that sometimes we will already have built its property scope // for a previous symbol. if (s.propertyScope != null) { return; } SymbolScope parentPropertyScope = null; ObjectType type = s.getType().toObjectType(); ObjectType proto = type.getParentScope(); if (proto != null && proto != type && proto.getConstructor() != null) { Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor()); if (parentSymbol != null) { createPropertyScopeFor(parentSymbol); parentPropertyScope = parentSymbol.getPropertyScope(); } } ObjectType instanceType = type; Iterable<String> propNames = type.getOwnPropertyNames(); if (instanceType.isFunctionPrototypeType()) { // Merge the properties of "Foo.prototype" and "new Foo()" together. instanceType = instanceType.getOwnerFunction().getInstanceType(); Set<String> set = Sets.newHashSet(propNames); Iterables.addAll(set, instanceType.getOwnPropertyNames()); propNames = set; } s.propertyScope = new SymbolScope(null, parentPropertyScope, type); for (String propName : propNames) { StaticSlot<JSType> newProp = instanceType.getSlot(propName); if (newProp.getDeclaration() == null) { // Skip properties without declarations. We won't know how to index // them, because we index things by node. continue; } // We have symbol tables that do not do type analysis. They just try // to build a complete index of all objects in the program. So we might // already have symbols for things like "Foo.bar". If this happens, // throw out the old symbol and use the type-based symbol. Symbol oldProp = getScope(s).getSlot(s.getName() + "." + propName); if (oldProp != null) { removeSymbol(oldProp); } Symbol newSym = copySymbolTo(newProp, s.propertyScope); if (oldProp != null) { if (newSym.getJSDocInfo() == null) { newSym.setJSDocInfo(oldProp.getJSDocInfo()); } newSym.propertyScope = oldProp.propertyScope; for (Reference ref : oldProp.references.values()) { newSym.defineReferenceAt(ref.getNode()); } } } } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private void createPropertyScopeFor(Symbol s) { // In order to build a property scope for s, we will need to build // a property scope for all its implicit prototypes first. This means // that sometimes we will already have built its property scope // for a previous symbol. if (s.propertyScope != null) { return; } SymbolScope parentPropertyScope = null; ObjectType type = s.getType() == null ? null : s.getType().toObjectType(); if (type == null) { return; } ObjectType proto = type.getParentScope(); if (proto != null && proto != type && proto.getConstructor() != null) { Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor()); if (parentSymbol != null) { createPropertyScopeFor(parentSymbol); parentPropertyScope = parentSymbol.getPropertyScope(); } } ObjectType instanceType = type; Iterable<String> propNames = type.getOwnPropertyNames(); if (instanceType.isFunctionPrototypeType()) { // Merge the properties of "Foo.prototype" and "new Foo()" together. instanceType = instanceType.getOwnerFunction().getInstanceType(); Set<String> set = Sets.newHashSet(propNames); Iterables.addAll(set, instanceType.getOwnPropertyNames()); propNames = set; } s.setPropertyScope(new SymbolScope(null, parentPropertyScope, type, s)); for (String propName : propNames) { StaticSlot<JSType> newProp = instanceType.getSlot(propName); if (newProp.getDeclaration() == null) { // Skip properties without declarations. We won't know how to index // them, because we index things by node. continue; } // We have symbol tables that do not do type analysis. They just try // to build a complete index of all objects in the program. So we might // already have symbols for things like "Foo.bar". If this happens, // throw out the old symbol and use the type-based symbol. Symbol oldProp = getScope(s).getSlot(s.getName() + "." + propName); if (oldProp != null) { removeSymbol(oldProp); } Symbol newSym = copySymbolTo(newProp, s.propertyScope); if (oldProp != null) { if (newSym.getJSDocInfo() == null) { newSym.setJSDocInfo(oldProp.getJSDocInfo()); } newSym.setPropertyScope(oldProp.propertyScope); for (Reference ref : oldProp.references.values()) { newSym.defineReferenceAt(ref.getNode()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private FlowScope traverse(Node n, FlowScope scope) { switch (n.getType()) { case Token.ASSIGN: scope = traverseAssign(n, scope); break; case Token.NAME: scope = traverseName(n, scope); break; case Token.GETPROP: scope = traverseGetProp(n, scope); break; case Token.AND: scope = traverseAnd(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.OR: scope = traverseOr(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.HOOK: scope = traverseHook(n, scope); break; case Token.OBJECTLIT: scope = traverseObjectLiteral(n, scope); break; case Token.CALL: scope = traverseCall(n, scope); break; case Token.NEW: scope = traverseNew(n, scope); break; case Token.ASSIGN_ADD: case Token.ADD: scope = traverseAdd(n, scope); break; case Token.POS: case Token.NEG: scope = traverse(n.getFirstChild(), scope); // Find types. n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.ARRAYLIT: scope = traverseArrayLiteral(n, scope); break; case Token.THIS: n.setJSType(scope.getTypeOfThis()); break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.LSH: case Token.RSH: case Token.ASSIGN_URSH: case Token.URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITOR: case Token.ASSIGN_MUL: case Token.ASSIGN_SUB: case Token.DIV: case Token.MOD: case Token.BITAND: case Token.BITXOR: case Token.BITOR: case Token.MUL: case Token.SUB: case Token.DEC: case Token.INC: case Token.BITNOT: scope = traverseChildren(n, scope); n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.PARAM_LIST: scope = traverse(n.getFirstChild(), scope); n.setJSType(getJSType(n.getFirstChild())); break; case Token.COMMA: scope = traverseChildren(n, scope); n.setJSType(getJSType(n.getLastChild())); break; case Token.TYPEOF: scope = traverseChildren(n, scope); n.setJSType(getNativeType(STRING_TYPE)); break; case Token.DELPROP: case Token.LT: case Token.LE: case Token.GT: case Token.GE: case Token.NOT: case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.INSTANCEOF: case Token.IN: scope = traverseChildren(n, scope); n.setJSType(getNativeType(BOOLEAN_TYPE)); break; case Token.GETELEM: scope = traverseGetElem(n, scope); break; case Token.EXPR_RESULT: scope = traverseChildren(n, scope); if (n.getFirstChild().isGetProp()) { ensurePropertyDeclared(n.getFirstChild()); } break; case Token.SWITCH: scope = traverse(n.getFirstChild(), scope); break; case Token.RETURN: scope = traverseReturn(n, scope); break; case Token.VAR: case Token.THROW: scope = traverseChildren(n, scope); break; case Token.CATCH: scope = traverseCatch(n, scope); break; case Token.CAST: scope = traverseChildren(n, scope); break; } // TODO(johnlenz): remove this after the CAST node change has shaken out. if (!n.isFunction()) { JSDocInfo info = n.getJSDocInfo(); if (info != null && info.hasType()) { JSType castType = info.getType().evaluate(syntacticScope, registry); // A stubbed type declaration on a qualified name should take // effect for all subsequent accesses of that name, // so treat it the same as an assign to that name. if (n.isQualifiedName() && n.getParent().isExprResult()) { updateScopeForTypeChange(scope, n, n.getJSType(), castType); } n.setJSType(castType); } } return scope; } #location 155 #vulnerability type NULL_DEREFERENCE
#fixed code private FlowScope traverse(Node n, FlowScope scope) { switch (n.getType()) { case Token.ASSIGN: scope = traverseAssign(n, scope); break; case Token.NAME: scope = traverseName(n, scope); break; case Token.GETPROP: scope = traverseGetProp(n, scope); break; case Token.AND: scope = traverseAnd(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.OR: scope = traverseOr(n, scope).getJoinedFlowScope() .createChildFlowScope(); break; case Token.HOOK: scope = traverseHook(n, scope); break; case Token.OBJECTLIT: scope = traverseObjectLiteral(n, scope); break; case Token.CALL: scope = traverseCall(n, scope); break; case Token.NEW: scope = traverseNew(n, scope); break; case Token.ASSIGN_ADD: case Token.ADD: scope = traverseAdd(n, scope); break; case Token.POS: case Token.NEG: scope = traverse(n.getFirstChild(), scope); // Find types. n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.ARRAYLIT: scope = traverseArrayLiteral(n, scope); break; case Token.THIS: n.setJSType(scope.getTypeOfThis()); break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.LSH: case Token.RSH: case Token.ASSIGN_URSH: case Token.URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITAND: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITOR: case Token.ASSIGN_MUL: case Token.ASSIGN_SUB: case Token.DIV: case Token.MOD: case Token.BITAND: case Token.BITXOR: case Token.BITOR: case Token.MUL: case Token.SUB: case Token.DEC: case Token.INC: case Token.BITNOT: scope = traverseChildren(n, scope); n.setJSType(getNativeType(NUMBER_TYPE)); break; case Token.PARAM_LIST: scope = traverse(n.getFirstChild(), scope); n.setJSType(getJSType(n.getFirstChild())); break; case Token.COMMA: scope = traverseChildren(n, scope); n.setJSType(getJSType(n.getLastChild())); break; case Token.TYPEOF: scope = traverseChildren(n, scope); n.setJSType(getNativeType(STRING_TYPE)); break; case Token.DELPROP: case Token.LT: case Token.LE: case Token.GT: case Token.GE: case Token.NOT: case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: case Token.INSTANCEOF: case Token.IN: scope = traverseChildren(n, scope); n.setJSType(getNativeType(BOOLEAN_TYPE)); break; case Token.GETELEM: scope = traverseGetElem(n, scope); break; case Token.EXPR_RESULT: scope = traverseChildren(n, scope); if (n.getFirstChild().isGetProp()) { ensurePropertyDeclared(n.getFirstChild()); } break; case Token.SWITCH: scope = traverse(n.getFirstChild(), scope); break; case Token.RETURN: scope = traverseReturn(n, scope); break; case Token.VAR: case Token.THROW: scope = traverseChildren(n, scope); break; case Token.CATCH: scope = traverseCatch(n, scope); break; case Token.CAST: scope = traverseChildren(n, scope); JSDocInfo info = n.getJSDocInfo(); if (info != null && info.hasType()) { n.setJSType(info.getType().evaluate(syntacticScope, registry)); } break; } return scope; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( null, safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph( NodeTraversal t, ControlFlowGraph<Node> cfg, Set<Var> escaped) { UndiGraph<Var, Void> interferenceGraph = LinkedUndirectedGraph.create(); Scope scope = t.getScope(); // First create a node for each non-escaped variable. for (Iterator<Var> i = scope.getVars(); i.hasNext();) { Var v = i.next(); if (!escaped.contains(v)) { // TODO(user): In theory, we CAN coalesce function names just like // any variables. Our Liveness analysis captures this just like it as // described in the specification. However, we saw some zipped and // and unzipped size increase after this. We are not totally sure why // that is but, for now, we will respect the dead functions and not play // around with it. if (!NodeUtil.isFunction(v.getParentNode())) { interferenceGraph.createNode(v); } } } // Go through each variable and try to connect them. for (Iterator<Var> i1 = scope.getVars(); i1.hasNext();) { Var v1 = i1.next(); NEXT_VAR_PAIR: for (Iterator<Var> i2 = scope.getVars(); i2.hasNext();) { Var v2 = i2.next(); // Skip duplicate pairs. if (v1.index >= v2.index) { continue; } if (!interferenceGraph.hasNode(v1) || !interferenceGraph.hasNode(v2)) { // Skip nodes that were not added. They are globals and escaped // locals. Also avoid merging a variable with itself. continue NEXT_VAR_PAIR; } if (v1.getParentNode().getType() == Token.LP && v2.getParentNode().getType() == Token.LP) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } // Go through every CFG node in the program and look at // this variable pair. If they are both live at the same // time, add an edge between them and continue to the next pair. NEXT_CROSS_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_CROSS_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); // Check the live states and add edge when possible. if ((state.getIn().isLive(v1) && state.getIn().isLive(v2)) || (state.getOut().isLive(v1) && state.getOut().isLive(v2))) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } } // v1 and v2 might not have an edge between them! woohoo. there's // one last sanity check that we have to do: we have to check // if there's a collision *within* the cfg node. NEXT_INTRA_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_INTRA_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); boolean v1OutLive = state.getOut().isLive(v1); boolean v2OutLive = state.getOut().isLive(v2); CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker( new LiveRangeChecker(v1, v2OutLive ? null : v2), new LiveRangeChecker(v2, v1OutLive ? null : v1)); NodeTraversal.traverse( compiler, cfgNode.getValue(), checker); if (checker.connectIfCrossed(interferenceGraph)) { continue NEXT_VAR_PAIR; } } } } return interferenceGraph; } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph( NodeTraversal t, ControlFlowGraph<Node> cfg, Set<Var> escaped) { UndiGraph<Var, Void> interferenceGraph = LinkedUndirectedGraph.create(); // For all variables V not in unsafeCrossRange, // LiveRangeChecker(V, X) and LiveRangeChecker(Y, V) will never add a edge // to the interferenceGraph. In other words, we don't need to use // LiveRangeChecker on variable pair (A, B) if both A and B are not // in the unsafeCrossRangeSet. See PrescreenCrossLiveRange for details. Set<Var> unsafeCrossRangeSet = Sets.newHashSet(); Scope scope = t.getScope(); for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue; } for (Iterator<Var> i = scope.getVars(); i.hasNext();) { final Var v = i.next(); if (!unsafeCrossRangeSet.contains(v)) { FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); PrescreenCrossLiveRange check = new PrescreenCrossLiveRange(v, state.getOut()); NodeTraversal.traverse(compiler, cfgNode.getValue(), check); if (!check.isSafe()) { unsafeCrossRangeSet.add(v); } } } } // First create a node for each non-escaped variable. for (Iterator<Var> i = scope.getVars(); i.hasNext();) { Var v = i.next(); if (!escaped.contains(v)) { // TODO(user): In theory, we CAN coalesce function names just like // any variables. Our Liveness analysis captures this just like it as // described in the specification. However, we saw some zipped and // and unzipped size increase after this. We are not totally sure why // that is but, for now, we will respect the dead functions and not play // around with it. if (!NodeUtil.isFunction(v.getParentNode())) { interferenceGraph.createNode(v); } } } // Go through each variable and try to connect them. for (Iterator<Var> i1 = scope.getVars(); i1.hasNext();) { Var v1 = i1.next(); NEXT_VAR_PAIR: for (Iterator<Var> i2 = scope.getVars(); i2.hasNext();) { Var v2 = i2.next(); // Skip duplicate pairs. if (v1.index >= v2.index) { continue; } if (!interferenceGraph.hasNode(v1) || !interferenceGraph.hasNode(v2)) { // Skip nodes that were not added. They are globals and escaped // locals. Also avoid merging a variable with itself. continue NEXT_VAR_PAIR; } if (v1.getParentNode().getType() == Token.LP && v2.getParentNode().getType() == Token.LP) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } // Go through every CFG node in the program and look at // this variable pair. If they are both live at the same // time, add an edge between them and continue to the next pair. NEXT_CROSS_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_CROSS_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); // Check the live states and add edge when possible. if ((state.getIn().isLive(v1) && state.getIn().isLive(v2)) || (state.getOut().isLive(v1) && state.getOut().isLive(v2))) { interferenceGraph.connectIfNotFound(v1, null, v2); continue NEXT_VAR_PAIR; } } // v1 and v2 might not have an edge between them! woohoo. there's // one last sanity check that we have to do: we have to check // if there's a collision *within* the cfg node. if (!unsafeCrossRangeSet.contains(v1) && !unsafeCrossRangeSet.contains(v2)) { continue NEXT_VAR_PAIR; } NEXT_INTRA_CFG_NODE: for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) { if (cfg.isImplicitReturn(cfgNode)) { continue NEXT_INTRA_CFG_NODE; } FlowState<LiveVariableLattice> state = cfgNode.getAnnotation(); boolean v1OutLive = state.getOut().isLive(v1); boolean v2OutLive = state.getOut().isLive(v2); CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker( new LiveRangeChecker(v1, v2OutLive ? null : v2), new LiveRangeChecker(v2, v1OutLive ? null : v1)); NodeTraversal.traverse( compiler, cfgNode.getValue(), checker); if (checker.connectIfCrossed(interferenceGraph)) { continue NEXT_VAR_PAIR; } } } } return interferenceGraph; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Symbol getSymbolForInstancesOf(FunctionType fn) { Preconditions.checkState(fn.isConstructor() || fn.isInterface()); ObjectType pType = fn.getPrototype(); String name = pType.getReferenceName(); if (name == null || globalScope == null) { return null; } Node source = fn.getSource(); return (source == null ? globalScope : getEnclosingScope(source)).getSlot(name); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public Symbol getSymbolForInstancesOf(FunctionType fn) { Preconditions.checkState(fn.isConstructor() || fn.isInterface()); ObjectType pType = fn.getPrototype(); return getSymbolForName(fn.getSource(), pType.getReferenceName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void enterScope(NodeTraversal t) { Scope scope = t.getScope(); // Computes the control flow graph. ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false); cfa.process(null, scope.getRootNode()); cfgStack.push(curCfg); curCfg = cfa.getCfg(); new GraphReachability<Node, ControlFlowGraph.Branch>(curCfg) .compute(curCfg.getEntry().getValue()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void enterScope(NodeTraversal t) {}
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (value.getType() != Token.THIS && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, Node.newString(Token.NAME, newName) .copyInformationFromForTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void removeUnreferencedVars() { CodingConvention convention = compiler.getCodingConvention(); for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) { Var var = it.next(); // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. removeAllAssigns(var); compiler.addToDebugLog("Unreferenced var: " + var.name); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); Node parent = toRemove.getParent(); Preconditions.checkState( toRemove.getType() == Token.VAR || toRemove.getType() == Token.FUNCTION || toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION, "We should only declare vars and functions and function args"); if (toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION) { // Don't remove function arguments here. That's a special case // that's taken care of in removeUnreferencedFunctionArgs. } else if (NodeUtil.isFunctionExpression(toRemove)) { if (!preserveFunctionExpressionNames) { toRemove.getFirstChild().setString(""); compiler.reportCodeChange(); } // Don't remove bleeding functions. } else if (parent != null && parent.getType() == Token.FOR && parent.getChildCount() < 4) { // foreach iterations have 3 children. Leave them alone. } else if (toRemove.getType() == Token.VAR && nameNode.hasChildren() && NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) { // If this is a single var declaration, we can at least remove the // declaration itself and just leave the value, e.g., // var a = foo(); => foo(); if (toRemove.getChildCount() == 1) { parent.replaceChild(toRemove, new Node(Token.EXPR_RESULT, nameNode.removeFirstChild())); compiler.reportCodeChange(); } } else if (toRemove.getType() == Token.VAR && toRemove.getChildCount() > 1) { // For var declarations with multiple names (i.e. var a, b, c), // only remove the unreferenced name toRemove.removeChild(nameNode); compiler.reportCodeChange(); } else if (parent != null) { NodeUtil.removeChild(parent, toRemove); compiler.reportCodeChange(); } } } #location 45 #vulnerability type NULL_DEREFERENCE
#fixed code private void removeUnreferencedVars() { CodingConvention convention = codingConvention; for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) { Var var = it.next(); // Remove calls to inheritance-defining functions where the unreferenced // class is the subclass. for (Node exprCallNode : inheritsCalls.get(var)) { NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode); compiler.reportCodeChange(); } // Regardless of what happens to the original declaration, // we need to remove all assigns, because they may contain references // to other unreferenced variables. removeAllAssigns(var); compiler.addToDebugLog("Unreferenced var: " + var.name); Node nameNode = var.nameNode; Node toRemove = nameNode.getParent(); Node parent = toRemove.getParent(); Preconditions.checkState( toRemove.getType() == Token.VAR || toRemove.getType() == Token.FUNCTION || toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION, "We should only declare vars and functions and function args"); if (toRemove.getType() == Token.LP && parent.getType() == Token.FUNCTION) { // Don't remove function arguments here. That's a special case // that's taken care of in removeUnreferencedFunctionArgs. } else if (NodeUtil.isFunctionExpression(toRemove)) { if (!preserveFunctionExpressionNames) { toRemove.getFirstChild().setString(""); compiler.reportCodeChange(); } // Don't remove bleeding functions. } else if (parent != null && parent.getType() == Token.FOR && parent.getChildCount() < 4) { // foreach iterations have 3 children. Leave them alone. } else if (toRemove.getType() == Token.VAR && nameNode.hasChildren() && NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) { // If this is a single var declaration, we can at least remove the // declaration itself and just leave the value, e.g., // var a = foo(); => foo(); if (toRemove.getChildCount() == 1) { parent.replaceChild(toRemove, new Node(Token.EXPR_RESULT, nameNode.removeFirstChild())); compiler.reportCodeChange(); } } else if (toRemove.getType() == Token.VAR && toRemove.getChildCount() > 1) { // For var declarations with multiple names (i.e. var a, b, c), // only remove the unreferenced name toRemove.removeChild(nameNode); compiler.reportCodeChange(); } else if (parent != null) { NodeUtil.removeChild(parent, toRemove); compiler.reportCodeChange(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (value.getType() != Token.THIS && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, Node.newString(Token.NAME, newName) .copyInformationFromForTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private Node aliasAndInlineArguments( Node fnTemplateRoot, LinkedHashMap<String, Node> argMap, Set<String> namesToAlias) { if (namesToAlias == null || namesToAlias.isEmpty()) { // There are no names to alias, just inline the arguments directly. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, argMap); Preconditions.checkState(result == fnTemplateRoot); return result; } else { // Create local alias of names that can not be safely // used directly. // An arg map that will be updated to contain the // safe aliases. Map<String, Node> newArgMap = Maps.newHashMap(argMap); // Declare the alias in the same order as they // are declared. List<Node> newVars = Lists.newLinkedList(); // NOTE: argMap is a linked map so we get the parameters in the // order that they were declared. for (Entry<String, Node> entry : argMap.entrySet()) { String name = entry.getKey(); if (namesToAlias.contains(name)) { if (name.equals(THIS_MARKER)) { boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot); // Update "this", this is only necessary if "this" is referenced // and the value of "this" is not Token.THIS, or the value of "this" // has side effects. Node value = entry.getValue(); if (!value.isThis() && (referencesThis || NodeUtil.mayHaveSideEffects(value, compiler))) { String newName = getUniqueThisName(); Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(newName, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.put(THIS_MARKER, Node.newString(Token.NAME, newName) .copyInformationFromForTree(newValue)); } } else { Node newValue = entry.getValue().cloneTree(); Node newNode = NodeUtil.newVarNode(name, newValue) .copyInformationFromForTree(newValue); newVars.add(0, newNode); // Remove the parameter from the list to replace. newArgMap.remove(name); } } } // Inline the arguments. Node result = FunctionArgumentInjector.inject( compiler, fnTemplateRoot, null, newArgMap); Preconditions.checkState(result == fnTemplateRoot); // Now that the names have been replaced, add the new aliases for // the old names. for (Node n : newVars) { fnTemplateRoot.addChildToFront(n); } return result; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<JSSourceFile> getDefaultExterns() throws IOException { InputStream input = CommandLineRunner.class.getResourceAsStream( "/externs.zip"); ZipInputStream zip = new ZipInputStream(input); Map<String, JSSourceFile> externsMap = Maps.newHashMap(); for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) { LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize()); externsMap.put(entry.getName(), JSSourceFile.fromInputStream( // Give the files an odd prefix, so that they do not conflict // with the user's files. "externs.zip//" + entry.getName(), entryStream)); } Preconditions.checkState( externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)), "Externs zip must match our hard-coded list of externs."); // Order matters, so the resources must be added to the result list // in the expected order. List<JSSourceFile> externs = Lists.newArrayList(); for (String key : DEFAULT_EXTERNS_NAMES) { externs.add(externsMap.get(key)); } return externs; } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public static List<JSSourceFile> getDefaultExterns() throws IOException { InputStream input = CommandLineRunner.class.getResourceAsStream( "/externs.zip"); ZipInputStream zip = new ZipInputStream(input); Map<String, JSSourceFile> externsMap = Maps.newHashMap(); for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) { BufferedInputStream entryStream = new BufferedInputStream( new LimitInputStream(zip, entry.getSize())); externsMap.put(entry.getName(), JSSourceFile.fromInputStream( // Give the files an odd prefix, so that they do not conflict // with the user's files. "externs.zip//" + entry.getName(), entryStream)); } Preconditions.checkState( externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)), "Externs zip must match our hard-coded list of externs."); // Order matters, so the resources must be added to the result list // in the expected order. List<JSSourceFile> externs = Lists.newArrayList(); for (String key : DEFAULT_EXTERNS_NAMES) { externs.add(externsMap.get(key)); } return externs; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code int processResults(Result result, List<JSModule> modules, B options) throws FlagUsageException, IOException { if (config.computePhaseOrdering) { return 0; } if (config.printPassGraph) { if (compiler.getRoot() == null) { return 1; } else { jsOutput.append( DotFormatter.toDot(compiler.getPassConfig().getPassGraph())); jsOutput.append('\n'); return 0; } } if (config.printAst) { if (compiler.getRoot() == null) { return 1; } else { ControlFlowGraph<Node> cfg = compiler.computeCFG(); DotFormatter.appendDot( compiler.getRoot().getLastChild(), cfg, jsOutput); jsOutput.append('\n'); return 0; } } if (config.printTree) { if (compiler.getRoot() == null) { jsOutput.append("Code contains errors; no tree was generated.\n"); return 1; } else { compiler.getRoot().appendStringTree(jsOutput); jsOutput.append("\n"); return 0; } } rootRelativePathsMap = constructRootRelativePathsMap(); if (config.skipNormalOutputs) { // Output the manifest and bundle files if requested. outputManifest(); outputBundle(); return 0; } else if (result.success) { if (modules == null) { writeOutput( jsOutput, compiler, compiler.toSource(), config.outputWrapper, OUTPUT_WRAPPER_MARKER); // Output the source map if requested. outputSourceMap(options, config.jsOutputFile); } else { parsedModuleWrappers = parseModuleWrappers( config.moduleWrapper, modules); maybeCreateDirsForPath(config.moduleOutputPathPrefix); // If the source map path is in fact a pattern for each // module, create a stream per-module. Otherwise, create // a single source map. Writer mapOut = null; if (!shouldGenerateMapPerModule(options)) { mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, null)); } for (JSModule m : modules) { if (shouldGenerateMapPerModule(options)) { mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, m)); } Writer writer = fileNameToLegacyOutputWriter(getModuleOutputFileName(m)); if (options.sourceMapOutputPath != null) { compiler.getSourceMap().reset(); } writeModuleOutput(writer, m); if (options.sourceMapOutputPath != null) { compiler.getSourceMap().appendTo(mapOut, m.getName()); } writer.close(); if (shouldGenerateMapPerModule(options) && mapOut != null) { mapOut.close(); mapOut = null; } } if (mapOut != null) { mapOut.close(); } } // Output the externs if required. if (options.externExportsPath != null) { Writer eeOut = openExternExportsStream(options, config.jsOutputFile); eeOut.append(result.externExport); eeOut.close(); } // Output the variable and property name maps if requested. outputNameMaps(options); // Output the manifest and bundle files if requested. outputManifest(); outputBundle(); if (options.tracer.isOn()) { outputTracerReport(); } } // return 0 if no errors, the error count otherwise return Math.min(result.errors.length, 0x7f); } #location 105 #vulnerability type NULL_DEREFERENCE
#fixed code AbstractCommandLineRunner() { this(System.out, System.err); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Node tryFoldFor(Node n) { Preconditions.checkArgument(n.getType() == Token.FOR); // This is not a FOR-IN loop if (n.getChildCount() != 4) { return n; } // There isn't an initializer if (n.getFirstChild().getType() != Token.EMPTY) { return n; } Node cond = NodeUtil.getConditionExpression(n); if (NodeUtil.getBooleanValue(cond) != TernaryValue.FALSE) { return n; } NodeUtil.redeclareVarsInsideBranch(n); NodeUtil.removeChild(n.getParent(), n); reportCodeChange(); return null; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code Node tryOptimizeBlock(Node n) { // Remove any useless children for (Node c = n.getFirstChild(); c != null; ) { Node next = c.getNext(); // save c.next, since 'c' may be removed if (!mayHaveSideEffects(c)) { // TODO(johnlenz): determine what this is actually removing. Candidates // include: EMPTY nodes, control structures without children // (removing infinite loops), empty try blocks. What else? n.removeChild(c); // lazy kids reportCodeChange(); } else { tryOptimizeConditionalAfterAssign(c); } c = next; } if (n.isSyntheticBlock() || n.getParent() == null) { return n; } // Try to remove the block. if (NodeUtil.tryMergeBlock(n)) { reportCodeChange(); return null; } return n; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void outputManifest() throws IOException { String outputManifest = config.outputManifest; if (Strings.isEmpty(outputManifest)) { return; } JSModuleGraph graph = compiler.getModuleGraph(); if (shouldGenerateManifestPerModule()) { // Generate per-module manifests. Iterable<JSModule> modules = graph.getAllModules(); for (JSModule module : modules) { Writer out = fileNameToOutputWriter(expandManifest(module)); printManifestTo(module.getInputs(), out); out.close(); } } else { // Generate a single file manifest. Writer out = fileNameToOutputWriter(expandManifest(null)); if (graph == null) { printManifestTo(compiler.getInputsInOrder(), out); } else { printModuleGraphManifestTo(graph, out); } out.close(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code private void outputManifest() throws IOException { List<String> outputManifests = config.outputManifests; if (outputManifests.isEmpty()) { return; } for (String outputManifest : outputManifests) { if (outputManifest.isEmpty()) { continue; } JSModuleGraph graph = compiler.getModuleGraph(); if (shouldGenerateManifestPerModule(outputManifest)) { // Generate per-module manifests. Iterable<JSModule> modules = graph.getAllModules(); for (JSModule module : modules) { Writer out = fileNameToOutputWriter( expandManifest(module, outputManifest)); printManifestTo(module.getInputs(), out); out.close(); } } else { // Generate a single file manifest. Writer out = fileNameToOutputWriter( expandManifest(null, outputManifest)); if (graph == null) { printManifestTo(compiler.getInputsInOrder(), out); } else { printModuleGraphManifestTo(graph, out); } out.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code private Node inlineReturnValue(Node callNode, Node fnNode) { Node block = fnNode.getLastChild(); Node callParentNode = callNode.getParent(); // NOTE: As the normalize pass guarantees globals aren't being // shadowed and an expression can't introduce new names, there is // no need to check for conflicts. // Create an argName -> expression map, checking for side effects. Map<String, Node> argMap = FunctionArgumentInjector.getFunctionCallParameterMap( fnNode, callNode, this.safeNameIdSupplier); Node newExpression; if (!block.hasChildren()) { Node srcLocation = block; newExpression = NodeUtil.newUndefinedNode(srcLocation); } else { Node returnNode = block.getFirstChild(); Preconditions.checkArgument(returnNode.getType() == Token.RETURN); // Clone the return node first. Node safeReturnNode = returnNode.cloneTree(); Node inlineResult = FunctionArgumentInjector.inject( null, safeReturnNode, null, argMap); Preconditions.checkArgument(safeReturnNode == inlineResult); newExpression = safeReturnNode.removeFirstChild(); } callParentNode.replaceChild(callNode, newExpression); return newExpression; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void process(Node externs, Node root) { Map<String, TweakInfo> tweakInfos = collectTweaks(root); applyCompilerDefaultValueOverrides(tweakInfos); boolean changed = false; if (stripTweaks) { changed = stripAllCalls(tweakInfos); } else if (!compilerDefaultValueOverrides.isEmpty()) { // Pass the compiler default value overrides to the JS through a specially // named variable. Node varNode = createCompilerDefaultValueOverridesVarNode( root.getFirstChild()); root.getFirstChild().addChildToFront(varNode); changed = true; } if (changed) { compiler.reportCodeChange(); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void process(Node externs, Node root) { CollectTweaksResult result = collectTweaks(root); applyCompilerDefaultValueOverrides(result.tweakInfos); boolean changed = false; if (stripTweaks) { changed = stripAllCalls(result.tweakInfos); } else if (!compilerDefaultValueOverrides.isEmpty()) { changed = replaceGetCompilerOverridesCalls(result.getOverridesCalls); } if (changed) { compiler.reportCodeChange(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node fuseIntoOneStatement(Node parent, Node first, Node last) { // Nothing to fuse if there is only one statement. if (first == last) { return first; } // Step one: Create a comma tree that contains all the statements. Node commaTree = first.removeFirstChild(); Node onePastLast = last.getNext(); Node next = null; for (Node cur = first.getNext(); cur != onePastLast; cur = next) { commaTree = fuseExpressionIntoExpression( commaTree, cur.removeFirstChild()); next = cur.getNext(); parent.removeChild(cur); } // Step two: The last EXPR_RESULT will now hold the comma tree with all // the fused statements. first.addChildToBack(commaTree); return first; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code private Node fuseIntoOneStatement(Node parent, Node first, Node last) { // Nothing to fuse if there is only one statement. if (first.getNext() == last) { return first; } // Step one: Create a comma tree that contains all the statements. Node commaTree = first.removeFirstChild(); Node next = null; for (Node cur = first.getNext(); cur != last; cur = next) { commaTree = fuseExpressionIntoExpression( commaTree, cur.removeFirstChild()); next = cur.getNext(); parent.removeChild(cur); } // Step two: The last EXPR_RESULT will now hold the comma tree with all // the fused statements. first.addChildToBack(commaTree); return first; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code FunctionTypeBuilder inferReturnType(@Nullable JSDocInfo info) { if (info != null && info.hasReturnType()) { returnType = info.getReturnType().evaluate(scope, typeRegistry); returnTypeInferred = false; } return this; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code FunctionTypeBuilder(String fnName, AbstractCompiler compiler, Node errorRoot, String sourceName, Scope scope) { Preconditions.checkNotNull(errorRoot); this.fnName = fnName == null ? "" : fnName; this.codingConvention = compiler.getCodingConvention(); this.typeRegistry = compiler.getTypeRegistry(); this.errorRoot = errorRoot; this.sourceName = sourceName; this.compiler = compiler; this.scope = scope; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void analyzeFunctionBwd( List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset) { for (DiGraphNode<Node, ControlFlowGraph.Branch> dn : workset) { Node n = dn.getValue(); TypeEnv outEnv = getOutEnv(n); TypeEnv inEnv; System.out.println("\tBWD Statment: " + n); System.out.println("\t\toutEnv: " + outEnv); switch (n.getType()) { case Token.EXPR_RESULT: inEnv = analyzeExprBwd(n.getFirstChild(), outEnv, JSType.TOP).env; break; case Token.RETURN: { Node retExp = n.getFirstChild(); if (retExp == null) { inEnv = outEnv; } else { JSType declRetType = currentScope.getDeclaredType().getReturnType(); declRetType = declRetType == null ? JSType.UNKNOWN : declRetType; inEnv = analyzeExprBwd(retExp, outEnv, declRetType).env; } break; } case Token.VAR: { inEnv = null; for (Node nameNode = n.getFirstChild(); nameNode != null; nameNode = nameNode.getNext()) { String varName = nameNode.getQualifiedName(); Node rhs = nameNode.getFirstChild(); JSType declType = currentScope.getDeclaredTypeOf(varName); inEnv = envPutType(outEnv, varName, JSType.UNKNOWN); if (rhs == null || currentScope.isLocalFunDef(varName)) { continue; } JSType requiredType = (declType == null) ? JSType.UNKNOWN : declType; inEnv = analyzeExprBwd(rhs, inEnv, JSType.meet(requiredType, envGetType(outEnv, varName))).env; } break; } default: inEnv = outEnv; break; } System.out.println("\t\tinEnv: " + inEnv); setInEnv(n, inEnv); } } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code private void analyzeFunctionBwd( List<DiGraphNode<Node, ControlFlowGraph.Branch>> workset) { for (DiGraphNode<Node, ControlFlowGraph.Branch> dn : workset) { Node n = dn.getValue(); if (n.isThrow()) { // Throw statements have no out edges. // TODO(blickly): Support analyzing the body of the THROW continue; } TypeEnv outEnv = getOutEnv(n); TypeEnv inEnv; System.out.println("\tBWD Statment: " + n); System.out.println("\t\toutEnv: " + outEnv); switch (n.getType()) { case Token.EXPR_RESULT: inEnv = analyzeExprBwd(n.getFirstChild(), outEnv, JSType.TOP).env; break; case Token.RETURN: { Node retExp = n.getFirstChild(); if (retExp == null) { inEnv = outEnv; } else { JSType declRetType = currentScope.getDeclaredType().getReturnType(); declRetType = declRetType == null ? JSType.UNKNOWN : declRetType; inEnv = analyzeExprBwd(retExp, outEnv, declRetType).env; } break; } case Token.VAR: { inEnv = null; for (Node nameNode = n.getFirstChild(); nameNode != null; nameNode = nameNode.getNext()) { String varName = nameNode.getQualifiedName(); Node rhs = nameNode.getFirstChild(); JSType declType = currentScope.getDeclaredTypeOf(varName); inEnv = envPutType(outEnv, varName, JSType.UNKNOWN); if (rhs == null || currentScope.isLocalFunDef(varName)) { continue; } JSType requiredType = (declType == null) ? JSType.UNKNOWN : declType; inEnv = analyzeExprBwd(rhs, inEnv, JSType.meet(requiredType, envGetType(outEnv, varName))).env; } break; } case Token.BLOCK: case Token.EMPTY: inEnv = outEnv; break; case Token.FOR: // TODO(blickly): Analyze these statements case Token.WHILE: case Token.DO: case Token.IF: inEnv = outEnv; break; default: if (NodeUtil.isStatement(n)) { throw new RuntimeException("Unhandled statement type: " + Token.name(n.getType())); } else { inEnv = analyzeExprBwd(n, outEnv).env; break; } } System.out.println("\t\tinEnv: " + inEnv); setInEnv(n, inEnv); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code int processResults(Result result, List<JSModule> modules, B options) throws FlagUsageException, IOException { if (config.computePhaseOrdering) { return 0; } if (config.printPassGraph) { if (compiler.getRoot() == null) { return 1; } else { jsOutput.append( DotFormatter.toDot(compiler.getPassConfig().getPassGraph())); jsOutput.append('\n'); return 0; } } if (config.printAst) { if (compiler.getRoot() == null) { return 1; } else { ControlFlowGraph<Node> cfg = compiler.computeCFG(); DotFormatter.appendDot( compiler.getRoot().getLastChild(), cfg, jsOutput); jsOutput.append('\n'); return 0; } } if (config.printTree) { if (compiler.getRoot() == null) { jsOutput.append("Code contains errors; no tree was generated.\n"); return 1; } else { compiler.getRoot().appendStringTree(jsOutput); jsOutput.append("\n"); return 0; } } rootRelativePathsMap = constructRootRelativePathsMap(); if (config.skipNormalOutputs) { // Output the manifest and bundle files if requested. outputManifest(); outputBundle(); return 0; } else if (result.success) { if (modules == null) { writeOutput( jsOutput, compiler, compiler.toSource(), config.outputWrapper, OUTPUT_WRAPPER_MARKER); // Output the source map if requested. outputSourceMap(options, config.jsOutputFile); } else { parsedModuleWrappers = parseModuleWrappers( config.moduleWrapper, modules); maybeCreateDirsForPath(config.moduleOutputPathPrefix); // If the source map path is in fact a pattern for each // module, create a stream per-module. Otherwise, create // a single source map. Writer mapOut = null; if (!shouldGenerateMapPerModule(options)) { mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, null)); } for (JSModule m : modules) { if (shouldGenerateMapPerModule(options)) { mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, m)); } Writer writer = fileNameToLegacyOutputWriter(getModuleOutputFileName(m)); if (options.sourceMapOutputPath != null) { compiler.getSourceMap().reset(); } writeModuleOutput(writer, m); if (options.sourceMapOutputPath != null) { compiler.getSourceMap().appendTo(mapOut, m.getName()); } writer.close(); if (shouldGenerateMapPerModule(options) && mapOut != null) { mapOut.close(); mapOut = null; } } if (mapOut != null) { mapOut.close(); } } // Output the externs if required. if (options.externExportsPath != null) { Writer eeOut = openExternExportsStream(options, config.jsOutputFile); eeOut.append(result.externExport); eeOut.close(); } // Output the variable and property name maps if requested. outputNameMaps(options); // Output the manifest and bundle files if requested. outputManifest(); outputBundle(); if (options.tracer.isOn()) { outputTracerReport(); } } // return 0 if no errors, the error count otherwise return Math.min(result.errors.length, 0x7f); } #location 105 #vulnerability type NULL_DEREFERENCE
#fixed code AbstractCommandLineRunner() { this(System.out, System.err); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void ensureTyped(NodeTraversal t, Node n, JSType type) { // Make sure FUNCTION nodes always get function type. Preconditions.checkState(!n.isFunction() || type.isFunctionType() || type.isUnknownType()); JSDocInfo info = n.getJSDocInfo(); if (info != null) { if (info.hasType()) { // TODO(johnlenz): Change this so that we only look for casts on CAST // nodes one the misplaced type annotation warning is on by default and // people have been given a chance to fix them. As is, this is here // simply for legacy casts. JSType infoType = info.getType().evaluate(t.getScope(), typeRegistry); validator.expectCanCast(t, n, infoType, type); type = infoType; } if (info.isImplicitCast() && !inExterns) { String propName = n.isGetProp() ? n.getLastChild().getString() : "(missing)"; compiler.report( t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName)); } } if (n.getJSType() == null) { n.setJSType(type); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private void ensureTyped(NodeTraversal t, Node n, JSType type) { // Make sure FUNCTION nodes always get function type. Preconditions.checkState(!n.isFunction() || type.isFunctionType() || type.isUnknownType()); // TODO(johnlenz): this seems like a strange place to check "@implicitCast" JSDocInfo info = n.getJSDocInfo(); if (info != null) { if (info.isImplicitCast() && !inExterns) { String propName = n.isGetProp() ? n.getLastChild().getString() : "(missing)"; compiler.report( t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName)); } } if (n.getJSType() == null) { n.setJSType(type); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void outputManifest() throws IOException { String outputManifest = config.outputManifest; if (Strings.isEmpty(outputManifest)) { return; } JSModuleGraph graph = compiler.getModuleGraph(); if (shouldGenerateManifestPerModule()) { // Generate per-module manifests. Iterable<JSModule> modules = graph.getAllModules(); for (JSModule module : modules) { Writer out = fileNameToOutputWriter(expandManifest(module)); printManifestTo(module.getInputs(), out); out.close(); } } else { // Generate a single file manifest. Writer out = fileNameToOutputWriter(expandManifest(null)); if (graph == null) { printManifestTo(compiler.getInputsInOrder(), out); } else { printModuleGraphManifestTo(graph, out); } out.close(); } } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code private void outputManifest() throws IOException { List<String> outputManifests = config.outputManifests; if (outputManifests.isEmpty()) { return; } for (String outputManifest : outputManifests) { if (outputManifest.isEmpty()) { continue; } JSModuleGraph graph = compiler.getModuleGraph(); if (shouldGenerateManifestPerModule(outputManifest)) { // Generate per-module manifests. Iterable<JSModule> modules = graph.getAllModules(); for (JSModule module : modules) { Writer out = fileNameToOutputWriter( expandManifest(module, outputManifest)); printManifestTo(module.getInputs(), out); out.close(); } } else { // Generate a single file manifest. Writer out = fileNameToOutputWriter( expandManifest(null, outputManifest)); if (graph == null) { printManifestTo(compiler.getInputsInOrder(), out); } else { printModuleGraphManifestTo(graph, out); } out.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.