output
stringlengths 79
30.1k
| instruction
stringclasses 1
value | input
stringlengths 216
28.9k
|
---|---|---|
#fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
String[] names;
String[] aliases;
if (!(localStack.peek() instanceof ForeachContext)) {
// create a clone of the context
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
names = foreachContext.getNames();
aliases = foreachContext.getAliases();
try {
Iterator[] iters = new Iterator[names.length];
for (int i = 0; i < names.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(names[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator(); // this throws null pointer exception in thread race
}
// set the newly created iterators into the context
foreachContext.setIterators(iters);
// push the context onto the local stack.
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)), e);
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)), e);
}
}
else {
foreachContext = (ForeachContext) localStack.peek();
// names = foreachContext.getNames();
aliases = foreachContext.getAliases();
}
Iterator[] iters = foreachContext.getItererators();
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(aliases[i], iters[i].next());
}
int c;
tokens.put("i0", c = foreachContext.getCount());
if (c != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
foreachContext.incrementCount();
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(aliases[i]);
}
// foreachContext.setIterators(null);
// foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (CACHE_DISABLE || !cacheAggressively) {
char[] seg = new char[expression.length - 3];
// arraycopy(expression, 2, seg, 0, seg.length);
for (int i = 0; i < seg.length; i++)
seg[i] = expression[i + 2];
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
if (tokens == null) {
tokens = new HashMap();
}
ForeachContext foreachContext;
if (!(localStack.peek() instanceof ForeachContext)) {
foreachContext = ((ForeachContext) currNode.getRegister()).clone();
// if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
localStack.push(foreachContext);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
foreachContext = (ForeachContext) localStack.peek();
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
localStack.pop();
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 122
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected ASTNode verify(ParserContext pCtx, ASTNode tk) {
if (tk.isDiscard() || (tk.fields & (ASTNode.OPERATOR | ASTNode.LITERAL)) != 0) return tk;
if (verifying) {
if (tk.isAssignment()) {
char[] assign = tk.getNameAsArray();
int c = 0;
while (c < assign.length && assign[c] != '=') c++;
String varName = new String(assign, 0, c++).trim();
if (isReservedWord(varName)) {
addFatalError("invalid assignment - variable name is a reserved keyword: " + varName);
}
ExpressionCompiler subCompiler =
new ExpressionCompiler(new String(assign, c, assign.length - c).trim());
subCompiler._compile();
pCtx.addVariable(varName, returnType = tk.getEgressType());
}
else if (tk.isIdentifier()) {
PropertyVerifier propVerifier = new PropertyVerifier(tk.getNameAsArray(), getParserContext());
pCtx.addInput(tk.getAbsoluteName(), returnType = propVerifier.analyze());
}
}
return tk;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected ASTNode verify(ParserContext pCtx, ASTNode tk) {
if (tk.isDiscard() || (tk.fields & (ASTNode.OPERATOR | ASTNode.LITERAL)) != 0) return tk;
if (verifying) {
if (tk.isAssignment()) {
char[] assign = tk.getNameAsArray();
int c = 0;
while (c < assign.length && assign[c] != '=') c++;
String varName = new String(assign, 0, c++).trim();
if (isReservedWord(varName)) {
addFatalError("invalid assignment - variable name is a reserved keyword: " + varName);
}
locals.add(varName);
ExpressionCompiler subCompiler =
new ExpressionCompiler(new String(assign, c, assign.length - c).trim());
subCompiler._compile();
inputs.addAll(subCompiler.getInputs());
pCtx.addVariable(varName, tk.getEgressType());
}
else if (tk.isIdentifier()) {
inputs.add(tk.getAbsoluteName());
PropertyVerifier propVerifier = new PropertyVerifier(tk.getNameAsArray(), getParserContext());
returnType = propVerifier.analyze();
inputs.addAll(propVerifier.getInputs());
}
}
return tk;
}
#location 31
#vulnerability type NULL_DEREFERENCE |
#fixed code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
synchronized (Runtime.getRuntime()) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Object execute(Object ctx, Map tokens, TemplateRegistry registry) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
/**
* This is an optimization for property expressions.
*/
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
if (!cacheAggressively) {
char[] seg = new char[expression.length - 3];
arraycopy(expression, 2, seg, 0, seg.length);
return MVEL.eval(seg, ctx, tokens);
}
else {
String s = new String(expression, 2, expression.length - 3);
if (!EX_PRECOMP_CACHE.containsKey(s)) {
synchronized (EX_PRECOMP_CACHE) {
EX_PRECOMP_CACHE.put(s, compileExpression(s));
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
//noinspection unchecked
MVELInterpretedRuntime oParser = new MVELInterpretedRuntime(ctx, tokens);
initStack();
pushAndForward();
while ((currNode = pop()) != null) {
node = currNode.getNode();
switch (currNode.getToken()) {
case LITERAL: {
sbuf.append(register = new String(expression, currNode.getStartPos(),
currNode.getEndPos() - currNode.getStartPos()));
break;
}
case PROPERTY_EX: {
sbuf.append(
valueOf(register = oParser.setExpressionArray(getInternalSegment(currNode)).parse())
);
break;
}
case IF:
case ELSEIF: {
try {
if (!((Boolean) oParser.setExpressionArray(getInternalSegment(currNode)).parse())) {
exitContext();
}
}
catch (ClassCastException e) {
throw new CompileException("IF expression does not return a boolean: " + new String(getSegment(currNode)));
}
break;
}
case FOREACH: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (foreachContext.getItererators() == null) {
try {
String[] lists = getForEachSegment(currNode).split(",");
Iterator[] iters = new Iterator[lists.length];
for (int i = 0; i < lists.length; i++) {
//noinspection unchecked
Object listObject = new MVELInterpretedRuntime(lists[i], ctx, tokens).parse();
if (listObject instanceof Object[]) {
listObject = Arrays.asList((Object[]) listObject);
}
iters[i] = ((Collection) listObject).iterator();
}
foreachContext.setIterators(iters);
}
catch (ClassCastException e) {
throw new CompileException("expression for collections does not return a collections object: " + new String(getSegment(currNode)));
}
catch (NullPointerException e) {
throw new CompileException("null returned for foreach in expression: " + (getForEachSegment(currNode)));
}
}
Iterator[] iters = foreachContext.getItererators();
String[] alias = currNode.getAlias().split(",");
// must trim vars
for (int i = 0; i < alias.length; i++) {
alias[i] = alias[i].trim();
}
if (iters[0].hasNext()) {
push();
//noinspection unchecked
for (int i = 0; i < iters.length; i++) {
//noinspection unchecked
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
//noinspection unchecked
tokens.put("i0", foreachContext.getCount());
foreachContext.setCount(foreachContext.getCount() + 1);
}
else {
for (int i = 0; i < iters.length; i++) {
tokens.remove(alias[i]);
}
foreachContext.setIterators(null);
foreachContext.setCount(0);
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length != 2) {
return sbuf.toString();
}
else {
return register;
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
IncludeRefParam[] params = includeRef.getParams();
Map<String, Object> vars = new HashMap<String, Object>(params.length * 2);
for (IncludeRefParam param : params) {
vars.put(param.getIdentifier(), MVEL.eval(param.getValue(), ctx, tokens));
}
if (registry == null) {
throw new CompileException("No TemplateRegistry specified, cannot load template='" + includeRef.getName() + "'");
}
String template = registry.getTemplate(includeRef.getName());
if (template == null) {
throw new CompileException("Template does not exist in the TemplateRegistry, cannot load template='" + includeRef.getName() + "'");
}
sbuf.append(TemplateInterpreter.parse(template, ctx, vars, registry));
}
}
forwardAndPush();
}
throw new CompileException("expression did not end properly: expected TERMINUS node");
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
if (currNode != null) {
throw new CompileException("problem encountered at node [" + currNode.getNode() + "] "
+ currNode.getToken() + "{" + currNode.getStartPos() + "," + currNode.getEndPos() + "}: " + e.getMessage(), e);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 62
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected ASTNode nextToken() {
/**
* If the cursor is at the end of the expression, we have nothing more to do:
* return null.
*/
if (cursor >= length) {
return null;
}
else if (!splitAccumulator.isEmpty()) {
return lastNode = (ASTNode) splitAccumulator.pop();
}
int brace, start = cursor;
/**
* Because of parser recursion for sub-expression parsing, we sometimes need to remain
* certain field states. We do not reset for assignments, boolean mode, list creation or
* a capture only mode.
*/
fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE);
boolean capture = false;
boolean union = false;
if (debugSymbols) {
if (!lastWasLineLabel) {
if (getParserContext().getSourceFile() == null) {
throw new CompileException("unable to produce debugging symbols: source name must be provided.");
}
ParserContext pCtx = getParserContext();
line = pCtx.getLineCount();
int scan = cursor;
while (expr[scan] == '\n') {
scan++;
line++;
}
if (lastWasComment) {
line++;
lastWasComment = false;
}
pCtx.setLineCount(line);
if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) {
lastWasLineLabel = true;
pCtx.setLineAndOffset(line, cursor);
pCtx.addKnownLine(pCtx.getSourceFile(), line);
LineLabel ll = new LineLabel(pCtx.getSourceFile(), line);
if (pCtx.getFirstLineLabel() == null) pCtx.setFirstLineLabel(ll);
return lastNode = ll;
}
}
else {
lastWasComment = lastWasLineLabel = false;
}
}
/**
* Skip any whitespace currently under the starting point.
*/
while (start < length && isWhitespace(expr[start])) start++;
/**
* From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for
* trouble unless you really know what you're doing.
*/
for (cursor = start; cursor < length;) {
if (isIdentifierPart(expr[cursor])) {
/**
* If the current character under the cursor is a valid
* part of an identifier, we keep capturing.
*/
capture = true;
cursor++;
}
else if (capture) {
String t;
if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) {
switch (OPERATORS.get(t)) {
case NEW:
start = cursor + 1;
captureToEOT();
return new NewObjectNode(subArray(start, cursor), fields);
case ASSERT:
start = cursor + 1;
captureToEOS();
return new AssertNode(subArray(start, cursor--), fields);
case RETURN:
start = cursor + 1;
captureToEOS();
return new ReturnNode(subArray(start, cursor), fields);
case IF:
fields |= ASTNode.BLOCK_IF;
return captureCodeBlock();
case FOREACH:
fields |= ASTNode.BLOCK_FOREACH;
return captureCodeBlock();
case WITH:
fields |= ASTNode.BLOCK_WITH;
return captureCodeBlock();
case IMPORT:
start = cursor + 1;
captureToEOS();
ImportNode importNode = new ImportNode(subArray(start, cursor--), fields);
getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass());
return importNode;
case IMPORT_STATIC:
start = cursor + 1;
captureToEOS();
return new StaticImportNode(subArray(start, cursor--), fields);
}
}
/**
* If we *were* capturing a token, and we just hit a non-identifier
* character, we stop and figure out what to do.
*/
skipWhitespace();
if (expr[cursor] == '(') {
fields |= ASTNode.METHOD;
/**
* If the current token is a method call or a constructor, we
* simply capture the entire parenthesized range and allow
* reduction to be dealt with through sub-parsing the property.
*/
cursor++;
for (brace = 1; cursor < length && brace > 0;) {
switch (expr[cursor++]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length) + 1;
break;
case'"':
cursor = captureStringLiteral('"', expr, cursor, length) + 1;
break;
}
}
/**
* If the brace counter is greater than 0, we know we have
* unbalanced braces in the expression. So we throw a
* optimize error now.
*/
if (brace > 0)
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
/**
* If we encounter any of the following cases, we are still dealing with
* a contiguous token.
*/
String name;
if (cursor < length) {
switch (expr[cursor]) {
case'+':
switch (lookAhead(1)) {
case'+':
ASTNode n = new PostFixIncNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t);
}
else {
return new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name);
}
}
break;
case'-':
switch (lookAhead(1)) {
case'-':
ASTNode n = new PostFixDecNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignSub(subArray(start, cursor), fields, name);
}
break;
case'*':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignMult(subArray(start, cursor), fields, name);
}
break;
case'/':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignDiv(subArray(start, cursor), fields, name);
}
break;
case']':
case'[':
balancedCapture('[');
cursor++;
continue;
case'.':
union = true;
cursor++;
continue;
case'~':
if (isAt('=', 1)) {
char[] stmt = subArray(start, trimLeft(cursor));
start = cursor += 2;
captureToEOT();
return new RegExMatch(stmt, fields, subArray(start, cursor));
}
break;
case'=':
if (isAt('+', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignAdd(subArray(start, cursor), fields, name);
}
if (greedy && !isAt('=', 1)) {
cursor++;
fields |= ASTNode.ASSIGN;
skipWhitespace();
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields);
}
else if (lastWasIdentifier) {
/**
* Check for typing information.
*/
if (lastNode.getLiteralValue() instanceof String) {
if (getParserContext().hasImport((String) lastNode.getLiteralValue())) {
lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
else {
try {
/**
* take a stab in the dark and try and load the class
*/
lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) {
lastNode.setDiscard(true);
captureToEOS();
return new TypedVarNode(subArray(start, cursor), fields, (Class)
lastNode.getLiteralValue());
}
throw new ParseException("unknown class: " + lastNode.getLiteralValue());
}
else {
return new AssignmentNode(subArray(start, cursor), fields);
}
}
}
}
/**
* Produce the token.
*/
trimWhitespace();
if (parserContext != null) {
char[] _subset = subset(expr, start, cursor - start);
int offset;
Class cls;
if ((offset = ArrayTools.findFirst('.', _subset)) != -1) {
String iStr;
if (getParserContext().hasImport(iStr = new String(_subset, 0, offset))) {
lastWasIdentifier = true;
return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, getParserContext().getImport(iStr));
// / return lastNode = new Union(_subset, offset + 1, _subset.length, fields, new LiteralNode(getParserContext().getImport(iStr)));
}
// else if ((cls = createClassSafe(iStr = new String(_subset, offset = ArrayTools.findLast('.', _subset), _subset.length - offset))) != null) {
//
// }
}
else {
ASTNode node = new ASTNode(_subset, 0, _subset.length, fields);
lastWasIdentifier = node.isIdentifier();
return lastNode = node;
}
}
return createToken(expr, start, cursor, fields);
}
else
switch (expr[cursor]) {
case'@': {
start++;
captureToEOT();
String interceptorName = new String(expr, start, cursor - start);
if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors().
containsKey(interceptorName)) {
throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor);
}
return new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken());
}
case'=':
return createToken(expr, start, (cursor += 2), fields);
case'-':
if (isAt('-', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixDecNode(subArray(start, cursor), fields);
}
else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) {
return createToken(expr, start, cursor++ + 1, fields);
}
else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) {
cursor++;
break;
}
case'+':
if (isAt('+', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixIncNode(subArray(start, cursor), fields);
}
return createToken(expr, start, cursor++ + 1, fields);
case'*':
if (isAt('*', 1)) {
cursor++;
}
return createToken(expr, start, cursor++ + 1, fields);
case';':
cursor++;
lastWasIdentifier = false;
return lastNode = new EndOfStatement();
case'#':
case'/':
if (isAt(expr[cursor], 1)) {
/**
* Handle single line comments.
*/
while (cursor < length && expr[cursor] != '\n') cursor++;
if (debugSymbols) {
line = getParserContext().getLineCount();
skipWhitespaceWithLineAccounting();
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
getParserContext().setLineCount(line);
}
else if (cursor < length) {
skipWhitespace();
}
if ((start = cursor) >= length) return null;
continue;
}
else if (expr[cursor] == '/' && isAt('*', 1)) {
/**
* Handle multi-line comments.
*/
int len = length - 1;
/**
* This probably seems highly redundant, but sub-compilations within the same
* source will spawn a new compiler, and we need to sync this with the
* parser context;
*/
if (debugSymbols) {
line = getParserContext().getLineCount();
}
while (true) {
cursor++;
/**
* Since multi-line comments may cross lines, we must keep track of any line-break
* we encounter.
*/
if (debugSymbols && expr[cursor] == '\n') {
line++;
}
if (cursor == len) {
throw new CompileException("unterminated block comment", expr, cursor);
}
if (expr[cursor] == '*' && isAt('/', 1)) {
if ((cursor += 2) >= length) return null;
skipWhitespace();
start = cursor;
break;
}
}
if (debugSymbols) {
getParserContext().setLineCount(line);
}
continue;
}
case'?':
case':':
case'^':
case'%': {
return createToken(expr, start, cursor++ + 1, fields);
}
case'(': {
cursor++;
boolean singleToken = true;
boolean lastWS = false;
skipWhitespace();
for (brace = 1; cursor < length && brace > 0; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'i':
if (isAt('n', 1) && isWhitespace(lookAhead(2))) {
fields |= ASTNode.FOLD;
}
break;
default:
/**
* Check to see if we should disqualify this current token as a potential
* type-cast candidate.
*/
if (lastWS || !isIdentifierPart(expr[cursor])) {
singleToken = false;
}
else if (isWhitespace(expr[cursor])) {
lastWS = true;
skipWhitespace();
cursor--;
}
}
}
if (brace > 0) {
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
char[] _subset = null;
if (singleToken) {
String tokenStr = new String(_subset = subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)));
if (getParserContext().hasImport(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr));
}
else if (LITERALS.containsKey(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, (Class) LITERALS.get(tokenStr));
}
else {
try {
/**
*
* take a stab in the dark and try and load the class
*/
int _start = cursor;
captureToEOS();
return new TypeCast(expr, _start, cursor, fields, createClass(tokenStr));
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if ((fields & ASTNode.FOLD) != 0) {
if (cursor < length && expr[cursor] == '.') {
cursor += 1;
continue;
}
return createToken(expr, trimRight(start), cursor, ASTNode.FOLD);
}
if (_subset != null) {
return handleUnion(new Substatement(_subset, fields));
}
else {
return handleUnion(new Substatement(subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)), fields));
}
}
case'}':
case']':
case')': {
throw new ParseException("unbalanced braces", expr, cursor);
}
case'>': {
if (expr[cursor + 1] == '>') {
if (expr[cursor += 2] == '>') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor + 1] == '=') {
return createToken(expr, start, cursor += 2, fields);
}
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'<': {
if (expr[++cursor] == '<') {
if (expr[++cursor] == '<') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor] == '=') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'"':
cursor = captureStringLiteral('"', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'&': {
if (expr[cursor++ + 1] == '&') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'|': {
if (expr[cursor++ + 1] == '|') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'~':
if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1)))
&& isDigit(expr[cursor + 1])) {
fields |= ASTNode.INVERT;
start++;
cursor++;
break;
}
else if (expr[cursor + 1] == '(') {
fields |= ASTNode.INVERT;
start = ++cursor;
continue;
}
else {
if (expr[cursor + 1] == '=') cursor++;
return createToken(expr, start, ++cursor, fields);
}
case'!': {
if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') {
start = cursor;
fields |= ASTNode.NEGATION;
continue;
}
else if (expr[cursor] != '=')
throw new CompileException("unexpected operator '!'", expr, cursor, null);
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'[':
case'{':
if (balancedCapture(expr[cursor]) == -1) {
if (cursor >= length) cursor--;
throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor);
}
if (cursor < (length - 1) && expr[cursor + 1] == '.') {
fields |= ASTNode.INLINE_COLLECTION;
cursor++;
continue;
}
return new InlineCollectionNode(expr, start, ++cursor, fields);
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected ASTNode nextToken() {
/**
* If the cursor is at the end of the expression, we have nothing more to do:
* return null.
*/
if (cursor >= length) {
return null;
}
else if (!splitAccumulator.isEmpty()) {
return lastNode = (ASTNode) splitAccumulator.pop();
}
int brace, start = cursor;
/**
* Because of parser recursion for sub-expression parsing, we sometimes need to remain
* certain field states. We do not reset for assignments, boolean mode, list creation or
* a capture only mode.
*/
fields = fields & (ASTNode.INLINE_COLLECTION | ASTNode.COMPILE_IMMEDIATE);
boolean capture = false;
boolean union = false;
if (debugSymbols) {
if (!lastWasLineLabel) {
if (getParserContext().getSourceFile() == null) {
throw new CompileException("unable to produce debugging symbols: source name must be provided.");
}
ParserContext pCtx = getParserContext();
line = pCtx.getLineCount();
int scan = cursor;
while (expr[scan] == '\n') {
scan++;
line++;
}
if (lastWasComment) {
line++;
lastWasComment = false;
}
pCtx.setLineCount(line);
if (!pCtx.isKnownLine(pCtx.getSourceFile(), line)) {
lastWasLineLabel = true;
pCtx.setLineAndOffset(line, cursor);
pCtx.addKnownLine(pCtx.getSourceFile(), line);
LineLabel ll = new LineLabel(pCtx.getSourceFile(), line);
if (pCtx.getFirstLineLabel() == null) pCtx.setFirstLineLabel(ll);
return lastNode = ll;
}
}
else {
lastWasComment = lastWasLineLabel = false;
}
}
/**
* Skip any whitespace currently under the starting point.
*/
while (start < length && isWhitespace(expr[start])) start++;
/**
* From here to the end of the method is the core MVEL parsing code. Fiddling around here is asking for
* trouble unless you really know what you're doing.
*/
for (cursor = start; cursor < length;) {
if (isIdentifierPart(expr[cursor])) {
/**
* If the current character under the cursor is a valid
* part of an identifier, we keep capturing.
*/
capture = true;
cursor++;
}
else if (capture) {
String t;
if (OPERATORS.containsKey(t = new String(expr, start, cursor - start))) {
switch (OPERATORS.get(t)) {
case NEW:
start = cursor + 1;
captureToEOT();
return new NewObjectNode(subArray(start, cursor), fields);
case ASSERT:
start = cursor + 1;
captureToEOS();
return new AssertNode(subArray(start, cursor--), fields);
case RETURN:
start = cursor + 1;
captureToEOS();
return new ReturnNode(subArray(start, cursor), fields);
case IF:
fields |= ASTNode.BLOCK_IF;
return captureCodeBlock();
case FOREACH:
fields |= ASTNode.BLOCK_FOREACH;
return captureCodeBlock();
case WITH:
fields |= ASTNode.BLOCK_WITH;
return captureCodeBlock();
case IMPORT:
start = cursor + 1;
captureToEOS();
ImportNode importNode = new ImportNode(subArray(start, cursor--), fields);
getParserContext().addImport(getSimpleClassName(importNode.getImportClass()), importNode.getImportClass());
return importNode;
case IMPORT_STATIC:
start = cursor + 1;
captureToEOS();
return new StaticImportNode(subArray(start, cursor--), fields);
}
}
/**
* If we *were* capturing a token, and we just hit a non-identifier
* character, we stop and figure out what to do.
*/
skipWhitespace();
if (expr[cursor] == '(') {
fields |= ASTNode.METHOD;
/**
* If the current token is a method call or a constructor, we
* simply capture the entire parenthesized range and allow
* reduction to be dealt with through sub-parsing the property.
*/
cursor++;
for (brace = 1; cursor < length && brace > 0;) {
switch (expr[cursor++]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length) + 1;
break;
case'"':
cursor = captureStringLiteral('"', expr, cursor, length) + 1;
break;
}
}
/**
* If the brace counter is greater than 0, we know we have
* unbalanced braces in the expression. So we throw a
* optimize error now.
*/
if (brace > 0)
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
/**
* If we encounter any of the following cases, we are still dealing with
* a contiguous token.
*/
String name;
if (cursor < length) {
switch (expr[cursor]) {
case'+':
switch (lookAhead(1)) {
case'+':
ASTNode n = new PostFixIncNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields, Operator.ADD, t);
}
else {
return new AssignmentNode(subArray(start, cursor), fields, Operator.ADD, name);
}
}
break;
case'-':
switch (lookAhead(1)) {
case'-':
ASTNode n = new PostFixDecNode(subArray(start, cursor), fields);
cursor += 2;
return n;
case'=':
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignSub(subArray(start, cursor), fields, name);
}
break;
case'*':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignMult(subArray(start, cursor), fields, name);
}
break;
case'/':
if (isAt('=', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignDiv(subArray(start, cursor), fields, name);
}
break;
case']':
case'[':
balancedCapture('[');
cursor++;
continue;
case'.':
union = true;
cursor++;
continue;
case'~':
if (isAt('=', 1)) {
char[] stmt = subArray(start, trimLeft(cursor));
start = cursor += 2;
captureToEOT();
return new RegExMatch(stmt, fields, subArray(start, cursor));
}
break;
case'=':
if (isAt('+', 1)) {
name = new String(expr, start, trimLeft(cursor));
start = cursor += 2;
captureToEOS();
return new AssignAdd(subArray(start, cursor), fields, name);
}
if (greedy && !isAt('=', 1)) {
cursor++;
fields |= ASTNode.ASSIGN;
skipWhitespace();
captureToEOS();
if (union) {
return new DeepAssignmentNode(subArray(start, cursor), fields);
}
else if (lastWasIdentifier) {
/**
* Check for typing information.
*/
if (lastNode.getLiteralValue() instanceof String) {
if (getParserContext().hasImport((String) lastNode.getLiteralValue())) {
lastNode.setLiteralValue(getParserContext().getImport((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
else {
try {
/**
* take a stab in the dark and try and load the class
*/
lastNode.setLiteralValue(createClass((String) lastNode.getLiteralValue()));
lastNode.setAsLiteral();
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if (lastNode.isLiteral() && lastNode.getLiteralValue() instanceof Class) {
lastNode.setDiscard(true);
captureToEOS();
return new TypedVarNode(subArray(start, cursor), fields, (Class)
lastNode.getLiteralValue());
}
throw new ParseException("unknown class: " + lastNode.getLiteralValue());
}
else {
return new AssignmentNode(subArray(start, cursor), fields);
}
}
}
}
/**
* Produce the token.
*/
trimWhitespace();
return createToken(expr, start, cursor, fields);
}
else
switch (expr[cursor]) {
case'@': {
start++;
captureToEOT();
String interceptorName = new String(expr, start, cursor - start);
if (getParserContext().getInterceptors() == null || !getParserContext().getInterceptors().
containsKey(interceptorName)) {
throw new CompileException("reference to undefined interceptor: " + interceptorName, expr, cursor);
}
return new InterceptorWrapper(getParserContext().getInterceptors().get(interceptorName), nextToken());
}
case'=':
return createToken(expr, start, (cursor += 2), fields);
case'-':
if (isAt('-', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixDecNode(subArray(start, cursor), fields);
}
else if ((cursor > 0 && !isWhitespace(lookBehind(1))) || !isDigit(lookAhead(1))) {
return createToken(expr, start, cursor++ + 1, fields);
}
else if ((cursor - 1) < 0 || (!isDigit(lookBehind(1))) && isDigit(lookAhead(1))) {
cursor++;
break;
}
case'+':
if (isAt('+', 1)) {
start = cursor += 2;
captureToEOT();
return new PreFixIncNode(subArray(start, cursor), fields);
}
return createToken(expr, start, cursor++ + 1, fields);
case'*':
if (isAt('*', 1)) {
cursor++;
}
return createToken(expr, start, cursor++ + 1, fields);
case';':
cursor++;
lastWasIdentifier = false;
return lastNode = new EndOfStatement();
case'#':
case'/':
if (isAt(expr[cursor], 1)) {
/**
* Handle single line comments.
*/
while (cursor < length && expr[cursor] != '\n') cursor++;
if (debugSymbols) {
line = getParserContext().getLineCount();
skipWhitespaceWithLineAccounting();
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
getParserContext().setLineCount(line);
}
else if (cursor < length) {
skipWhitespace();
}
if ((start = cursor) >= length) return null;
continue;
}
else if (expr[cursor] == '/' && isAt('*', 1)) {
/**
* Handle multi-line comments.
*/
int len = length - 1;
/**
* This probably seems highly redundant, but sub-compilations within the same
* source will spawn a new compiler, and we need to sync this with the
* parser context;
*/
if (debugSymbols) {
line = getParserContext().getLineCount();
}
while (true) {
cursor++;
/**
* Since multi-line comments may cross lines, we must keep track of any line-break
* we encounter.
*/
if (debugSymbols && expr[cursor] == '\n') {
line++;
}
if (cursor == len) {
throw new CompileException("unterminated block comment", expr, cursor);
}
if (expr[cursor] == '*' && isAt('/', 1)) {
if ((cursor += 2) >= length) return null;
skipWhitespace();
start = cursor;
break;
}
}
if (debugSymbols) {
getParserContext().setLineCount(line);
}
continue;
}
case'?':
case':':
case'^':
case'%': {
return createToken(expr, start, cursor++ + 1, fields);
}
case'(': {
cursor++;
boolean singleToken = true;
boolean lastWS = false;
skipWhitespace();
for (brace = 1; cursor < length && brace > 0; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
brace--;
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'i':
if (isAt('n', 1) && isWhitespace(lookAhead(2))) {
fields |= ASTNode.FOLD;
}
break;
default:
/**
* Check to see if we should disqualify this current token as a potential
* type-cast candidate.
*/
if (lastWS || isIdentifierPart(expr[cursor])) {
singleToken = false;
}
else if (isWhitespace(expr[cursor])) {
lastWS = true;
skipWhitespace();
cursor--;
}
}
}
if (brace > 0) {
throw new CompileException("unbalanced braces in expression: (" + brace + "):", expr, cursor);
}
char[] _subset = null;
if (singleToken) {
String tokenStr = new String(_subset = subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)));
if (getParserContext().hasImport(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, getParserContext().getImport(tokenStr));
}
else if (LITERALS.containsKey(tokenStr)) {
start = cursor;
captureToEOS();
return new TypeCast(expr, start, cursor, fields, (Class) LITERALS.get(tokenStr));
}
else {
try {
/**
*
* take a stab in the dark and try and load the class
*/
int _start = cursor;
captureToEOS();
return new TypeCast(expr, _start, cursor, fields, createClass(tokenStr));
}
catch (ClassNotFoundException e) {
/**
* Just fail through.
*/
}
}
}
if ((fields & ASTNode.FOLD) != 0) {
if (cursor < length && expr[cursor] == '.') {
cursor += 1;
continue;
}
return createToken(expr, trimRight(start), cursor, ASTNode.FOLD);
}
if (_subset != null) {
return handleUnion(new Substatement(_subset, fields));
}
else {
return handleUnion(new Substatement(subset(expr, trimRight(start + 1), trimLeft(cursor - 1) - (start + 1)), fields));
}
}
case'}':
case']':
case')': {
throw new ParseException("unbalanced braces", expr, cursor);
}
case'>': {
if (expr[cursor + 1] == '>') {
if (expr[cursor += 2] == '>') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor + 1] == '=') {
return createToken(expr, start, cursor += 2, fields);
}
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'<': {
if (expr[++cursor] == '<') {
if (expr[++cursor] == '<') cursor++;
return createToken(expr, start, cursor, fields);
}
else if (expr[cursor] == '=') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'"':
cursor = captureStringLiteral('"', expr, cursor, length);
return new LiteralNode(handleStringEscapes(subset(expr, start + 1, cursor++ - start - 1)), String.class);
case'&': {
if (expr[cursor++ + 1] == '&') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'|': {
if (expr[cursor++ + 1] == '|') {
return createToken(expr, start, ++cursor, fields);
}
else {
return createToken(expr, start, cursor, fields);
}
}
case'~':
if ((cursor - 1 < 0 || !isIdentifierPart(lookBehind(1)))
&& isDigit(expr[cursor + 1])) {
fields |= ASTNode.INVERT;
start++;
cursor++;
break;
}
else if (expr[cursor + 1] == '(') {
fields |= ASTNode.INVERT;
start = ++cursor;
continue;
}
else {
if (expr[cursor + 1] == '=') cursor++;
return createToken(expr, start, ++cursor, fields);
}
case'!': {
if (isIdentifierPart(expr[++cursor]) || expr[cursor] == '(') {
start = cursor;
fields |= ASTNode.NEGATION;
continue;
}
else if (expr[cursor] != '=')
throw new CompileException("unexpected operator '!'", expr, cursor, null);
else {
return createToken(expr, start, ++cursor, fields);
}
}
case'[':
case'{':
if (balancedCapture(expr[cursor]) == -1) {
if (cursor >= length) cursor--;
throw new CompileException("unbalanced brace: in inline map/list/array creation", expr, cursor);
}
if (cursor < (length - 1) && expr[cursor + 1] == '.') {
fields |= ASTNode.INLINE_COLLECTION;
cursor++;
continue;
}
return new InlineCollectionNode(expr, start, ++cursor, fields);
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
}
#location 508
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
private TypeUsage getTypeConcrete(Node node, boolean solveLambdas) {
if (node == null) throw new IllegalArgumentException();
if (node instanceof NameExpr) {
NameExpr nameExpr = (NameExpr) node;
logger.finest("getType on name expr " + node);
Optional<Value> value = new SymbolSolver(typeSolver).solveSymbolAsValue(nameExpr.getName(), nameExpr);
if (!value.isPresent()){
throw new UnsolvedSymbolException("FOO Solving "+node, nameExpr.getName());
} else {
return value.get().getUsage();
}
} else if (node instanceof MethodCallExpr) {
logger.finest("getType on method call " + node);
// first solve the method
MethodUsage ref = new JavaParserFacade(typeSolver).solveMethodAsUsage((MethodCallExpr) node);
logger.finest("getType on method call " + node + " resolved to " + ref);
logger.finest("getType on method call " + node + " return type is " + ref.returnType());
return ref.returnType();
// the type is the return type of the method
} else if (node instanceof LambdaExpr) {
if (node.getParentNode() instanceof MethodCallExpr) {
MethodCallExpr callExpr = (MethodCallExpr) node.getParentNode();
int pos = JavaParserSymbolDeclaration.getParamPos(node);
SymbolReference<MethodDeclaration> refMethod = new JavaParserFacade(typeSolver).solve(callExpr);
if (!refMethod.isSolved()) {
throw new UnsolvedSymbolException(callExpr.getName());
}
logger.finest("getType on lambda expr " + refMethod.getCorrespondingDeclaration().getName());
//logger.finest("Method param " + refMethod.getCorrespondingDeclaration().getParam(pos));
if (solveLambdas) {
TypeUsage result = refMethod.getCorrespondingDeclaration().getParam(pos).getType(typeSolver);
// We need to replace the type variables
result = result.solveGenericTypes(JavaParserFactory.getContext(node), typeSolver);
return result;
} else {
return refMethod.getCorrespondingDeclaration().getParam(pos).getType(typeSolver);
}
//System.out.println("LAMBDA " + node.getParentNode());
//System.out.println("LAMBDA CLASS " + node.getParentNode().getClass().getCanonicalName());
//TypeUsage typeOfMethod = new JavaParserFacade(typeSolver).getType(node.getParentNode());
//throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value");
} else {
throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value");
}
} else if (node instanceof VariableDeclarator) {
if (node.getParentNode() instanceof FieldDeclaration) {
FieldDeclaration parent = (FieldDeclaration) node.getParentNode();
return new JavaParserFacade(typeSolver).convertToUsage(parent.getType(), parent);
} else if (node.getParentNode() instanceof VariableDeclarationExpr) {
VariableDeclarationExpr parent = (VariableDeclarationExpr) node.getParentNode();
return new JavaParserFacade(typeSolver).convertToUsage(parent.getType(), parent);
} else {
throw new UnsupportedOperationException(node.getParentNode().getClass().getCanonicalName());
}
} else if (node instanceof Parameter) {
Parameter parameter = (Parameter)node;
if (parameter.getType() instanceof UnknownType){
throw new IllegalStateException("Parameter has unknown type: " + parameter);
}
return new JavaParserFacade(typeSolver).convertToUsage(parameter.getType(), parameter);
} else if (node instanceof FieldAccessExpr) {
FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) node;
// We should understand if this is a static access
try {
Optional<Value> value = new SymbolSolver(typeSolver).solveSymbolAsValue(fieldAccessExpr.getField(), fieldAccessExpr);
if (value.isPresent()) {
return value.get().getUsage();
} else {
throw new UnsolvedSymbolException(fieldAccessExpr.getField());
}
} catch (UnsolvedSymbolException e){
// Sure, it was not found as value because maybe it is a type and this is a static access
if (fieldAccessExpr.getScope() instanceof NameExpr){
NameExpr staticValue = (NameExpr)fieldAccessExpr.getScope();
SymbolReference<TypeDeclaration> typeAccessedStatically = JavaParserFactory.getContext(fieldAccessExpr).solveType(staticValue.toString(), typeSolver);
if (!typeAccessedStatically.isSolved()) {
throw e;
} else {
// TODO here maybe we have to substitute type parameters
return typeAccessedStatically.getCorrespondingDeclaration().getField(fieldAccessExpr.getField(), typeSolver).getType(typeSolver);
}
} else {
throw e;
}
}
} else if (node instanceof ObjectCreationExpr) {
ObjectCreationExpr objectCreationExpr = (ObjectCreationExpr) node;
TypeUsage typeUsage = new JavaParserFacade(typeSolver).convertToUsage(objectCreationExpr.getType(), node);
return typeUsage;
} else if (node instanceof NullLiteralExpr) {
return new NullTypeUsage();
} else if (node instanceof BooleanLiteralExpr) {
return PrimitiveTypeUsage.BOOLEAN;
} else if (node instanceof IntegerLiteralExpr) {
return PrimitiveTypeUsage.INT;
} else if (node instanceof LongLiteralExpr) {
return PrimitiveTypeUsage.LONG;
} else if (node instanceof CharLiteralExpr) {
return PrimitiveTypeUsage.CHAR;
} else if (node instanceof StringLiteralExpr) {
return new TypeUsageOfTypeDeclaration(new JreTypeSolver().solveType("java.lang.String"));
} else if (node instanceof UnaryExpr) {
UnaryExpr unaryExpr = (UnaryExpr)node;
switch (unaryExpr.getOperator()) {
case negative:
case positive:
return getTypeConcrete(unaryExpr.getExpr(), solveLambdas);
case not:
return PrimitiveTypeUsage.BOOLEAN;
case posIncrement:
case preIncrement:
case preDecrement:
case posDecrement:
return getTypeConcrete(unaryExpr.getExpr(), solveLambdas);
default:
throw new UnsupportedOperationException(unaryExpr.getOperator().name());
}
} else if (node instanceof BinaryExpr) {
BinaryExpr binaryExpr = (BinaryExpr) node;
switch (binaryExpr.getOperator()) {
case plus:
case minus:
return getTypeConcrete(binaryExpr.getLeft(), solveLambdas);
case lessEquals:
case less:
case greater:
case greaterEquals:
case equals:
case notEquals:
case or:
case and:
return PrimitiveTypeUsage.BOOLEAN;
case binAnd:
case binOr:
return getTypeConcrete(binaryExpr.getLeft(), solveLambdas);
default:
throw new UnsupportedOperationException("FOO " +binaryExpr.getOperator().name());
}
} else if (node instanceof VariableDeclarationExpr) {
VariableDeclarationExpr expr = (VariableDeclarationExpr)node;
return convertToUsage(expr.getType(), JavaParserFactory.getContext(node));
} else if (node instanceof InstanceOfExpr) {
return PrimitiveTypeUsage.BOOLEAN;
} else if (node instanceof EnclosedExpr) {
EnclosedExpr enclosedExpr = (EnclosedExpr)node;
return getTypeConcrete(enclosedExpr.getInner(), solveLambdas);
} else if (node instanceof CastExpr) {
CastExpr enclosedExpr = (CastExpr)node;
return convertToUsage(enclosedExpr.getType(), JavaParserFactory.getContext(node));
} else if (node instanceof AssignExpr) {
AssignExpr assignExpr = (AssignExpr) node;
return getTypeConcrete(assignExpr.getTarget(), solveLambdas);
} else if (node instanceof ThisExpr) {
return new TypeUsageOfTypeDeclaration(getTypeDeclaration(findContainingTypeDecl(node)));
} else if (node instanceof ConditionalExpr) {
ConditionalExpr conditionalExpr = (ConditionalExpr)node;
return getTypeConcrete(conditionalExpr.getThenExpr(), solveLambdas);
} else if (node instanceof ArrayCreationExpr) {
ArrayCreationExpr arrayCreationExpr = (ArrayCreationExpr)node;
return convertToUsage(arrayCreationExpr.getType(), JavaParserFactory.getContext(node));
} else {
throw new UnsupportedOperationException(node.getClass().getCanonicalName());
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private TypeUsage getTypeConcrete(Node node, boolean solveLambdas) {
if (node == null) throw new IllegalArgumentException();
if (node instanceof NameExpr) {
NameExpr nameExpr = (NameExpr) node;
logger.finest("getType on name expr " + node);
Optional<Value> value = new SymbolSolver(typeSolver).solveSymbolAsValue(nameExpr.getName(), nameExpr);
if (!value.isPresent()){
throw new UnsolvedSymbolException("Solving "+node, nameExpr.getName());
} else {
return value.get().getUsage();
}
} else if (node instanceof MethodCallExpr) {
logger.finest("getType on method call " + node);
// first solve the method
MethodUsage ref = new JavaParserFacade(typeSolver).solveMethodAsUsage((MethodCallExpr) node);
logger.finest("getType on method call " + node + " resolved to " + ref);
logger.finest("getType on method call " + node + " return type is " + ref.returnType());
return ref.returnType();
// the type is the return type of the method
} else if (node instanceof LambdaExpr) {
if (node.getParentNode() instanceof MethodCallExpr) {
MethodCallExpr callExpr = (MethodCallExpr) node.getParentNode();
int pos = JavaParserSymbolDeclaration.getParamPos(node);
SymbolReference<MethodDeclaration> refMethod = new JavaParserFacade(typeSolver).solve(callExpr);
if (!refMethod.isSolved()) {
throw new UnsolvedSymbolException(callExpr.getName());
}
logger.finest("getType on lambda expr " + refMethod.getCorrespondingDeclaration().getName());
//logger.finest("Method param " + refMethod.getCorrespondingDeclaration().getParam(pos));
if (solveLambdas) {
TypeUsage result = refMethod.getCorrespondingDeclaration().getParam(pos).getType(typeSolver);
// We need to replace the type variables
result = result.solveGenericTypes(JavaParserFactory.getContext(node), typeSolver);
return result;
} else {
return refMethod.getCorrespondingDeclaration().getParam(pos).getType(typeSolver);
}
//System.out.println("LAMBDA " + node.getParentNode());
//System.out.println("LAMBDA CLASS " + node.getParentNode().getClass().getCanonicalName());
//TypeUsage typeOfMethod = new JavaParserFacade(typeSolver).getType(node.getParentNode());
//throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value");
} else {
throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value");
}
} else if (node instanceof VariableDeclarator) {
if (node.getParentNode() instanceof FieldDeclaration) {
FieldDeclaration parent = (FieldDeclaration) node.getParentNode();
return new JavaParserFacade(typeSolver).convertToUsage(parent.getType(), parent);
} else if (node.getParentNode() instanceof VariableDeclarationExpr) {
VariableDeclarationExpr parent = (VariableDeclarationExpr) node.getParentNode();
return new JavaParserFacade(typeSolver).convertToUsage(parent.getType(), parent);
} else {
throw new UnsupportedOperationException(node.getParentNode().getClass().getCanonicalName());
}
} else if (node instanceof Parameter) {
Parameter parameter = (Parameter)node;
if (parameter.getType() instanceof UnknownType){
throw new IllegalStateException("Parameter has unknown type: " + parameter);
}
return new JavaParserFacade(typeSolver).convertToUsage(parameter.getType(), parameter);
} else if (node instanceof FieldAccessExpr) {
FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) node;
// We should understand if this is a static access
try {
Optional<Value> value = new SymbolSolver(typeSolver).solveSymbolAsValue(fieldAccessExpr.getField(), fieldAccessExpr);
if (value.isPresent()) {
return value.get().getUsage();
} else {
throw new UnsolvedSymbolException(fieldAccessExpr.getField());
}
} catch (UnsolvedSymbolException e){
// Sure, it was not found as value because maybe it is a type and this is a static access
if (fieldAccessExpr.getScope() instanceof NameExpr){
NameExpr staticValue = (NameExpr)fieldAccessExpr.getScope();
SymbolReference<TypeDeclaration> typeAccessedStatically = JavaParserFactory.getContext(fieldAccessExpr).solveType(staticValue.toString(), typeSolver);
if (!typeAccessedStatically.isSolved()) {
throw e;
} else {
// TODO here maybe we have to substitute type parameters
return typeAccessedStatically.getCorrespondingDeclaration().getField(fieldAccessExpr.getField(), typeSolver).getType(typeSolver);
}
} else {
throw e;
}
}
} else if (node instanceof ObjectCreationExpr) {
ObjectCreationExpr objectCreationExpr = (ObjectCreationExpr) node;
TypeUsage typeUsage = new JavaParserFacade(typeSolver).convertToUsage(objectCreationExpr.getType(), node);
return typeUsage;
} else if (node instanceof NullLiteralExpr) {
return new NullTypeUsage();
} else if (node instanceof BooleanLiteralExpr) {
return PrimitiveTypeUsage.BOOLEAN;
} else if (node instanceof IntegerLiteralExpr) {
return PrimitiveTypeUsage.INT;
} else if (node instanceof LongLiteralExpr) {
return PrimitiveTypeUsage.LONG;
} else if (node instanceof CharLiteralExpr) {
return PrimitiveTypeUsage.CHAR;
} else if (node instanceof StringLiteralExpr) {
return new TypeUsageOfTypeDeclaration(new JreTypeSolver().solveType("java.lang.String"));
} else if (node instanceof UnaryExpr) {
UnaryExpr unaryExpr = (UnaryExpr)node;
switch (unaryExpr.getOperator()) {
case negative:
case positive:
return getTypeConcrete(unaryExpr.getExpr(), solveLambdas);
case not:
return PrimitiveTypeUsage.BOOLEAN;
case posIncrement:
case preIncrement:
case preDecrement:
case posDecrement:
return getTypeConcrete(unaryExpr.getExpr(), solveLambdas);
default:
throw new UnsupportedOperationException(unaryExpr.getOperator().name());
}
} else if (node instanceof BinaryExpr) {
BinaryExpr binaryExpr = (BinaryExpr) node;
switch (binaryExpr.getOperator()) {
case plus:
case minus:
return getTypeConcrete(binaryExpr.getLeft(), solveLambdas);
case lessEquals:
case less:
case greater:
case greaterEquals:
case equals:
case notEquals:
case or:
case and:
return PrimitiveTypeUsage.BOOLEAN;
case binAnd:
case binOr:
return getTypeConcrete(binaryExpr.getLeft(), solveLambdas);
default:
throw new UnsupportedOperationException("FOO " +binaryExpr.getOperator().name());
}
} else if (node instanceof VariableDeclarationExpr) {
VariableDeclarationExpr expr = (VariableDeclarationExpr)node;
return convertToUsage(expr.getType(), JavaParserFactory.getContext(node));
} else if (node instanceof InstanceOfExpr) {
return PrimitiveTypeUsage.BOOLEAN;
} else if (node instanceof EnclosedExpr) {
EnclosedExpr enclosedExpr = (EnclosedExpr)node;
return getTypeConcrete(enclosedExpr.getInner(), solveLambdas);
} else if (node instanceof CastExpr) {
CastExpr enclosedExpr = (CastExpr)node;
return convertToUsage(enclosedExpr.getType(), JavaParserFactory.getContext(node));
} else if (node instanceof AssignExpr) {
AssignExpr assignExpr = (AssignExpr) node;
return getTypeConcrete(assignExpr.getTarget(), solveLambdas);
} else if (node instanceof ThisExpr) {
return new TypeUsageOfTypeDeclaration(getTypeDeclaration(findContainingTypeDecl(node)));
} else if (node instanceof ConditionalExpr) {
ConditionalExpr conditionalExpr = (ConditionalExpr)node;
return getTypeConcrete(conditionalExpr.getThenExpr(), solveLambdas);
} else if (node instanceof ArrayCreationExpr) {
ArrayCreationExpr arrayCreationExpr = (ArrayCreationExpr)node;
return convertToUsage(arrayCreationExpr.getType(), JavaParserFactory.getContext(node));
} else {
throw new UnsupportedOperationException(node.getClass().getCanonicalName());
}
}
#location 161
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Generated("com.github.javaparser.generator.core.visitor.HashCodeVisitorGenerator")
public Integer visit(final ConstructorDeclaration n, final Void arg) {
return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().accept(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg)) * 31 + (n.getComment().isPresent() ? n.getComment().get().accept(this, arg) : 0);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Generated("com.github.javaparser.generator.core.visitor.HashCodeVisitorGenerator")
public Integer visit(final ConstructorDeclaration n, final Void arg) {
return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().accept(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getReceiverParameter().isPresent() ? n.getReceiverParameter().get().accept(this, arg) : 0) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg)) * 31 + (n.getComment().isPresent() ? n.getComment().get().accept(this, arg) : 0);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "AClass.java");
CombinedTypeSolver localCts = new CombinedTypeSolver();
localCts.add(new ReflectionTypeSolver());
localCts.add(new JavaParserTypeSolver(src));
ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts));
JavaParser parser = new JavaParser(parserConfiguration);
StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name());
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get();
Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "AClass.java");
CombinedTypeSolver localCts = new CombinedTypeSolver();
localCts.add(new ReflectionTypeSolver());
localCts.add(new JavaParserTypeSolver(src));
ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts));
JavaParser parser = new JavaParser(parserConfiguration);
StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8);
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get();
Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
}
#location 13
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public Type getType() {
if (wrappedNode instanceof Parameter) {
Parameter parameter = (Parameter) wrappedNode;
if (getParentNode(wrappedNode) instanceof LambdaExpr) {
int pos = getParamPos(parameter);
Type lambdaType = JavaParserFacade.get(typeSolver).getType(getParentNode(wrappedNode));
// TODO understand from the context to which method this corresponds
//MethodDeclaration methodDeclaration = JavaParserFacade.get(typeSolver).getMethodCalled
//MethodDeclaration methodCalled = JavaParserFacade.get(typeSolver).solve()
throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName());
} else {
Type rawType = null;
if (parameter.getType() instanceof com.github.javaparser.ast.type.PrimitiveType) {
rawType = PrimitiveType.byName(((com.github.javaparser.ast.type.PrimitiveType) parameter.getType()).getType().name());
} else {
rawType = JavaParserFacade.get(typeSolver).convertToUsage(parameter.getType(), wrappedNode);
}
if (parameter.isVarArgs()) {
return new ArrayType(rawType);
} else {
return rawType;
}
}
} else if (wrappedNode instanceof VariableDeclarator) {
VariableDeclarator variableDeclarator = (VariableDeclarator) wrappedNode;
if (getParentNode(wrappedNode) instanceof VariableDeclarationExpr) {
VariableDeclarationExpr variableDeclarationExpr = (VariableDeclarationExpr) getParentNode(variableDeclarator);
return JavaParserFacade.get(typeSolver).convert(variableDeclarationExpr.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver));
} else if (getParentNode(wrappedNode) instanceof FieldDeclaration) {
FieldDeclaration fieldDeclaration = (FieldDeclaration) getParentNode(variableDeclarator);
return JavaParserFacade.get(typeSolver).convert(fieldDeclaration.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver));
} else {
throw new UnsupportedOperationException(getParentNode(wrappedNode).getClass().getCanonicalName());
}
} else {
throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName());
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Type getType() {
if (wrappedNode instanceof Parameter) {
Parameter parameter = (Parameter) wrappedNode;
if (wrappedNode.getParentNode() instanceof LambdaExpr) {
int pos = getParamPos(parameter);
Type lambdaType = JavaParserFacade.get(typeSolver).getType(wrappedNode.getParentNode());
// TODO understand from the context to which method this corresponds
//MethodDeclaration methodDeclaration = JavaParserFacade.get(typeSolver).getMethodCalled
//MethodDeclaration methodCalled = JavaParserFacade.get(typeSolver).solve()
throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName());
} else {
Type rawType = null;
if (parameter.getType() instanceof com.github.javaparser.ast.type.PrimitiveType) {
rawType = PrimitiveType.byName(((com.github.javaparser.ast.type.PrimitiveType) parameter.getType()).getType().name());
} else {
rawType = JavaParserFacade.get(typeSolver).convertToUsage(parameter.getType(), wrappedNode);
}
if (parameter.isVarArgs()) {
return new ArrayType(rawType);
} else {
return rawType;
}
}
} else if (wrappedNode instanceof VariableDeclarator) {
VariableDeclarator variableDeclarator = (VariableDeclarator) wrappedNode;
if (wrappedNode.getParentNode() instanceof VariableDeclarationExpr) {
VariableDeclarationExpr variableDeclarationExpr = (VariableDeclarationExpr) variableDeclarator.getParentNode();
return JavaParserFacade.get(typeSolver).convert(variableDeclarationExpr.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver));
} else if (wrappedNode.getParentNode() instanceof FieldDeclaration) {
FieldDeclaration fieldDeclaration = (FieldDeclaration) variableDeclarator.getParentNode();
return JavaParserFacade.get(typeSolver).convert(fieldDeclaration.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver));
} else {
throw new UnsupportedOperationException(wrappedNode.getParentNode().getClass().getCanonicalName());
}
} else {
throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName());
}
}
#location 30
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public List<ReferenceTypeUsage> getAllAncestors() {
List<ReferenceTypeUsage> ancestors = new LinkedList<>();
if (getSuperClass(typeSolver) != null) {
ReferenceTypeUsage superClass = getSuperClass(typeSolver);
ancestors.add(superClass);
ancestors.addAll(getSuperClass(typeSolver).getAllAncestors());
}
ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new ReferenceTypeUsage(i, typeSolver)).collect(Collectors.<ReferenceTypeUsage>toList()));
return ancestors;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public List<ReferenceTypeUsage> getAllAncestors() {
List<ReferenceTypeUsage> ancestors = new LinkedList<>();
if (getSuperClass(typeSolver) != null) {
ancestors.add(new ReferenceTypeUsage(getSuperClass(typeSolver), typeSolver));
ancestors.addAll(getSuperClass(typeSolver).getAllAncestors());
}
ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new ReferenceTypeUsage(i, typeSolver)).collect(Collectors.<ReferenceTypeUsage>toList()));
return ancestors;
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
public Optional<Value> solveSymbolAsValue(String name, Node node) {
Context context = JavaParserFactory.getContext(node);
return solveSymbolAsValue(name, context);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Optional<Value> solveSymbolAsValue(String name, Node node) {
return solveSymbolAsValue(name, JavaParserFactory.getContext(node));
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "AClass.java");
CombinedTypeSolver localCts = new CombinedTypeSolver();
localCts.add(new ReflectionTypeSolver());
localCts.add(new JavaParserTypeSolver(src));
ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts));
JavaParser parser = new JavaParser(parserConfiguration);
StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8);
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get();
Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "AClass.java");
CombinedTypeSolver localCts = new CombinedTypeSolver();
localCts.add(new ReflectionTypeSolver());
localCts.add(new JavaParserTypeSolver(src));
ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts));
JavaParser parser = new JavaParser(parserConfiguration);
StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass));
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get();
Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK |
#fixed code
@Generated("com.github.javaparser.generator.core.visitor.NoCommentHashCodeVisitorGenerator")
public Integer visit(final ConstructorDeclaration n, final Void arg) {
return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().accept(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Generated("com.github.javaparser.generator.core.visitor.NoCommentHashCodeVisitorGenerator")
public Integer visit(final ConstructorDeclaration n, final Void arg) {
return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().accept(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getReceiverParameter().isPresent() ? n.getReceiverParameter().get().accept(this, arg) : 0) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg));
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "AClass.java");
CombinedTypeSolver localCts = new CombinedTypeSolver();
localCts.add(new ReflectionTypeSolver());
localCts.add(new JavaParserTypeSolver(src));
ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts));
JavaParser parser = new JavaParser(parserConfiguration);
StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8);
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get();
Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("AND", fae.get().resolve().getName());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "AClass.java");
CombinedTypeSolver localCts = new CombinedTypeSolver();
localCts.add(new ReflectionTypeSolver());
localCts.add(new JavaParserTypeSolver(src));
ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts));
JavaParser parser = new JavaParser(parserConfiguration);
StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass));
CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get();
Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("AND", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void shouldReturnThePrimaryKeysAtTheEndWhenMultipleFieldsFormThePrimaryKey() {
Schema schema = SchemaBuilder.struct().name("com.example.Person")
.field("firstName", Schema.STRING_SCHEMA)
.field("lastName", Schema.STRING_SCHEMA)
.field("age", Schema.INT32_SCHEMA)
.field("bool", Schema.BOOLEAN_SCHEMA)
.field("short", Schema.INT16_SCHEMA)
.field("byte", Schema.INT8_SCHEMA)
.field("long", Schema.INT64_SCHEMA)
.field("float", Schema.FLOAT32_SCHEMA)
.field("double", Schema.FLOAT64_SCHEMA)
.field("bytes", Schema.BYTES_SCHEMA)
.field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build();
short s = 1234;
byte b = -32;
long l = 12425436;
float f = (float) 2356.3;
double d = -2436546.56457;
byte[] bs = new byte[]{-32, 124};
Struct struct = new Struct(schema)
.put("firstName", "Alex")
.put("lastName", "Smith")
.put("bool", true)
.put("short", s)
.put("byte", b)
.put("long", l)
.put("float", f)
.put("double", d)
.put("bytes", bs)
.put("age", 30);
Map<String, FieldAlias> mappings = new HashMap<>();
mappings.put("firstName", new FieldAlias("fName", true));
mappings.put("lastName", new FieldAlias("lName", true));
FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings);
StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm);
List<PreparedStatementBinder> binders = dataExtractor.get(struct,
new SinkRecord("", 1, null, null, schema, struct, 0));
HashMap<String, PreparedStatementBinder> map = new HashMap<>();
List<PreparedStatementBinder> pkBinders = new LinkedList<>();
for (PreparedStatementBinder p : binders) {
if (p.isPrimaryKey()) {
pkBinders.add(p);
}
map.put(p.getFieldName(), p);
}
assertTrue(!binders.isEmpty());
assertEquals(binders.size(), 10);
assertEquals(pkBinders.size(), 2);
assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "fName") ||
Objects.equals(pkBinders.get(1).getFieldName(), "fName")
);
assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "lName") ||
Objects.equals(pkBinders.get(1).getFieldName(), "lName")
);
assertTrue(map.containsKey("fName"));
assertTrue(map.get("fName").getClass() == StringPreparedStatementBinder.class);
assertTrue(map.containsKey("lName"));
assertTrue(map.get("lName").getClass() == StringPreparedStatementBinder.class);
assertTrue(map.containsKey("age"));
assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class);
assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class);
assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l);
assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class);
assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s);
assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class);
assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b);
assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class);
assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0);
assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class);
assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0);
assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class);
assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue()));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void shouldReturnThePrimaryKeysAtTheEndWhenMultipleFieldsFormThePrimaryKey() {
Schema schema = SchemaBuilder.struct().name("com.example.Person")
.field("firstName", Schema.STRING_SCHEMA)
.field("lastName", Schema.STRING_SCHEMA)
.field("age", Schema.INT32_SCHEMA)
.field("bool", Schema.BOOLEAN_SCHEMA)
.field("short", Schema.INT16_SCHEMA)
.field("byte", Schema.INT8_SCHEMA)
.field("long", Schema.INT64_SCHEMA)
.field("float", Schema.FLOAT32_SCHEMA)
.field("double", Schema.FLOAT64_SCHEMA)
.field("bytes", Schema.BYTES_SCHEMA)
.field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build();
short s = 1234;
byte b = -32;
long l = 12425436;
float f = (float) 2356.3;
double d = -2436546.56457;
byte[] bs = new byte[]{-32, 124};
Struct struct = new Struct(schema)
.put("firstName", "Alex")
.put("lastName", "Smith")
.put("bool", true)
.put("short", s)
.put("byte", b)
.put("long", l)
.put("float", f)
.put("double", d)
.put("bytes", bs)
.put("age", 30);
Map<String, FieldAlias> mappings = new HashMap<>();
mappings.put("firstName", new FieldAlias("fName", true));
mappings.put("lastName", new FieldAlias("lName", true));
FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings);
StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm);
StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct,
new SinkRecord("", 1, null, null, schema, struct, 0));
HashMap<String, PreparedStatementBinder> map = new HashMap<>();
for (PreparedStatementBinder p : Iterables.concat(binders.getNonKeyColumns(), binders.getKeyColumns()))
map.put(p.getFieldName(), p);
assertTrue(!binders.isEmpty());
assertEquals(binders.getNonKeyColumns().size() + binders.getKeyColumns().size(), 10);
List<PreparedStatementBinder> pkBinders = binders.getKeyColumns();
assertEquals(pkBinders.size(), 2);
assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "fName") ||
Objects.equals(pkBinders.get(1).getFieldName(), "fName")
);
assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "lName") ||
Objects.equals(pkBinders.get(1).getFieldName(), "lName")
);
assertTrue(map.containsKey("fName"));
assertTrue(map.get("fName").getClass() == StringPreparedStatementBinder.class);
assertTrue(map.containsKey("lName"));
assertTrue(map.get("lName").getClass() == StringPreparedStatementBinder.class);
assertTrue(map.containsKey("age"));
assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class);
assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class);
assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l);
assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class);
assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s);
assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class);
assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b);
assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class);
assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0);
assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class);
assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0);
assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class);
assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue()));
}
#location 49
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void handleAllFieldsMappingSettingAndTheMappingsProvided() {
List<DbTableColumn> columns = Lists.newArrayList(
new DbTableColumn("col1", true, false, 1),
new DbTableColumn("col2", false, false, 1),
new DbTableColumn("col3", false, false, 1));
DbTable table = new DbTable("tableA", columns);
Map<String, FieldAlias> aliasMap = new HashMap<>();
aliasMap.put("f1", new FieldAlias("col3"));
FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap);
FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT);
assertEquals(newMappings.getTableName(), mappings.getTableName());
assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic());
assertEquals(newMappings.areAllFieldsIncluded(), false);
Map<String, FieldAlias> newAliasMap = newMappings.getMappings();
assertEquals(4, newAliasMap.size()); //+ the specific mapping
assertTrue(newAliasMap.containsKey("col1"));
assertEquals(newAliasMap.get("col1").getName(), "col1");
assertEquals(newAliasMap.get("col1").isPrimaryKey(), true);
assertTrue(newAliasMap.containsKey("col2"));
assertEquals(newAliasMap.get("col2").getName(), "col2");
assertEquals(newAliasMap.get("col2").isPrimaryKey(), false);
assertTrue(newAliasMap.containsKey("col3"));
assertEquals(newAliasMap.get("col3").getName(), "col3");
assertEquals(newAliasMap.get("col3").isPrimaryKey(), false);
assertTrue(newAliasMap.containsKey("f1"));
assertEquals(newAliasMap.get("f1").getName(), "col3");
assertEquals(newAliasMap.get("f1").isPrimaryKey(), false);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void handleAllFieldsMappingSettingAndTheMappingsProvided() {
List<DbTableColumn> columns = Lists.newArrayList(
new DbTableColumn("col1", true, false, 1),
new DbTableColumn("col2", false, false, 1),
new DbTableColumn("col3", false, false, 1));
DbTable table = new DbTable("tableA", columns);
Map<String, FieldAlias> aliasMap = new HashMap<>();
aliasMap.put("f1", new FieldAlias("col3"));
FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap);
FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table);
assertEquals(newMappings.getTableName(), mappings.getTableName());
assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic());
assertEquals(newMappings.areAllFieldsIncluded(), false);
Map<String, FieldAlias> newAliasMap = newMappings.getMappings();
assertEquals(4, newAliasMap.size()); //+ the specific mapping
assertTrue(newAliasMap.containsKey("col1"));
assertEquals(newAliasMap.get("col1").getName(), "col1");
assertEquals(newAliasMap.get("col1").isPrimaryKey(), true);
assertTrue(newAliasMap.containsKey("col2"));
assertEquals(newAliasMap.get("col2").getName(), "col2");
assertEquals(newAliasMap.get("col2").isPrimaryKey(), false);
assertTrue(newAliasMap.containsKey("col3"));
assertEquals(newAliasMap.get("col3").getName(), "col3");
assertEquals(newAliasMap.get("col3").isPrimaryKey(), false);
assertTrue(newAliasMap.containsKey("f1"));
assertEquals(newAliasMap.get("f1").getName(), "col3");
assertEquals(newAliasMap.get("f1").isPrimaryKey(), false);
}
#location 21
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void connect() throws IOException {
if (!connectLock.tryLock()) {
throw new IllegalStateException("BinaryLogClient is already connected");
}
boolean notifyWhenDisconnected = false;
try {
try {
channel = openChannel();
GreetingPacket greetingPacket = receiveGreeting();
authenticate(greetingPacket);
connectionId = greetingPacket.getThreadId();
if (binlogFilename == null) {
fetchBinlogFilenameAndPosition();
}
if (binlogPosition < 4) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4);
}
binlogPosition = 4;
}
ChecksumType checksumType = fetchBinlogChecksum();
if (checksumType != ChecksumType.NONE) {
confirmSupportOfChecksum(checksumType);
}
requestBinaryLogStream();
} catch (IOException e) {
disconnectChannel();
throw e;
}
connected = true;
notifyWhenDisconnected = true;
if (logger.isLoggable(Level.INFO)) {
String position;
synchronized (gtidSetAccessLock) {
position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition;
}
logger.info("Connected to " + hostname + ":" + port + " at " + position +
" (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")");
}
synchronized (lifecycleListeners) {
for (LifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onConnect(this);
}
}
if (keepAlive && !isKeepAliveThreadRunning()) {
spawnKeepAliveThread();
}
ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class);
synchronized (gtidSetAccessLock) {
if (gtidSet != null) {
ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class);
}
}
listenForEventPackets();
} finally {
connectLock.unlock();
if (notifyWhenDisconnected) {
synchronized (lifecycleListeners) {
for (LifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onDisconnect(this);
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void connect() throws IOException {
if (connected) {
throw new IllegalStateException("BinaryLogClient is already connected");
}
GreetingPacket greetingPacket;
try {
try {
Socket socket = socketFactory != null ? socketFactory.createSocket() : new Socket();
socket.connect(new InetSocketAddress(hostname, port));
channel = new PacketChannel(socket);
if (channel.getInputStream().peek() == -1) {
throw new EOFException();
}
} catch (IOException e) {
throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port +
". Please make sure it's running.", e);
}
greetingPacket = receiveGreeting();
authenticate(greetingPacket);
if (binlogFilename == null) {
fetchBinlogFilenameAndPosition();
}
if (binlogPosition < 4) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4);
}
binlogPosition = 4;
}
ChecksumType checksumType = fetchBinlogChecksum();
if (checksumType != ChecksumType.NONE) {
confirmSupportOfChecksum(checksumType);
}
requestBinaryLogStream();
} catch (IOException e) {
if (channel != null && channel.isOpen()) {
channel.close();
}
throw e;
}
connected = true;
connectionId = greetingPacket.getThreadId();
if (logger.isLoggable(Level.INFO)) {
String position;
synchronized (gtidSetAccessLock) {
position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition;
}
logger.info("Connected to " + hostname + ":" + port + " at " + position +
" (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")");
}
synchronized (lifecycleListeners) {
for (LifecycleListener lifecycleListener : lifecycleListeners) {
lifecycleListener.onConnect(this);
}
}
if (keepAlive && !isKeepAliveThreadRunning()) {
spawnKeepAliveThread();
}
ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class);
synchronized (gtidSetAccessLock) {
if (gtidSet != null) {
ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class);
}
}
listenForEventPackets();
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void testChecksumNONE() throws Exception {
EventDeserializer eventDeserializer = new EventDeserializer();
BinaryLogFileReader reader = new BinaryLogFileReader(
new FileInputStream("src/test/resources/mysql-bin.checksum-none"), eventDeserializer);
readAll(reader, 191);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testChecksumNONE() throws Exception {
EventDeserializer eventDeserializer = new EventDeserializer();
BinaryLogFileReader reader = new BinaryLogFileReader(new GZIPInputStream(
new FileInputStream("src/test/resources/mysql-bin.sakila.gz")), eventDeserializer);
readAll(reader, 1462);
}
#location 4
#vulnerability type RESOURCE_LEAK |
#fixed code
private List<WordFrequency> loadFrequencies(final String input) {
try {
final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
frequencyAnalyzer.setWordFrequenciesToReturn(cliParameters.getWordCount());
frequencyAnalyzer.setMinWordLength(cliParameters.getMinWordLength());
frequencyAnalyzer.setStopWords(cliParameters.getStopWords());
frequencyAnalyzer.setCharacterEncoding(cliParameters.getCharacterEncoding());
if (cliParameters.getNormalizers().isEmpty()) {
cliParameters.getNormalizers().addAll(Arrays.asList(NormalizerType.TRIM, NormalizerType.CHARACTER_STRIPPING, NormalizerType.LOWERCASE));
}
for (final NormalizerType normalizer : cliParameters.getNormalizers()) {
frequencyAnalyzer.addNormalizer(buildNormalizer(normalizer));
}
frequencyAnalyzer.setWordTokenizer(buildTokenizer());
return frequencyAnalyzer.load(toInputStream(input));
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private List<WordFrequency> loadFrequencies(final String input) {
try {
final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
frequencyAnalyzer.setWordFrequenciesToReturn(cliParameters.getWordCount());
frequencyAnalyzer.setMinWordLength(cliParameters.getMinWordLength());
frequencyAnalyzer.setStopWords(cliParameters.getStopWords());
frequencyAnalyzer.setCharacterEncoding(cliParameters.getCharacterEncoding());
for (final NormalizerType normalizer : cliParameters.getNormalizers()) {
frequencyAnalyzer.setNormalizer(buildNormalizer(normalizer));
}
frequencyAnalyzer.setWordTokenizer(buildTokenizer());
return frequencyAnalyzer.load(toInputStream(input));
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
#location 13
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testSyncHandleSuccessfulResponse() throws Exception {
RpcFuture<String> rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient);
RpcResponse response = new RpcResponse();
response.setResult("hello world");
rpcFuture.handleResponse(response);
String resp = rpcFuture.get(1, TimeUnit.SECONDS);
assertThat(resp, is("hello world"));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testSyncHandleSuccessfulResponse() throws Exception {
RpcFuture rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient);
RpcResponse response = new RpcResponse();
response.setResult("hello world");
rpcFuture.handleResponse(response);
Response resp = rpcFuture.get(1, TimeUnit.SECONDS);
assertThat((String) resp.getResult(), is("hello world"));
}
#location 8
#vulnerability type NULL_DEREFERENCE |
#fixed code
private void generateBuildConfig() throws MojoExecutionException
{
getLog().debug( "Generating BuildConfig file" );
// Create the BuildConfig for our package.
String packageName = extractPackageNameFromAndroidManifest( androidManifestFile );
if ( StringUtils.isNotBlank( customPackage ) )
{
packageName = customPackage;
}
generateBuildConfigForPackage( packageName );
// Generate the BuildConfig for any APKLIB and AAR dependencies.
// Need to generate for AAR, because some old AARs like ActionBarSherlock do not have BuildConfig (or R)
for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB, AAR ) )
{
if ( skipBuildConfigGeneration( artifact ) )
{
continue;
}
final File manifest = new File( getUnpackedLibFolder( artifact ), "AndroidManifest.xml" );
final String depPackageName = extractPackageNameFromAndroidManifest( manifest );
generateBuildConfigForPackage( depPackageName );
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void generateBuildConfig() throws MojoExecutionException
{
getLog().debug( "Generating BuildConfig file" );
// Create the BuildConfig for our package.
String packageName = extractPackageNameFromAndroidManifest( androidManifestFile );
if ( StringUtils.isNotBlank( customPackage ) )
{
packageName = customPackage;
}
generateBuildConfigForPackage( packageName );
try
{
// Generate the BuildConfig for any APKLIB and AAR dependencies.
// Need to generate for AAR, because some old AARs like ActionBarSherlock do not have BuildConfig (or R)
for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB, AAR ) )
{
final File manifest = new File( getUnpackedLibFolder( artifact ), "AndroidManifest.xml" );
final String depPackageName = extractPackageNameFromAndroidManifest( manifest );
if ( artifact.getType().equals( AAR ) )
{
final JarFile jar = new JarFile( getUnpackedAarClassesJar( artifact ) );
final JarEntry entry = jar.getJarEntry( depPackageName.replace( '.', '/' ) + "/BuildConfig.class" );
if ( entry != null )
{
getLog().info( "Skip BuildConfig.java generation for "
+ artifact.getGroupId() + " " + artifact.getArtifactId() );
continue;
}
}
generateBuildConfigForPackage( depPackageName );
}
}
catch ( IOException e )
{
getLog().error( "Error generating BuildConfig ", e );
throw new MojoExecutionException( "Error generating BuildConfig", e );
}
}
#location 25
#vulnerability type RESOURCE_LEAK |
#fixed code
public MakefileHolder createMakefileFromArtifacts( File outputDir, Set<Artifact> artifacts,
String ndkArchitecture,
boolean useHeaderArchives )
throws IOException, MojoExecutionException
{
final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" );
final List<File> includeDirectories = new ArrayList<File>();
// Add now output - allows us to somewhat intelligently determine the include paths to use for the header
// archive
makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $("
+ MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
if ( ! artifacts.isEmpty() )
{
for ( Artifact artifact : artifacts )
{
if ( !NativeHelper.isMatchinArchitecture( ndkArchitecture, artifact ) )
{
continue;
}
makeFile.append( "#\n" );
makeFile.append( "# Group ID: " );
makeFile.append( artifact.getGroupId() );
makeFile.append( '\n' );
makeFile.append( "# Artifact ID: " );
makeFile.append( artifact.getArtifactId() );
makeFile.append( '\n' );
makeFile.append( "# Artifact Type: " );
makeFile.append( artifact.getType() );
makeFile.append( '\n' );
makeFile.append( "# Version: " );
makeFile.append( artifact.getVersion() );
makeFile.append( '\n' );
makeFile.append( "include $(CLEAR_VARS)" );
makeFile.append( '\n' );
makeFile.append( "LOCAL_MODULE := " );
makeFile.append( artifact.getArtifactId() );
makeFile.append( '\n' );
final boolean apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture );
if ( useHeaderArchives )
{
try
{
Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(),
artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(),
artifact.getArtifactHandler() );
final Artifact resolvedHarArtifact = AetherHelper
.resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos );
File includeDir = new File( System.getProperty( "java.io.tmpdir" ),
"android_maven_plugin_native_includes" + System.currentTimeMillis() + "_"
+ resolvedHarArtifact.getArtifactId() );
includeDir.deleteOnExit();
includeDirectories.add( includeDir );
JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir,
new JarHelper.UnjarListener()
{
@Override
public boolean include( JarEntry jarEntry )
{
return ! jarEntry.getName().startsWith( "META-INF" );
}
} );
makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " );
final String str = includeDir.getAbsolutePath();
makeFile.append( str );
makeFile.append( '\n' );
if ( log.isDebugEnabled() )
{
Collection<File> includes = FileUtils.listFiles( includeDir,
TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE );
log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes );
}
}
catch ( Exception e )
{
throw new MojoExecutionException(
"Error while resolving header archive file for: " + artifact.getArtifactId(), e );
}
}
if ( "a".equals( artifact.getType() ) || apklibStatic )
{
makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" );
}
else
{
makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" );
}
}
}
return new MakefileHolder( includeDirectories, makeFile.toString() );
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public MakefileHolder createMakefileFromArtifacts( File outputDir, Set<Artifact> artifacts,
String ndkArchitecture,
boolean useHeaderArchives )
throws IOException, MojoExecutionException
{
final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" );
final List<File> includeDirectories = new ArrayList<File>();
// Add now output - allows us to somewhat intelligently determine the include paths to use for the header
// archive
makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $("
+ MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" );
makeFile.append( '\n' );
if ( ! artifacts.isEmpty() )
{
for ( Artifact artifact : artifacts )
{
boolean apklibStatic = false;
makeFile.append( "#\n" );
makeFile.append( "# Group ID: " );
makeFile.append( artifact.getGroupId() );
makeFile.append( '\n' );
makeFile.append( "# Artifact ID: " );
makeFile.append( artifact.getArtifactId() );
makeFile.append( '\n' );
makeFile.append( "# Artifact Type: " );
makeFile.append( artifact.getType() );
makeFile.append( '\n' );
makeFile.append( "# Version: " );
makeFile.append( artifact.getVersion() );
makeFile.append( '\n' );
makeFile.append( "include $(CLEAR_VARS)" );
makeFile.append( '\n' );
makeFile.append( "LOCAL_MODULE := " );
makeFile.append( artifact.getArtifactId() );
makeFile.append( '\n' );
apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture );
if ( useHeaderArchives )
{
try
{
Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(),
artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(),
artifact.getArtifactHandler() );
final Artifact resolvedHarArtifact = AetherHelper
.resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos );
File includeDir = new File( System.getProperty( "java.io.tmpdir" ),
"android_maven_plugin_native_includes" + System.currentTimeMillis() + "_"
+ resolvedHarArtifact.getArtifactId() );
includeDir.deleteOnExit();
includeDirectories.add( includeDir );
JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir,
new JarHelper.UnjarListener()
{
@Override
public boolean include( JarEntry jarEntry )
{
return ! jarEntry.getName().startsWith( "META-INF" );
}
} );
makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " );
final String str = includeDir.getAbsolutePath();
makeFile.append( str );
makeFile.append( '\n' );
if ( log.isDebugEnabled() )
{
Collection<File> includes = FileUtils.listFiles( includeDir,
TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE );
log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes );
}
}
catch ( Exception e )
{
throw new MojoExecutionException(
"Error while resolving header archive file for: " + artifact.getArtifactId(), e );
}
}
if ( "a".equals( artifact.getType() ) || apklibStatic )
{
makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" );
}
else
{
makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" );
}
}
}
return new MakefileHolder( includeDirectories, makeFile.toString() );
}
#location 65
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void describeAsAdditionalInfo_notEmpty() {
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
addCompareException(exceptions);
assertExpectedFacts(
exceptions.describeAsAdditionalInfo(),
"additionally, one or more exceptions were thrown while comparing elements");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void describeAsAdditionalInfo_notEmpty() {
Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable();
addCompareException(exceptions);
assertExpectedFacts(
exceptions.describeAsAdditionalInfo().asIterable(),
"additionally, one or more exceptions were thrown while comparing elements");
}
#location 6
#vulnerability type NULL_DEREFERENCE |
#fixed code
public String getConceptNetUrl() {
String urlFromConfigOrDefault = (String)getConfiguration().getSettingValueFor(CONFIG_KEY_URL);
return urlFromConfigOrDefault == null
? DEFAULT_CONCEPTNET_URL
: urlFromConfigOrDefault;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public String getConceptNetUrl() {
String urlFromConfigOrDefault = getConfiguration().getSettingValueFor(CONFIG_KEY_URL).toString();
return urlFromConfigOrDefault == null
? DEFAULT_CONCEPTNET_URL
: urlFromConfigOrDefault;
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
public static List<Class<?>> getClasses(final String packageName) {
List<Class<?>> classes = new LinkedList<Class<?>>();
List<File> paths = getPackageDirectories(packageName);
for (File path : paths) {
for (File entry : path.listFiles()) {
if (isClass(entry.getName())) {
Class<?> clazz = getPathEntryAsClass(packageName, entry.getName());
classes.add(clazz);
}
}
}
return classes;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static List<Class<?>> getClasses(final String packageName) {
List<Class<?>> classes = new LinkedList<Class<?>>();
File directory = getPackageAsDirectory(packageName);
for (File entry : directory.listFiles()) {
if (isClass(entry.getName())) {
Class<?> clazz = getPathEntryAsClass(packageName, entry.getName());
classes.add(clazz);
}
}
return classes;
}
#location 6
#vulnerability type NULL_DEREFERENCE |
#fixed code
public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) {
return SetupConfig.get().getDynamicBuildRepository()
.getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) {
return new DynamicBuildRepository().getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString());
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public Future<byte[]> get(String uri, Callback<byte[]> callback) {
return request("GET", uri, null, null, null, null, null, callback);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Future<byte[]> get(String uri, Callback<byte[]> callback) {
HttpGet req = new HttpGet(uri);
Log.debug("Starting HTTP GET request", "request", req.getRequestLine());
return execute(client, req, callback);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public static void setRootPath(String rootPath) {
Log.info("Setting 'root' application path", "path", rootPath);
Conf.rootPath = cleanPath(rootPath);
setStaticPath(Conf.rootPath + "/static");
setDynamicPath(Conf.rootPath + "/dynamic");
setConfigPath(Conf.rootPath);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void setRootPath(String rootPath) {
Log.info("Setting 'root' application path", "path", rootPath);
Conf.rootPath = cleanPath(rootPath);
setStaticPath(Conf.rootPath + "/static");
setDynamicPath(Conf.rootPath + "/dynamic");
setConfigPath(Conf.rootPath);
setTemplatesPath(Conf.rootPath + "/templates");
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public static void main(String[] args) {
final HttpParser parser = new HttpParser();
final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)};
final RapidoidHelper helper = new RapidoidHelper(null);
for (int i = 0; i < 100; i++) {
Msc.benchmark("parse", 3000000, new Runnable() {
int n;
@Override
public void run() {
Buf buf = reqs[n % 4];
buf.position(0);
parser.parse(buf, helper);
n++;
}
});
}
System.out.println(BUFS.instances() + " buffer instances.");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void main(String[] args) {
final HttpParser parser = new HttpParser();
final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)};
final RapidoidHelper helper = new RapidoidHelper(null);
BufRange[] ranges = helper.ranges1.ranges;
final BufRanges headers = helper.ranges2;
final BoolWrap isGet = helper.booleans[0];
final BoolWrap isKeepAlive = helper.booleans[1];
final BufRange verb = ranges[ranges.length - 1];
final BufRange uri = ranges[ranges.length - 2];
final BufRange path = ranges[ranges.length - 3];
final BufRange query = ranges[ranges.length - 4];
final BufRange protocol = ranges[ranges.length - 5];
final BufRange body = ranges[ranges.length - 6];
for (int i = 0; i < 10; i++) {
Msc.benchmark("parse", 3000000, new Runnable() {
int n;
@Override
public void run() {
Buf buf = reqs[n % 4];
buf.position(0);
parser.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, headers, helper);
n++;
}
});
}
System.out.println(BUFS.instances() + " buffer instances.");
}
#location 30
#vulnerability type RESOURCE_LEAK |
#fixed code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void initDbConnectServer() throws Exception{
dbRpcConnnectManngeer.initManager();
dbRpcConnnectManngeer.initServers(sdDbServers);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void loadPackage(String namespace, String ext)
throws Exception {
if(fileNames == null){
fileNames = messageScanner.scannerPackage(namespace, ext);
}
// 加载class,获取协议命令
DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader();
defaultClassLoader.resetDynamicGameClassLoader();
DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader();
if(fileNames != null) {
for (String fileName : fileNames) {
String realClass = namespace
+ "."
+ fileName.subSequence(0, fileName.length()
- (ext.length()));
// Class<?> messageClass = null;
// FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader();
// if (!defaultClassLoader.isJarLoad()) {
// defaultClassLoader.initClassLoaderPath(realClass, ext);
// byte[] bytes = fileClassLoader.getClassData(realClass);
// messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
// } else {
// //读取 game_server_handler.jar包所在位置
// URL url = ClassLoader.getSystemClassLoader().getResource("./");
// File file = new File(url.getPath());
// File parentFile = new File(file.getParent());
// String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar";
// logger.info("message load jar path:" + jarPath);
// JarFile jarFile = new JarFile(new File(jarPath));
// fileClassLoader.initJarPath(jarFile);
// byte[] bytes = fileClassLoader.getClassData(realClass);
// messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
// }
Class<?> messageClass = Class.forName(realClass);
logger.info("handler load: " + messageClass);
IMessageHandler iMessageHandler = getMessageHandler(messageClass);
AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler;
handler.init();
Method[] methods = messageClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MessageCommandAnnotation.class)) {
MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method
.getAnnotation(MessageCommandAnnotation.class);
if (messageCommandAnnotation != null) {
addHandler(messageCommandAnnotation.command(), iMessageHandler);
}
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void loadPackage(String namespace, String ext)
throws Exception {
if(fileNames == null){
fileNames = messageScanner.scannerPackage(namespace, ext);
}
// 加载class,获取协议命令
DefaultClassLoader defaultClassLoader = LocalMananger.getInstance().getLocalSpringServiceManager().getDefaultClassLoader();
defaultClassLoader.resetDynamicGameClassLoader();
DynamicGameClassLoader dynamicGameClassLoader = defaultClassLoader.getDynamicGameClassLoader();
if(fileNames != null) {
for (String fileName : fileNames) {
String realClass = namespace
+ "."
+ fileName.subSequence(0, fileName.length()
- (ext.length()));
Class<?> messageClass = null;
FileClassLoader fileClassLoader = defaultClassLoader.getDefaultClassLoader();
if (!defaultClassLoader.isJarLoad()) {
defaultClassLoader.initClassLoaderPath(realClass, ext);
byte[] bytes = fileClassLoader.getClassData(realClass);
messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
} else {
//读取 game_server_handler.jar包所在位置
URL url = ClassLoader.getSystemClassLoader().getResource("./");
File file = new File(url.getPath());
File parentFile = new File(file.getParent());
String jarPath = parentFile.getPath() + File.separator + "lib/game_server_handler.jar";
logger.info("message load jar path:" + jarPath);
JarFile jarFile = new JarFile(new File(jarPath));
fileClassLoader.initJarPath(jarFile);
byte[] bytes = fileClassLoader.getClassData(realClass);
messageClass = dynamicGameClassLoader.findClass(realClass, bytes);
}
logger.info("handler load: " + messageClass);
IMessageHandler iMessageHandler = getMessageHandler(messageClass);
AbstractMessageHandler handler = (AbstractMessageHandler) iMessageHandler;
handler.init();
Method[] methods = messageClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MessageCommandAnnotation.class)) {
MessageCommandAnnotation messageCommandAnnotation = (MessageCommandAnnotation) method
.getAnnotation(MessageCommandAnnotation.class);
if (messageCommandAnnotation != null) {
addHandler(messageCommandAnnotation.command(), iMessageHandler);
}
}
}
}
}
}
#location 22
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
Configuration cfg = facade.getConfiguration();
Collection<PluginConfig> installedPlugins = null;
if(cfg != null){
installedPlugins = cfg.getPlugins();
}
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>();
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id = "";
if (!groupId.equals("org.walkmod")) {
id = groupId + ":";
}
id += artifactId.substring("walkmod-".length(),
artifactId.length() - "-plugin".length());
if (Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0))
+ description.substring(1, description.length());
}
if (!description.endsWith(".")) {
description = description + ".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for (int j = 0; j < max; j++) {
String name = nList.item(j).getNodeName();
if (name.equals("url")) {
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
PluginConfig equivalentPluginCfg = new PluginConfigImpl();
equivalentPluginCfg.setGroupId(groupId);
equivalentPluginCfg.setArtifactId(artifactId);
boolean isInstalled = (installedPlugins != null && installedPlugins
.contains(equivalentPluginCfg));
installedList.put(id, isInstalled);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
at = new V2_AsciiTable();
at.addRule();
at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION");
at.addStrongRule();
for (String key : sortedKeys) {
String installed = "";
if (installedList.get(key)) {
installed = "*";
}
at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key));
}
at.addRule();
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void execute() {
if (help) {
command.usage("init");
} else {
try {
WalkModFacade facade = new WalkModFacade(OptionsBuilder.options());
Configuration cfg = facade.getConfiguration();
Collection<PluginConfig> installedPlugins = cfg.getPlugins();
URL searchURL = new URL(MVN_SEARCH_URL);
InputStream is = null;
Map<String, Boolean> installedList = new LinkedHashMap<String, Boolean>();
Map<String, String> pluginsList = new LinkedHashMap<String, String>();
Map<String, String> pluginsURLs = new LinkedHashMap<String, String>();
try {
is = searchURL.openStream();
String content = readInputStreamAsString(is);
DefaultJSONParser parser = new DefaultJSONParser(content);
JSONObject object = parser.parseObject();
parser.close();
JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs");
for (int i = 0; i < artifactList.size(); i++) {
JSONObject artifact = artifactList.getJSONObject(i);
String artifactId = artifact.getString("a");
if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) {
String groupId = artifact.getString("g");
String latestVersion = artifact.getString("latestVersion");
String pom = artifactId + "-" + latestVersion + ".pom";
String directory = groupId.replaceAll("\\.", "/");
URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/"
+ latestVersion + "/" + pom);
InputStream projectIs = artifactDetailsURL.openStream();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(projectIs);
NodeList nList = doc.getElementsByTagName("description");
String description = "unavailable description";
if (nList.getLength() == 1) {
description = nList.item(0).getTextContent();
}
String id = "";
if (!groupId.equals("org.walkmod")) {
id = groupId + ":";
}
id += artifactId.substring("walkmod-".length(),
artifactId.length() - "-plugin".length());
if (Character.isLowerCase(description.charAt(0))) {
description = Character.toUpperCase(description.charAt(0))
+ description.substring(1, description.length());
}
if (!description.endsWith(".")) {
description = description + ".";
}
pluginsList.put(id, description);
nList = doc.getChildNodes().item(0).getChildNodes();
int max = nList.getLength();
String url = "unavailable url";
for (int j = 0; j < max; j++) {
String name = nList.item(j).getNodeName();
if (name.equals("url")) {
url = nList.item(j).getTextContent();
j = max;
}
}
pluginsURLs.put(id, url);
PluginConfig equivalentPluginCfg = new PluginConfigImpl();
equivalentPluginCfg.setGroupId(groupId);
equivalentPluginCfg.setArtifactId(artifactId);
boolean isInstalled = (installedPlugins != null && installedPlugins
.contains(equivalentPluginCfg));
installedList.put(id, isInstalled);
} finally {
projectIs.close();
}
}
}
} finally {
is.close();
}
Set<String> keys = pluginsList.keySet();
List<String> sortedKeys = new LinkedList<String>(keys);
Collections.sort(sortedKeys);
at = new V2_AsciiTable();
at.addRule();
at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION");
at.addStrongRule();
for (String key : sortedKeys) {
String installed = "";
if (installedList.get(key)) {
installed = "*";
}
at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key));
}
at.addRule();
} catch (Exception e) {
throw new WalkModException("Invalid plugins URL", e);
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE |
#fixed code
private void setTotalAndPreUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseLong(getAttributeValue(startEl, "total"));
event.setTotal(toKiloBytes(total));
event.setPreUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free"))));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void setTotalAndPreUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseInt(getAttributeValue(startEl, "total"));
event.setTotal(toKiloBytes(total));
event.setPreUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free"))));
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
private void setPostUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseLong(getAttributeValue(startEl, "total"));
event.setPostUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free"))));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void setPostUsed(GCEvent event, StartElement startEl) {
long total = NumberParser.parseInt(getAttributeValue(startEl, "total"));
event.setPostUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free"))));
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public void run() {
// First, analyze the torrent's local data.
try {
this.torrent.init();
} catch (ClosedByInterruptException cbie) {
logger.warn("Client was interrupted during initialization. " +
"Aborting right away.");
this.setState(ClientState.ERROR);
return;
} catch (IOException ioe) {
logger.error("Could not initialize torrent file data!", ioe);
this.setState(ClientState.ERROR);
return;
}
// Initial completion test
if (this.torrent.isComplete()) {
this.seed();
} else {
this.setState(ClientState.SHARING);
}
this.announce.start();
this.service.start();
int optimisticIterations = 0;
int rateComputationIterations = 0;
while (!this.stop) {
optimisticIterations =
(optimisticIterations == 0 ?
Client.OPTIMISTIC_UNCHOKE_ITERATIONS :
optimisticIterations - 1);
rateComputationIterations =
(rateComputationIterations == 0 ?
Client.RATE_COMPUTATION_ITERATIONS :
rateComputationIterations - 1);
try {
this.unchokePeers(optimisticIterations == 0);
this.info();
if (rateComputationIterations == 0) {
this.resetPeerRates();
}
} catch (Exception e) {
logger.error("An exception occurred during the BitTorrent " +
"client main loop execution!", e);
}
try {
Thread.sleep(Client.UNCHOKING_FREQUENCY*1000);
} catch (InterruptedException ie) {
logger.trace("BitTorrent main loop interrupted.");
}
}
logger.debug("Stopping BitTorrent client connection service " +
"and announce threads...");
this.service.stop();
this.announce.stop();
// Close all peer connections
logger.debug("Closing all remaining peer connections...");
for (SharingPeer peer : this.connected.values()) {
peer.unbind(true);
}
this.torrent.close();
// Determine final state
if (this.torrent.isComplete()) {
this.setState(ClientState.DONE);
} else {
this.setState(ClientState.ERROR);
}
logger.info("BitTorrent client signing off.");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void run() {
// First, analyze the torrent's local data.
try {
this.torrent.init();
} catch (ClosedByInterruptException cbie) {
logger.warn("Client was interrupted during initialization. " +
"Aborting right away.");
this.setState(ClientState.ERROR);
return;
} catch (IOException ioe) {
logger.error("Could not initialize torrent file data!", ioe);
this.setState(ClientState.ERROR);
return;
}
// Initial completion test
if (this.torrent.isComplete()) {
this.seed();
} else {
this.setState(ClientState.SHARING);
}
this.announce.start();
this.service.start();
int optimisticIterations = 0;
int rateComputationIterations = 0;
while (!this.stop) {
optimisticIterations =
(optimisticIterations == 0 ?
Client.OPTIMISTIC_UNCHOKE_ITERATIONS :
optimisticIterations - 1);
rateComputationIterations =
(rateComputationIterations == 0 ?
Client.RATE_COMPUTATION_ITERATIONS :
rateComputationIterations - 1);
try {
this.unchokePeers(optimisticIterations == 0);
this.info();
if (rateComputationIterations == 0) {
this.resetPeerRates();
}
} catch (Exception e) {
logger.error("An exception occurred during the BitTorrent " +
"client main loop execution!", e);
}
try {
Thread.sleep(Client.UNCHOKING_FREQUENCY*1000);
} catch (InterruptedException ie) {
logger.trace("BitTorrent main loop interrupted.");
}
}
logger.debug("Stopping BitTorrent client connection service " +
"and announce threads...");
this.service.stop();
this.announce.stop();
// Close all peer connections
logger.debug("Closing all remaining peer connections...");
for (SharingPeer peer : this.connected.values()) {
peer.unbind(true);
}
// Determine final state
if (this.torrent.isComplete()) {
this.setState(ClientState.DONE);
} else {
this.setState(ClientState.ERROR);
}
logger.info("BitTorrent client signing off.");
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded(),
this.torrent.getDownloaded(),
this.torrent.getLeft()
});
try {
State state = State.CONNECT_REQUEST;
int tries = 0;
while (tries <= UDP_MAX_TRIES) {
if (this.lastConnectionTime != null &&
new Date().before(this.lastConnectionTime)) {
state = State.ANNOUNCE_REQUEST;
}
tries++;
}
ByteBuffer data = null;
UDPTrackerMessage.UDPTrackerResponseMessage message =
UDPTrackerMessage.UDPTrackerResponseMessage.parse(data);
this.handleTrackerResponse(message, inhibitEvents);
} catch (MessageValidationException mve) {
logger.error("Tracker message violates expected protocol: {}!",
mve.getMessage(), mve);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void announce(AnnounceRequestMessage.RequestEvent event,
boolean inhibitEvents) throws AnnounceException {
logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
new Object[] {
this.formatAnnounceEvent(event),
this.torrent.getUploaded(),
this.torrent.getDownloaded(),
this.torrent.getLeft()
});
try {
ByteBuffer data = null;
UDPTrackerMessage.UDPTrackerResponseMessage message =
UDPTrackerMessage.UDPTrackerResponseMessage.parse(data);
this.handleTrackerResponse(message, inhibitEvents);
} catch (MessageValidationException mve) {
logger.error("Tracker message violates expected protocol: {}!",
mve.getMessage(), mve);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE |
#fixed code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to {}...", peer);
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) {
// Could not connect to peer, abort
logger.warn("Could not connect to {}: {}", peer, ioe.getMessage());
return false;
}
try {
this.sendHandshake(socket);
Handshake hs = this.validateHandshake(socket,
(peer.hasPeerId() ? peer.getPeerId().array() : null));
this.fireNewPeerConnection(socket, hs.getPeerId());
return true;
} catch (ParseException pe) {
logger.info("Invalid handshake from {}: {}",
this.socketRepr(socket), pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: {}", ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean connect(SharingPeer peer) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(peer.getIp(),
peer.getPort());
logger.info("Connecting to " + peer + "...");
try {
socket.connect(address, 3*1000);
} catch (IOException ioe) {
// Could not connect to peer, abort
logger.warn("Could not connect to " + peer + ": " +
ioe.getMessage());
return false;
}
try {
this.sendHandshake(socket);
Handshake hs = this.validateHandshake(socket,
(peer.hasPeerId() ? peer.getPeerId().array() : null));
this.fireNewPeerConnection(socket, hs.getPeerId());
return true;
} catch (ParseException pe) {
logger.info("Invalid handshake from " + this.socketRepr(socket) +
": " + pe.getMessage());
try { socket.close(); } catch (IOException e) { }
} catch (IOException ioe) {
logger.info("An error occured while reading an incoming " +
"handshake: " + ioe.getMessage());
try {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
return false;
}
#location 30
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public synchronized void handleMessage(PeerMessage msg) {
// logger.trace("Received msg {} from {}", msg.getType(), this);
switch (msg.getType()) {
case KEEP_ALIVE:
// Nothing to do, we're keeping the connection open anyways.
break;
case CHOKE:
this.choked = true;
this.firePeerChoked();
this.cancelPendingRequests();
break;
case UNCHOKE:
this.choked = false;
logger.trace("Peer {} is now accepting requests.", this);
this.firePeerReady();
break;
case INTERESTED:
this.interested = true;
break;
case NOT_INTERESTED:
this.interested = false;
break;
case HAVE:
// Record this peer has the given piece
PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg;
Piece havePiece = this.torrent.getPiece(have.getPieceIndex());
synchronized (this.availablePiecesLock) {
this.availablePieces.set(havePiece.getIndex());
logger.trace("Peer {} now has {} [{}/{}].",
new Object[]{
this,
havePiece,
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.firePieceAvailabity(havePiece);
break;
case BITFIELD:
// Augment the hasPiece bit field from this BITFIELD message
PeerMessage.BitfieldMessage bitfield =
(PeerMessage.BitfieldMessage) msg;
synchronized (this.availablePiecesLock) {
this.availablePieces.or(bitfield.getBitfield());
logger.trace("Recorded bitfield from {} with {} " +
"pieces(s) [{}/{}].",
new Object[]{
this,
bitfield.getBitfield().cardinality(),
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.fireBitfieldAvailabity();
break;
case REQUEST:
PeerMessage.RequestMessage request =
(PeerMessage.RequestMessage) msg;
logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
request.getPiece(),
request.getLength(),
request.getOffset(),
this
});
Piece rp = this.torrent.getPiece(request.getPiece());
// If we are choking from this peer and it still sends us
// requests, it is a violation of the BitTorrent protocol.
// Similarly, if the peer requests a piece we don't have, it
// is a violation of the BitTorrent protocol. In these
// situation, terminate the connection.
if (this.isChoking() || !rp.isValid()) {
logger.warn("Peer {} violated protocol, terminating exchange.", this);
this.unbind(true);
break;
}
if (request.getLength() >
PeerMessage.RequestMessage.MAX_REQUEST_SIZE) {
logger.warn("Peer {} requested a block too big, " +
"terminating exchange.", this);
this.unbind(true);
break;
}
// At this point we agree to send the requested piece block to
// the remote peer, so let's queue a message with that block
try {
ByteBuffer block = rp.read(request.getOffset(),
request.getLength());
this.send(PeerMessage.PieceMessage.craft(request.getPiece(),
request.getOffset(), block));
this.upload.add(block.capacity());
if (request.getOffset() + request.getLength() == rp.size()) {
this.firePieceSent(rp);
}
} catch (IOException ioe) {
logger.error("error", ioe);
this.fireIOException(new IOException(
"Error while sending piece block request!", ioe));
}
break;
case PIECE:
// Record the incoming piece block.
// Should we keep track of the requested pieces and act when we
// get a piece we didn't ask for, or should we just stay
// greedy?
PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg;
Piece p = this.torrent.getPiece(piece.getPiece());
logger.trace("Got piece for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
p.getIndex(),
p.size(),
piece.getOffset(),
this
});
// Remove the corresponding request from the request queue to
// make room for next block requests.
this.removeBlockRequest(piece.getPiece(), piece.getOffset());
this.download.add(piece.getBlock().capacity());
try {
synchronized (p) {
if (p.isValid()) {
this.cancelPendingRequests(p);
this.firePeerReady();
logger.debug("Discarding block for already completed " + p);
break;
}
//TODO add proper catch for IOException
p.record(piece.getBlock(), piece.getOffset());
// If the block offset equals the piece size and the block
// length is 0, it means the piece has been entirely
// downloaded. In this case, we have nothing to save, but
// we should validate the piece.
if (getRemainingRequestedPieces(p).size() == 0) {
p.finish();
p.validate(torrent, p);
this.firePieceCompleted(p);
myRequestedPieces.remove(p);
this.firePeerReady();
} else {
if (piece.getOffset() + piece.getBlock().capacity()
== p.size()) { // final request reached
for (PeerMessage.RequestMessage requestMessage : getRemainingRequestedPieces(p)) {
send(requestMessage);
}
} else {
this.requestNextBlocksForPiece(p);
}
}
}
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
this.fireIOException(new IOException(
"Error while storing received piece block!", ioe));
break;
}
break;
case CANCEL:
// No need to support
break;
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public synchronized void handleMessage(PeerMessage msg) {
// logger.trace("Received msg {} from {}", msg.getType(), this);
switch (msg.getType()) {
case KEEP_ALIVE:
// Nothing to do, we're keeping the connection open anyways.
break;
case CHOKE:
this.choked = true;
this.firePeerChoked();
this.cancelPendingRequests();
break;
case UNCHOKE:
this.choked = false;
logger.trace("Peer {} is now accepting requests.", this);
this.firePeerReady();
break;
case INTERESTED:
this.interested = true;
break;
case NOT_INTERESTED:
this.interested = false;
break;
case HAVE:
// Record this peer has the given piece
PeerMessage.HaveMessage have = (PeerMessage.HaveMessage) msg;
Piece havePiece = this.torrent.getPiece(have.getPieceIndex());
synchronized (this.availablePiecesLock) {
this.availablePieces.set(havePiece.getIndex());
logger.trace("Peer {} now has {} [{}/{}].",
new Object[]{
this,
havePiece,
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.firePieceAvailabity(havePiece);
break;
case BITFIELD:
// Augment the hasPiece bit field from this BITFIELD message
PeerMessage.BitfieldMessage bitfield =
(PeerMessage.BitfieldMessage) msg;
synchronized (this.availablePiecesLock) {
this.availablePieces.or(bitfield.getBitfield());
logger.trace("Recorded bitfield from {} with {} " +
"pieces(s) [{}/{}].",
new Object[]{
this,
bitfield.getBitfield().cardinality(),
this.availablePieces.cardinality(),
this.torrent.getPieceCount()
});
}
this.fireBitfieldAvailabity();
break;
case REQUEST:
PeerMessage.RequestMessage request =
(PeerMessage.RequestMessage) msg;
logger.trace("Got request message for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
request.getPiece(),
request.getLength(),
request.getOffset(),
this
});
Piece rp = this.torrent.getPiece(request.getPiece());
// If we are choking from this peer and it still sends us
// requests, it is a violation of the BitTorrent protocol.
// Similarly, if the peer requests a piece we don't have, it
// is a violation of the BitTorrent protocol. In these
// situation, terminate the connection.
if (this.isChoking() || !rp.isValid()) {
logger.warn("Peer {} violated protocol, terminating exchange.", this);
this.unbind(true);
break;
}
if (request.getLength() >
PeerMessage.RequestMessage.MAX_REQUEST_SIZE) {
logger.warn("Peer {} requested a block too big, " +
"terminating exchange.", this);
this.unbind(true);
break;
}
// At this point we agree to send the requested piece block to
// the remote peer, so let's queue a message with that block
try {
ByteBuffer block = rp.read(request.getOffset(),
request.getLength());
this.send(PeerMessage.PieceMessage.craft(request.getPiece(),
request.getOffset(), block));
this.upload.add(block.capacity());
if (request.getOffset() + request.getLength() == rp.size()) {
this.firePieceSent(rp);
}
} catch (IOException ioe) {
logger.error("error", ioe);
this.fireIOException(new IOException(
"Error while sending piece block request!", ioe));
}
break;
case PIECE:
// Record the incoming piece block.
// Should we keep track of the requested pieces and act when we
// get a piece we didn't ask for, or should we just stay
// greedy?
PeerMessage.PieceMessage piece = (PeerMessage.PieceMessage) msg;
Piece p = this.torrent.getPiece(piece.getPiece());
logger.trace("Got piece for {} ({} {}@{}) from {}", new Object[]{
Arrays.toString(torrent.getFilenames().toArray()),
p.getIndex(),
p.size(),
piece.getOffset(),
this
});
// Remove the corresponding request from the request queue to
// make room for next block requests.
this.removeBlockRequest(piece);
this.download.add(piece.getBlock().capacity());
try {
synchronized (p) {
if (p.isValid()) {
this.requestedPiece = null;
this.cancelPendingRequests();
this.firePeerReady();
logger.debug("Discarding block for already completed " + p);
break;
}
//TODO add proper catch for IOException
p.record(piece.getBlock(), piece.getOffset());
// If the block offset equals the piece size and the block
// length is 0, it means the piece has been entirely
// downloaded. In this case, we have nothing to save, but
// we should validate the piece.
if (requests==null || requests.size() == 0) {
p.finish();
p.validate(torrent, p);
this.firePieceCompleted(p);
this.requestedPiece = null;
this.firePeerReady();
} else {
if (piece.getOffset() + piece.getBlock().capacity()
== p.size()) { // final request reached
for (PeerMessage.RequestMessage requestMessage : requests) {
send(requestMessage);
}
} else {
this.requestNextBlocks();
}
}
}
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
this.fireIOException(new IOException(
"Error while storing received piece block!", ioe));
break;
}
break;
case CANCEL:
// No need to support
break;
}
}
#location 163
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public BitSet getCompletedPieces() {
if (!this.isInitialized()) {
throw new IllegalStateException("Torrent not yet initialized!");
}
synchronized (this.completedPieces) {
return (BitSet)this.completedPieces.clone();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public BitSet getCompletedPieces() {
synchronized (this.completedPieces) {
return (BitSet)this.completedPieces.clone();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) {
try {
synchronized (piece) {
if (piece.isValid()) return;
piece.validate(torrent, piece);
if (piece.isValid()) {
piece.finish();
// Send a HAVE message to all connected peers, which don't have the piece
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash) &&
!remote.getAvailablePieces().get(piece.getIndex()))
remote.send(have);
}
final boolean isTorrentComplete;
synchronized (torrent) {
torrent.removeValidationFuture(piece);
torrent.notifyPieceDownloaded(piece, peer);
boolean isCurrentPeerSeeder = peer.getAvailablePieces().cardinality() == torrent.getPieceCount();
//if it's seeder we will send not interested message when we download full file
if (!isCurrentPeerSeeder) {
if (torrent.isAllPiecesOfPeerCompletedAndValidated(peer)) {
peer.notInteresting();
}
}
isTorrentComplete = torrent.isComplete();
if (isTorrentComplete) {
logger.debug("Download of {} complete.", torrent.getDirectoryName());
torrent.finish();
}
}
if (isTorrentComplete) {
LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(torrentHash);
if (announceableTorrent == null) return;
AnnounceableInformation announceableInformation = announceableTorrent.createAnnounceableInformation();
try {
announce.getCurrentTrackerClient(announceableInformation)
.announceAllInterfaces(COMPLETED, true, announceableInformation);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
for (SharingPeer remote : getPeersForTorrent(torrentHash)) {
remote.notInteresting();
}
}
} else {
torrent.markUncompleted(piece);
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
}
} catch (Throwable e) {
torrent.markUncompleted(piece);
logger.warn("unhandled exception in piece {} validation task", e);
}
torrent.handlePeerReady(peer);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) {
try {
synchronized (piece) {
if (piece.isValid()) return;
piece.validate(torrent, piece);
if (piece.isValid()) {
piece.finish();
// Send a HAVE message to all connected peers, which don't have the piece
PeerMessage have = PeerMessage.HaveMessage.craft(piece.getIndex());
for (SharingPeer remote : getConnectedPeers()) {
if (remote.getTorrent().getHexInfoHash().equals(torrentHash) &&
!remote.getAvailablePieces().get(piece.getIndex()))
remote.send(have);
}
final boolean isTorrentComplete;
synchronized (torrent) {
torrent.removeValidationFuture(piece);
torrent.notifyPieceDownloaded(piece, peer);
boolean isCurrentPeerSeeder = peer.getAvailablePieces().cardinality() == torrent.getPieceCount();
//if it's seeder we will send not interested message when we download full file
if (!isCurrentPeerSeeder) {
if (torrent.isAllPiecesOfPeerCompletedAndValidated(peer)) {
peer.notInteresting();
}
}
isTorrentComplete = torrent.isComplete();
if (isTorrentComplete) {
logger.debug("Download of {} complete.", torrent.getDirectoryName());
torrent.finish();
}
}
if (isTorrentComplete) {
LoadedTorrent announceableTorrent = torrentsStorage.getLoadedTorrent(torrentHash);
if (announceableTorrent == null) return;
AnnounceableInformation announceableInformation = announceableTorrent.createAnnounceableInformation();
try {
announce.getCurrentTrackerClient(announceableInformation)
.announceAllInterfaces(COMPLETED, true, announceableInformation);
} catch (AnnounceException e) {
logger.debug("unable to announce torrent {} on tracker {}", torrent, torrent.getAnnounce());
}
for (SharingPeer remote : getPeersForTorrent(torrentHash)) {
remote.notInteresting();
}
}
} else {
torrent.markUncompleted(piece);
logger.info("Downloaded piece #{} from {} was not valid ;-(. Trying another peer", piece.getIndex(), peer);
peer.getPoorlyAvailablePieces().set(piece.getIndex());
}
}
} catch (Throwable e) {
torrent.markUncompleted(piece);
logger.warn("unhandled exception in piece {} validation task", e);
}
}
#location 51
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
int serverPort = ConnectionManager.PORT_RANGE_START;
Socket socket = new Socket();
while (serverPort < ConnectionManager.PORT_RANGE_END) {
try {
socket.connect(new InetSocketAddress("127.0.0.1", serverPort));
} catch (ConnectException ignored) {}
serverPort++;
}
if (!socket.isConnected()) {
fail("can not connect to server channel of connection manager");
}
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", serverPort);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void canAcceptAndReadData() throws IOException, InterruptedException {
final AtomicInteger acceptCount = new AtomicInteger();
final AtomicInteger readCount = new AtomicInteger();
final AtomicInteger connectCount = new AtomicInteger();
final AtomicInteger lastReadBytesCount = new AtomicInteger();
final ByteBuffer byteBuffer = ByteBuffer.allocate(10);
final Semaphore semaphore = new Semaphore(0);
this.channelListener = new ChannelListener() {
@Override
public void onNewDataAvailable(SocketChannel socketChannel) throws IOException {
readCount.incrementAndGet();
lastReadBytesCount.set(socketChannel.read(byteBuffer));
if (lastReadBytesCount.get() == -1) {
socketChannel.close();
}
semaphore.release();
}
@Override
public void onConnectionAccept(SocketChannel socketChannel) throws IOException {
acceptCount.incrementAndGet();
semaphore.release();
}
@Override
public void onConnected(SocketChannel socketChannel, ConnectTask connectTask) {
connectCount.incrementAndGet();
semaphore.release();
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = executorService.submit(myConnectionManager);
assertEquals(acceptCount.get(), 0);
assertEquals(readCount.get(), 0);
Socket socket = new Socket("127.0.0.1", ConnectionManager.PORT_RANGE_START);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socket.isConnected());
assertEquals(acceptCount.get(), 1);
assertEquals(readCount.get(), 0);
Socket socketSecond = new Socket("127.0.0.1", ConnectionManager.PORT_RANGE_START);
tryAcquireOrFail(semaphore);//wait until connection is accepted
assertTrue(socketSecond.isConnected());
assertEquals(acceptCount.get(), 2);
assertEquals(readCount.get(), 0);
socketSecond.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 1);
assertEquals(acceptCount.get(), 2);
assertEquals(lastReadBytesCount.get(), -1);
byteBuffer.rewind();
assertEquals(byteBuffer.get(), 0);
byteBuffer.rewind();
String writeStr = "abc";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(writeStr.getBytes());
tryAcquireOrFail(semaphore);//wait until read bytes
assertEquals(readCount.get(), 2);
assertEquals(lastReadBytesCount.get(), 3);
byte[] expected = new byte[byteBuffer.capacity()];
System.arraycopy(writeStr.getBytes(), 0, expected, 0, writeStr.length());
assertEquals(byteBuffer.array(), expected);
outputStream.close();
socket.close();
tryAcquireOrFail(semaphore);//wait read that connection is closed
assertEquals(readCount.get(), 3);
int otherPeerPort = 7575;
ServerSocket ss = new ServerSocket(otherPeerPort);
assertEquals(connectCount.get(), 0);
myConnectionManager.connect(new ConnectTask("127.0.0.1", otherPeerPort, new TorrentHash() {
@Override
public byte[] getInfoHash() {
return new byte[0];
}
@Override
public String getHexInfoHash() {
return null;
}
}), 1, TimeUnit.SECONDS);
ss.accept();
tryAcquireOrFail(semaphore);
assertEquals(connectCount.get(), 1);
executorService.shutdownNow();
boolean executorShutdownCorrectly = executorService.awaitTermination(10, TimeUnit.SECONDS);
assertTrue(executorShutdownCorrectly);
}
#location 66
#vulnerability type NULL_DEREFERENCE |
#fixed code
public BitSet getAvailablePieces() {
if (!this.isInitialized()) {
throw new IllegalStateException("Torrent not yet initialized!");
}
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (piece.available()) {
availablePieces.set(piece.getIndex());
}
}
}
return availablePieces;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public BitSet getAvailablePieces() {
BitSet availablePieces = new BitSet(this.pieces.length);
synchronized (this.pieces) {
for (Piece piece : this.pieces) {
if (piece.available()) {
availablePieces.set(piece.getIndex());
}
}
}
return availablePieces;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
Client seeder = createClient("seeder");
seeder.start(InetAddress.getLocalHost());
Client leech = null;
try {
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
List<File> filesToShare = new ArrayList<File>();
for (int i = 0; i < numFiles; i++) {
File tempFile = tempFiles.createTempFile(513 * 1024);
File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
saveTorrent(torrent, torrentFile);
filesToShare.add(srcFile);
names.add(srcFile.getName());
}
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent());
}
leech = createClient("leecher");
leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null, new SelectorFactoryImpl());
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
}
new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
final Set<String> strings = listFileNames(downloadDir);
int count = 0;
final List<String> partItems = new ArrayList<String>();
for (String s : strings) {
if (s.endsWith(".part")) {
count++;
partItems.add(s);
}
}
if (count < 5) {
System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray()));
}
return strings.containsAll(names);
}
};
assertEquals(listFileNames(downloadDir), names);
} finally {
leech.stop();
seeder.stop();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
Client seeder = createClient("seeder");
seeder.start(InetAddress.getLocalHost());
Client leech = null;
try {
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
List<File> filesToShare = new ArrayList<File>();
for (int i = 0; i < numFiles; i++) {
File tempFile = tempFiles.createTempFile(513 * 1024);
File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = TorrentCreator.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
saveTorrent(torrent, torrentFile);
filesToShare.add(srcFile);
names.add(srcFile.getName());
}
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent());
}
leech = createClient("leecher");
leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null);
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
}
new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
final Set<String> strings = listFileNames(downloadDir);
int count = 0;
final List<String> partItems = new ArrayList<String>();
for (String s : strings) {
if (s.endsWith(".part")) {
count++;
partItems.add(s);
}
}
if (count < 5) {
System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray()));
}
return strings.containsAll(names);
}
};
assertEquals(listFileNames(downloadDir), names);
} finally {
leech.stop();
seeder.stop();
}
}
#location 35
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void downloadUninterruptibly(final String dotTorrentPath,
final String downloadDirPath,
final long idleTimeoutSec,
final int minSeedersCount,
final AtomicBoolean isInterrupted,
final long maxTimeForConnectMs,
DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException {
String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true);
final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash);
if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found");
SharedTorrent torrent = new TorrentLoaderImpl(torrentsStorage).loadTorrent(announceableTorrent);
long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
torrent.addDownloadProgressListener(listener);
final long startDownloadAt = System.currentTimeMillis();
long currentLeft = torrent.getLeft();
while (torrent.getClientState() != ClientState.SEEDING &&
torrent.getClientState() != ClientState.ERROR &&
(torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) &&
(System.currentTimeMillis() <= maxIdleTime)) {
if (Thread.currentThread().isInterrupted() || isInterrupted.get())
throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted");
if (currentLeft > torrent.getLeft()) {
currentLeft = torrent.getLeft();
maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
}
if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) {
if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) {
break;
}
}
Thread.sleep(100);
}
if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) {
removeAndDeleteTorrent(hash, torrent);
final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash);
int connectedPeersForTorrent = peersForTorrent.size();
for (SharingPeer peer : peersForTorrent) {
peer.unbind(true);
}
final String errorMsg;
if (System.currentTimeMillis() > maxIdleTime) {
int completedPieces = torrent.getCompletedPieces().cardinality();
int totalPieces = torrent.getPieceCount();
errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d"
, idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent);
} else if (connectedPeersForTorrent < minSeedersCount) {
errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent);
} else if (torrent.getClientState() == ClientState.ERROR) {
errorMsg = "Torrent state is ERROR";
} else {
errorMsg = "Unknown error";
}
throw new IOException("Unable to download torrent completely - " + errorMsg);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void downloadUninterruptibly(final String dotTorrentPath,
final String downloadDirPath,
final long idleTimeoutSec,
final int minSeedersCount,
final AtomicBoolean isInterrupted,
final long maxTimeForConnectMs,
DownloadProgressListener listener) throws IOException, InterruptedException, NoSuchAlgorithmException {
String hash = addTorrent(dotTorrentPath, downloadDirPath, false, true);
final AnnounceableFileTorrent announceableTorrent = torrentsStorage.getAnnounceableTorrent(hash);
if (announceableTorrent == null) throw new IOException("Unable to download torrent completely - announceable torrent is not found");
final SharedTorrent torrent = SharedTorrent.fromFile(new File(dotTorrentPath),
new File(downloadDirPath),
false,
false,
true,
announceableTorrent);
torrentsStorage.putIfAbsentActiveTorrent(torrent.getHexInfoHash(), torrent);
long maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
torrent.addDownloadProgressListener(listener);
final long startDownloadAt = System.currentTimeMillis();
long currentLeft = torrent.getLeft();
while (torrent.getClientState() != ClientState.SEEDING &&
torrent.getClientState() != ClientState.ERROR &&
(torrent.getSeedersCount() >= minSeedersCount || torrent.getLastAnnounceTime() < 0) &&
(System.currentTimeMillis() <= maxIdleTime)) {
if (Thread.currentThread().isInterrupted() || isInterrupted.get())
throw new InterruptedException("Download of " + torrent.getDirectoryName() + " was interrupted");
if (currentLeft > torrent.getLeft()) {
currentLeft = torrent.getLeft();
maxIdleTime = System.currentTimeMillis() + idleTimeoutSec * 1000;
}
if (System.currentTimeMillis() - startDownloadAt > maxTimeForConnectMs) {
if (getPeersForTorrent(torrent.getHexInfoHash()).size() < minSeedersCount) {
break;
}
}
Thread.sleep(100);
}
if (!(torrent.isFinished() && torrent.getClientState() == ClientState.SEEDING)) {
removeAndDeleteTorrent(hash, torrent);
final List<SharingPeer> peersForTorrent = getPeersForTorrent(hash);
int connectedPeersForTorrent = peersForTorrent.size();
for (SharingPeer peer : peersForTorrent) {
peer.unbind(true);
}
final String errorMsg;
if (System.currentTimeMillis() > maxIdleTime) {
int completedPieces = torrent.getCompletedPieces().cardinality();
int totalPieces = torrent.getPieceCount();
errorMsg = String.format("No pieces has been downloaded in %d seconds. Downloaded pieces %d/%d, connected peers %d"
, idleTimeoutSec, completedPieces, totalPieces, connectedPeersForTorrent);
} else if (connectedPeersForTorrent < minSeedersCount) {
errorMsg = String.format("Not enough seeders. Required %d, found %d", minSeedersCount, connectedPeersForTorrent);
} else if (torrent.getClientState() == ClientState.ERROR) {
errorMsg = "Torrent state is ERROR";
} else {
errorMsg = "Unknown error";
}
throw new IOException("Unable to download torrent completely - " + errorMsg);
}
}
#location 59
#vulnerability type RESOURCE_LEAK |
#fixed code
public void send(PeerMessage message) throws IllegalStateException {
logger.trace("Sending msg {} to {}", message.getType(), this);
if (this.isConnected()) {
ByteBuffer data = message.getData();
data.rewind();
connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() {
@Override
public void onWriteFailed(String message, Throwable e) {
logger.debug(message, e);
unbind(true);
}
@Override
public void onWriteDone() {
}
}), 1, TimeUnit.SECONDS);
} else {
logger.info("Attempting to send a message to non-connected peer {}!", this);
unbind(true);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void send(PeerMessage message) throws IllegalStateException {
logger.trace("Sending msg {} to {}", message.getType(), this);
if (this.isConnected()) {
ByteBuffer data = message.getData();
data.rewind();
boolean writeTaskAdded = connectionManager.offerWrite(new WriteTask(socketChannel, data, new WriteListener() {
@Override
public void onWriteFailed(String message, Throwable e) {
logger.debug(message, e);
unbind(true);
}
@Override
public void onWriteDone() {
}
}), 1, TimeUnit.SECONDS);
if (!writeTaskAdded) {
unbind(true);
}
} else {
logger.info("Attempting to send a message to non-connected peer {}!", this);
unbind(true);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public T blpopObject(int timeout, String key, Class clazz) {
this.setSchema(clazz);
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
List<byte[]> bytes = jedis.blpop(timeout, key.getBytes());
if (bytes == null || bytes.size() == 0) {
return null;
}
return getBytes(bytes.get(1));
} finally {
jedis.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public T blpopObject(int timeout, String key, Class clazz) {
this.setSchema(clazz);
Jedis jedis = null;
try {
List<byte[]> bytes = jedis.blpop(timeout, key.getBytes());
if (bytes == null || bytes.size() == 0) {
return null;
}
return getBytes(bytes.get(1));
} finally {
jedis.close();
}
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testCustomUserAgent() throws JSONException, UnirestException {
HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON)
.header("user-agent", "hello-world")
.asJson();
RequestCapture json = parse(response);
json.assertHeader("User-Agent", "hello-world");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testCustomUserAgent() throws JSONException, UnirestException {
HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson();
assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent"));
GetRequest getRequest = Unirest.get("http");
for (Object current : Arrays.asList(0, 1, 2)) {
getRequest.queryString("name", current);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testDelete() throws JSONException, UnirestException {
HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE).asJson();
assertEquals(200, response.getStatus());
response = Unirest.delete(MockServer.DELETE)
.field("name", "mark")
.field("foo","bar")
.asJson();
RequestCapture parse = parse(response);
parse.assertParam("name", "mark");
parse.assertParam("foo", "bar");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testDelete() throws JSONException, UnirestException {
HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson();
assertEquals(200, response.getStatus());
response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson();
assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name"));
}
#location 7
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testPostBinaryUTF8() throws URISyntaxException {
HttpResponse<JsonNode> response = Unirest.post(MockServer.POST)
.header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType())
.field("param3", "こんにちは")
.field("file", new File(getClass().getResource("/test").toURI()))
.asJson();
FormCapture json = TestUtils.read(response, FormCapture.class);
json.assertQuery("param3", "こんにちは");
json.getFile("test").assertBody("This is a test file");
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testPostBinaryUTF8() throws URISyntaxException {
HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").field("file", new File(getClass().getResource("/test").toURI())).asJson();
assertEquals("This is a test file", response.getBody().getObject().getJSONObject("files").getString("file"));
assertEquals("こんにちは", response.getBody().getObject().getJSONObject("form").getString("param3"));
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException {
FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI()));
MultipartBody request = Unirest.post(HOST + "/post")
.field("name", "Mark")
.field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg");
HttpResponse<JsonNode> jsonResponse = request
.asJson();
assertTrue(jsonResponse.getHeaders().size() > 0);
assertTrue(jsonResponse.getBody().toString().length() > 0);
assertFalse(jsonResponse.getRawBody() == null);
assertEquals(200, jsonResponse.getStatus());
JsonNode json = jsonResponse.getBody();
assertFalse(json.isArray());
JSONObject object = json.getObject();
assertNotNull(object);
assertNotNull(json.getArray());
assertEquals(1, json.getArray().length());
assertNotNull(json.getArray().get(0));
assertNotNull(object.getJSONObject("files"));
assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream"));
assertEquals("Mark", json.getObject().getJSONObject("form").getString("name"));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException {
HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg").asJson();
assertTrue(jsonResponse.getHeaders().size() > 0);
assertTrue(jsonResponse.getBody().toString().length() > 0);
assertFalse(jsonResponse.getRawBody() == null);
assertEquals(200, jsonResponse.getStatus());
JsonNode json = jsonResponse.getBody();
assertFalse(json.isArray());
assertNotNull(json.getObject());
assertNotNull(json.getArray());
assertEquals(1, json.getArray().length());
assertNotNull(json.getArray().get(0));
assertNotNull(json.getObject().getJSONObject("files"));
assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream"));
assertEquals("Mark", json.getObject().getJSONObject("form").getString("name"));
}
#location 3
#vulnerability type RESOURCE_LEAK |
#fixed code
public boolean isStarted() {
try {
lock.lock();
return client.getState() == CuratorFrameworkState.STARTED;
} finally {
lock.unlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean isStarted() {
return client.getState() == CuratorFrameworkState.STARTED;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void testReplication1() throws Exception {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final ChronicleSource source = new ChronicleSource(
new VanillaChronicle(sourceBasePath), 0);
final ChronicleSink sink = new ChronicleSink(
new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort());
try {
final Thread at = new Thread("th-appender") {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
}
appender.close();
} catch(Exception e) {
}
}
};
final Thread tt = new Thread("th-tailer") {
public void run() {
try {
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
long value = 1000000000 + i;
assertTrue(tailer.nextIndex());
long val = tailer.parseLong();
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
tailer.close();
} catch(Exception e) {
}
}
};
at.start();
tt.start();
at.join();
tt.join();
} finally {
sink.close();
sink.clear();
source.close();
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testReplication1() throws IOException {
final int RUNS = 100;
final String sourceBasePath = getVanillaTestPath("-source");
final String sinkBasePath = getVanillaTestPath("-sink");
final ChronicleSource source = new ChronicleSource(new VanillaChronicle(sourceBasePath), 0);
final ChronicleSink sink = new ChronicleSink(new VanillaChronicle(sinkBasePath), "localhost", source.getLocalPort());
try {
final ExcerptAppender appender = source.createAppender();
final ExcerptTailer tailer = sink.createTailer();
for (int i = 0; i < RUNS; i++) {
appender.startExcerpt();
long value = 1000000000 + i;
appender.append(value).append(' ');
appender.finish();
while(!tailer.nextIndex());
long val = tailer.parseLong();
//System.out.println("" + val);
assertEquals("i: " + i, value, val);
assertEquals("i: " + i, 0, tailer.remaining());
tailer.finish();
}
appender.close();
tailer.close();
} finally {
sink.close();
sink.checkCounts(1, 1);
sink.clear();
source.close();
source.checkCounts(1, 1);
source.clear();
assertFalse(new File(sourceBasePath).exists());
assertFalse(new File(sinkBasePath).exists());
}
}
#location 32
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testPricePublishing2() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource)
.source()
.bindAddress(BASE_PORT + 3)
.build();
final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink)
.sink()
.connectAddress("localhost", BASE_PORT + 3)
.build();
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices) {
reader.read();
}
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testPricePublishing2() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 3);
final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 3);
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices) {
reader.read();
}
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
}
#location 15
#vulnerability type RESOURCE_LEAK |
#fixed code
@NotNull
private WireStore acquireStore(final long cycle, final long epoch) {
@NotNull final RollCycle rollCycle = builder.rollCycle();
@NotNull final String cycleFormat = this.dateCache.formatFor(cycle);
@NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX);
try {
final File parentFile = cycleFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
final WireType wireType = builder.wireType();
final MappedBytes mappedBytes = mappedBytes(builder, cycleFile);
//noinspection PointlessBitwiseExpression
if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA
| Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) {
final SingleChronicleQueueStore wireStore = new
SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch);
final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4);
wireType.apply(bytes).getValueOut().typedMarshallable(wireStore);
final long length = bytes.writePosition();
wireStore.install(
length,
true,
cycle,
builder
);
mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large"));
return wireStore;
} else {
long end = System.currentTimeMillis() + TIMEOUT;
while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) {
if (System.currentTimeMillis() > end) {
throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile);
}
Jvm.pause(1);
}
mappedBytes.readPosition(0);
mappedBytes.writePosition(mappedBytes.capacity());
final int len = Wires.lengthOf(mappedBytes.readVolatileInt());
final long length = mappedBytes.readPosition() + len;
mappedBytes.readLimit(length);
//noinspection unchecked
final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable();
wireStore.install(length, false, cycle, builder);
return wireStore;
}
} catch (FileNotFoundException e) {
throw Jvm.rethrow(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@NotNull
private WireStore acquireStore(final long cycle, final long epoch) {
@NotNull final RollCycle rollCycle = builder.rollCycle();
@NotNull final String cycleFormat = this.dateCache.formatFor(cycle);
@NotNull final File cycleFile = new File(this.builder.path(), cycleFormat + SUFFIX);
try {
final File parentFile = cycleFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
final WireType wireType = builder.wireType();
final MappedBytes mappedBytes = mappedBytes(builder, cycleFile);
//noinspection PointlessBitwiseExpression
if (mappedBytes.compareAndSwapInt(0, Wires.NOT_INITIALIZED, Wires.META_DATA
| Wires.NOT_READY | Wires.UNKNOWN_LENGTH)) {
final SingleChronicleQueueStore wireStore = new
SingleChronicleQueueStore(rollCycle, wireType, mappedBytes, epoch);
final Bytes<?> bytes = mappedBytes.bytesForWrite().writePosition(4);
wireType.apply(bytes).getValueOut().typedMarshallable(wireStore);
final long length = bytes.writePosition();
final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, true);
wiredBytes.delegate().install(
wiredBytes.headerLength(),
wiredBytes.headerCreated(),
cycle,
builder
);
mappedBytes.writeOrderedInt(0L, Wires.META_DATA | Wires.toIntU30(bytes.writePosition() - 4, "Delegate too large"));
return wiredBytes.delegate();
} else {
long end = System.currentTimeMillis() + TIMEOUT;
while ((mappedBytes.readVolatileInt(0) & Wires.NOT_READY) == Wires.NOT_READY) {
if (System.currentTimeMillis() > end) {
throw new IllegalStateException("Timed out waiting for the header record to be ready in " + cycleFile);
}
Jvm.pause(1);
}
mappedBytes.readPosition(0);
mappedBytes.writePosition(mappedBytes.capacity());
final int len = Wires.lengthOf(mappedBytes.readVolatileInt());
final long length = mappedBytes.readPosition() + len;
mappedBytes.readLimit(length);
//noinspection unchecked
final WireStore wireStore = wireType.apply(mappedBytes).getValueIn().typedMarshallable();
final WiredBytes<WireStore> wiredBytes = new WiredBytes<>(wireType, mappedBytes, wireStore, length, false);
wiredBytes.delegate().install(
wiredBytes.headerLength(),
wiredBytes.headerCreated(),
cycle,
builder);
return wiredBytes.delegate();
}
} catch (FileNotFoundException e) {
throw Jvm.rethrow(e);
}
}
#location 37
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testPersistedLocalIndexedSink_001() throws Exception {
final int port = BASE_PORT + 201;
final String basePath = getIndexedTestPath();
final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build();
final Chronicle source = ChronicleQueueBuilder.source(chronicle)
.bindAddress("localhost", port)
.build();
final Chronicle sink = ChronicleQueueBuilder.sink(chronicle)
.sharedChronicle(true)
.connectAddress("localhost", port)
.build();
final CountDownLatch latch = new CountDownLatch(5);
final Random random = new Random();
final int items = 100;
try {
Thread appenderThread = new Thread() {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (long i = 1; i <= items; i++) {
if (latch.getCount() > 0) {
latch.countDown();
}
appender.startExcerpt(8);
appender.writeLong(i);
appender.finish();
sleep(10 + random.nextInt(80));
}
appender.close();
} catch (Exception e) {
}
}
};
appenderThread.start();
latch.await();
final ExcerptTailer tailer1 = sink.createTailer().toStart();
for (long i = 1; i <= items; i++) {
assertTrue(tailer1.nextIndex());
assertEquals(i - 1, tailer1.index());
assertEquals(i, tailer1.readLong());
tailer1.finish();
}
tailer1.close();
appenderThread.join();
sink.close();
sink.clear();
} finally {
source.close();
source.clear();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testPersistedLocalIndexedSink_001() throws Exception {
final int port = BASE_PORT + 201;
final String basePath = getIndexedTestPath();
final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build();
final ChronicleSource source = new ChronicleSource(chronicle, port);
final Chronicle sink = localChronicleSink(chronicle, "localhost", port);
final CountDownLatch latch = new CountDownLatch(5);
final Random random = new Random();
final int items = 100;
try {
Thread appenderThread = new Thread() {
public void run() {
try {
final ExcerptAppender appender = source.createAppender();
for (long i = 1; i <= items; i++) {
if (latch.getCount() > 0) {
latch.countDown();
}
appender.startExcerpt(8);
appender.writeLong(i);
appender.finish();
sleep(10 + random.nextInt(80));
}
appender.close();
} catch (Exception e) {
}
}
};
appenderThread.start();
latch.await();
final ExcerptTailer tailer1 = sink.createTailer().toStart();
for (long i = 1; i <= items; i++) {
assertTrue(tailer1.nextIndex());
assertEquals(i - 1, tailer1.index());
assertEquals(i, tailer1.readLong());
tailer1.finish();
}
tailer1.close();
appenderThread.join();
sink.close();
sink.clear();
} finally {
source.close();
source.clear();
}
}
#location 55
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testPricePublishing3() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = ChronicleQueueBuilder.indexed(basePathSource)
.source()
.bindAddress(BASE_PORT + 4)
.build();
final Chronicle sink = ChronicleQueueBuilder.indexed(basePathSink)
.sink()
.connectAddress("localhost", BASE_PORT + 4)
.build();
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices)
reader.read();
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testPricePublishing3() throws IOException, InterruptedException {
final String basePathSource = getIndexedTestPath("-source");
final String basePathSink = getIndexedTestPath("-sink");
final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 4);
final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 4);
final PriceWriter pw = new PriceWriter(source.createAppender());
final AtomicInteger count = new AtomicInteger();
PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() {
@Override
public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) {
count.incrementAndGet();
}
});
pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2);
assertEquals(-1, reader.excerpt.index());
reader.read();
assertEquals(0, reader.excerpt.index());
long start = System.nanoTime();
int prices = 2 * 1000 * 1000;
for (int i = 1; i <= prices; i++) {
pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1);
}
long mid = System.nanoTime();
while (count.get() < prices)
reader.read();
long end = System.nanoTime();
System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n",
(mid - start) / prices / 1e3, (end - mid) / prices / 1e3);
source.close();
sink.close();
assertIndexedClean(basePathSource);
assertIndexedClean(basePathSink);
}
#location 15
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
raftNode.getLock().lock();
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
raftNode.stepDown(request.getTerm());
}
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
raftNode.getLock().unlock();
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
raftNode.getLock().unlock();
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// truncate segment log from index
long lastIndexKept = index - 1;
raftNode.getRaftLog().truncateSuffix(lastIndexKept);
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// apply state machine
for (index = raftNode.getLastAppliedIndex() + 1; index <= raftNode.getCommitIndex(); index++) {
raftNode.getStateMachine().apply(
raftNode.getRaftLog().getEntry(index).getData().toByteArray());
}
}
raftNode.getLock().unlock();
return responseBuilder.build();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) {
Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder();
responseBuilder.setTerm(raftNode.getCurrentTerm());
responseBuilder.setSuccess(false);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (request.getTerm() < raftNode.getCurrentTerm()) {
return responseBuilder.build();
}
if (request.getTerm() > raftNode.getCurrentTerm()) {
LOG.info("Received AppendEntries request from server {} " +
"in term {} (this server's term was {})",
request.getServerId(), request.getTerm(),
raftNode.getCurrentTerm());
responseBuilder.setTerm(request.getTerm());
}
raftNode.stepDown(request.getTerm());
raftNode.resetElectionTimer();
if (raftNode.getLeaderId() == 0) {
raftNode.setLeaderId(request.getServerId());
}
if (request.getPrevLogIndex() > raftNode.getRaftLog().getLastLogIndex()) {
LOG.debug("Rejecting AppendEntries RPC: would leave gap");
return responseBuilder.build();
}
if (request.getPrevLogIndex() >= raftNode.getRaftLog().getStartLogIndex()
&& raftNode.getRaftLog().getEntry(request.getPrevLogIndex()).getTerm()
!= request.getPrevLogTerm()) {
LOG.debug("Rejecting AppendEntries RPC: terms don't agree");
return responseBuilder.build();
}
responseBuilder.setSuccess(true);
List<Raft.LogEntry> entries = new ArrayList<>();
long index = request.getPrevLogIndex();
for (Raft.LogEntry entry : request.getEntriesList()) {
index++;
if (index < raftNode.getRaftLog().getStartLogIndex()) {
continue;
}
if (raftNode.getRaftLog().getLastLogIndex() >= index) {
if (raftNode.getRaftLog().getEntry(index).getTerm() == entry.getTerm()) {
continue;
}
// TODO: truncate segment log from index
}
entries.add(entry);
}
raftNode.getRaftLog().append(entries);
responseBuilder.setLastLogIndex(raftNode.getRaftLog().getLastLogIndex());
if (raftNode.getCommitIndex() < request.getCommitIndex()) {
raftNode.setCommitIndex(request.getCommitIndex());
// TODO: apply state machine
}
return responseBuilder.build();
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected boolean isInstallingExtensionNeeded(Set<BindingEnum> bindingTypes) {
final JsonObject hostJson = readHostJson();
final JsonObject extensionBundle = hostJson == null ? null : hostJson.getAsJsonObject(EXTENSION_BUNDLE);
if (extensionBundle != null && extensionBundle.has("id") &&
StringUtils.equalsIgnoreCase(extensionBundle.get("id").getAsString(), EXTENSION_BUNDLE_ID)) {
getLog().info(SKIP_INSTALL_EXTENSIONS_BUNDLE);
return false;
}
final boolean isNonHttpTriggersExist = bindingTypes.stream().anyMatch(binding ->
!Arrays.asList(FUNCTION_WITHOUT_FUNCTION_EXTENSION).contains(binding));
if (!isNonHttpTriggersExist) {
getLog().info(SKIP_INSTALL_EXTENSIONS_HTTP);
return false;
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected boolean isInstallingExtensionNeeded(Set<BindingEnum> bindingTypes) {
final JsonObject hostJson = readHostJson();
final JsonObject extensionBundle = hostJson.getAsJsonObject(EXTENSION_BUNDLE);
if (extensionBundle != null && extensionBundle.has("id") &&
StringUtils.equalsIgnoreCase(extensionBundle.get("id").getAsString(), EXTENSION_BUNDLE_ID)) {
getLog().info(SKIP_INSTALL_EXTENSIONS_BUNDLE);
return false;
}
final boolean isNonHttpTriggersExist = bindingTypes.stream().anyMatch(binding ->
!Arrays.asList(FUNCTION_WITHOUT_FUNCTION_EXTENSION).contains(binding));
if (!isNonHttpTriggersExist) {
getLog().info(SKIP_INSTALL_EXTENSIONS_HTTP);
return false;
}
return true;
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void prepareBasic() throws Exception {
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void prepareBasic() throws Exception {
if (this.ctx == null) {
ctx = AppContext.getDefault();
}
if (ctx.getMainClass() == null && mainClass != null)
ctx.setMainClass(mainClass);
// 检查ClassLoader的情况
if (ctx.getClassLoader() == null)
ctx.setClassLoader(NbApp.class.getClassLoader());
if (ctx.getEnvHolder() == null) {
ctx.setEnvHolder(new SystemPropertiesEnvHolder());
}
// 看看日志应该用哪个
String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter");
if (!Strings.isBlank(logAdapter)) {
Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance());
}
log = Logs.get();
// 资源加载器
if (ctx.getResourceLoader() == null) {
ResourceLoader resourceLoader = new SimpleResourceLoader();
aware(resourceLoader);
ctx.setResourceLoader(resourceLoader);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void prepareIoc() {
if (ctx.getIoc() == null) {
ctx.setIoc(new NutIoc(ctx.getComboIocLoader()));
}
// 把核心对象放进ioc容器
if (!ctx.ioc.has("appContext")){
Ioc2 ioc2 = (Ioc2)ctx.getIoc();
ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx));
ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf()));
ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this));
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void prepareIoc() throws Exception {
if (ctx.getComboIocLoader() == null) {
int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64);
List<String> args = new ArrayList<>();
args.add("*js");
args.add("ioc/");
args.add("*tx");
args.add("*async");
args.add(""+asyncPoolSize);
args.add("*anno");
args.add(ctx.getPackage());
IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class);
if (iocBy != null) {
String[] tmp = iocBy.args();
ArrayList<String> _args = new ArrayList<>();
for (int i=0;i<tmp.length;i++) {
if (tmp[i].startsWith("*")) {
if (!_args.isEmpty()) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
_args.clear();
}
}
_args.add(tmp[i]);
}
if (_args.size() > 0) {
switch (_args.get(0)) {
case "*tx":
case "*async":
case "*anno":
case "*js":
break;
default:
args.addAll(_args);
}
}
}
ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()])));
}
// 用于加载Starter的IocLoader
starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter");
ctx.getComboIocLoader().addLoader(starterIocLoader);
if (ctx.getIoc() == null) {
ctx.setIoc(new NutIoc(ctx.getComboIocLoader()));
}
// 把核心对象放进ioc容器
if (!ctx.ioc.has("appContext")){
Ioc2 ioc2 = (Ioc2)ctx.getIoc();
ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx));
ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf()));
ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this));
}
}
#location 45
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void prepare() throws Exception {
if (prepared)
return;
// 初始化上下文
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before));
this.prepareBasic();
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after));
// 打印Banner,暂时不可配置具体的类
new SimpleBannerPrinter().printBanner(ctx);
// 配置信息要准备好
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before));
this.prepareConfigureLoader();
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after));
// 创建IocLoader体系
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before));
prepareIocLoader();
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after));
// 加载各种starter
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before));
prepareStarterClassList();
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after));
// 打印配置文档
if (printProcDoc) {
PropDocReader docReader = new PropDocReader();
docReader.load(starterClasses);
if (getAppContext().getConf().get("nutz.propdoc.packages") != null) {
for (String pkg : Strings.splitIgnoreBlank(getAppContext().getConf().get("nutz.propdoc.packages"))) {
for (Class<?> klass : Scans.me().scanPackage(pkg)) {
if (klass.isInterface())
continue;
docReader.addClass(klass);
}
}
}
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 创建Ioc容器
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before));
prepareIoc();
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after));
// 生成Starter实例
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before));
prepareStarterInstance();
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after));
// 从Ioc容器检索Listener
listeners.addAll(ctx.getBeans(NbAppEventListener.class));
prepared = true;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void prepare() throws Exception {
if (prepared)
return;
// 初始化上下文
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before));
this.prepareBasic();
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after));
// 打印Banner,暂时不可配置具体的类
new SimpleBannerPrinter().printBanner(ctx);
// 配置信息要准备好
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before));
this.prepareConfigureLoader();
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after));
// 创建IocLoader体系
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before));
prepareIocLoader();
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after));
// 加载各种starter
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before));
prepareStarterClassList();
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after));
// 打印配置文档
if (printProcDoc) {
PropDocReader docReader = new PropDocReader();
docReader.load(starterClasses);
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 创建Ioc容器
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before));
prepareIoc();
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after));
// 生成Starter实例
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before));
prepareStarterInstance();
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after));
// 从Ioc容器检索Listener
listeners.addAll(ctx.getBeans(NbAppEventListener.class));
prepared = true;
}
#location 42
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void _run() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void _run() throws Exception {
Stopwatch sw = Stopwatch.begin();
// 各种预备操作
this.prepare();
if (printProcDoc) {
PropDocReader docReader = new PropDocReader(ctx);
docReader.load();
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 依次启动
try {
ctx.init();
ctx.startServers();
if (ctx.getMainClass().getAnnotation(IocBean.class) != null)
ctx.getIoc().get(ctx.getMainClass());
sw.stop();
log.infof("NB started : %sms", sw.du());
synchronized (lock) {
lock.wait();
}
}
catch (Throwable e) {
log.error("something happen!!", e);
}
// 收尾
ctx.stopServers();
ctx.depose();
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void shutdown() {
log.info("ok, shutting down ...");
if (lock == null) {
_shutdown();
}
else {
synchronized (lock) {
lock.notify();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void shutdown() {
log.info("ok, shutting down ...");
synchronized (lock) {
lock.notify();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void prepare() throws Exception {
if (prepared)
return;
// 初始化上下文
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before));
this.prepareBasic();
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after));
// 打印Banner,暂时不可配置具体的类
new SimpleBannerPrinter().printBanner(ctx);
// 配置信息要准备好
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before));
this.prepareConfigureLoader();
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after));
// 创建IocLoader体系
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before));
prepareIocLoader();
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after));
// 加载各种starter
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before));
prepareStarterClassList();
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after));
// 打印配置文档
if (printProcDoc) {
PropDocReader docReader = new PropDocReader();
docReader.load(starterClasses);
if (getAppContext().getConf().get("nutz.propdoc.packages") != null) {
for (String pkg : Strings.splitIgnoreBlank(getAppContext().getConf().get("nutz.propdoc.packages"))) {
for (Class<?> klass : Scans.me().scanPackage(pkg)) {
if (klass.isInterface())
continue;
docReader.addClass(klass);
}
}
}
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 创建Ioc容器
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before));
prepareIoc();
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after));
// 生成Starter实例
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before));
prepareStarterInstance();
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after));
// 从Ioc容器检索Listener
listeners.addAll(ctx.getBeans(NbAppEventListener.class));
prepared = true;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void prepare() throws Exception {
if (prepared)
return;
// 初始化上下文
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before));
this.prepareBasic();
listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after));
// 打印Banner,暂时不可配置具体的类
new SimpleBannerPrinter().printBanner(ctx);
// 配置信息要准备好
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before));
this.prepareConfigureLoader();
listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after));
// 创建IocLoader体系
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before));
prepareIocLoader();
listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after));
// 加载各种starter
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before));
prepareStarterClassList();
listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after));
// 打印配置文档
if (printProcDoc) {
PropDocReader docReader = new PropDocReader();
docReader.load(starterClasses);
Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown());
}
// 创建Ioc容器
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before));
prepareIoc();
listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after));
// 生成Starter实例
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before));
prepareStarterInstance();
listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after));
// 从Ioc容器检索Listener
listeners.addAll(ctx.getBeans(NbAppEventListener.class));
prepared = true;
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET)
public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
String aoData = request.getParameter("aoData");
JSONArray jsonArray = JSON.parseArray(aoData);
int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0;
for (Object obj : jsonArray) {
JSONObject jsonObj = (JSONObject) obj;
if ("sEcho".equals(jsonObj.getString("name"))) {
sEcho = jsonObj.getIntValue("value");
} else if ("iDisplayStart".equals(jsonObj.getString("name"))) {
iDisplayStart = jsonObj.getIntValue("value");
} else if ("iDisplayLength".equals(jsonObj.getString("name"))) {
iDisplayLength = jsonObj.getIntValue("value");
}
}
JSONArray ret = JSON.parseArray(OffsetService.getLogSize(topic, group, ip));
int offset = 0;
JSONArray retArr = new JSONArray();
for (Object tmp : ret) {
JSONObject tmp2 = (JSONObject) tmp;
if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) {
JSONObject obj = new JSONObject();
obj.put("partition", tmp2.getInteger("partition"));
if (tmp2.getLong("logSize") == 0) {
obj.put("logsize", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("logsize", tmp2.getLong("logSize"));
}
if (tmp2.getLong("offset") == -1) {
obj.put("offset", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("offset", "<a class='btn btn-success btn-xs'>" + tmp2.getLong("offset") + "</a>");
}
obj.put("lag", "<a class='btn btn-danger btn-xs'>" + tmp2.getLong("lag") + "</a>");
obj.put("owner", tmp2.getString("owner"));
obj.put("created", tmp2.getString("create"));
obj.put("modify", tmp2.getString("modify"));
retArr.add(obj);
}
offset++;
}
JSONObject obj = new JSONObject();
obj.put("sEcho", sEcho);
obj.put("iTotalRecords", ret.size());
obj.put("iTotalDisplayRecords", ret.size());
obj.put("aaData", retArr);
try {
byte[] output = GzipUtils.compressToByte(obj.toJSONString());
response.setContentLength(output == null ? "NULL".toCharArray().length : output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET)
public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Charset", "utf-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Encoding", "gzip");
String ip = request.getHeader("x-forwarded-for");
LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip));
String aoData = request.getParameter("aoData");
JSONArray jsonArray = JSON.parseArray(aoData);
int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0;
for (Object obj : jsonArray) {
JSONObject jsonObj = (JSONObject) obj;
if ("sEcho".equals(jsonObj.getString("name"))) {
sEcho = jsonObj.getIntValue("value");
} else if ("iDisplayStart".equals(jsonObj.getString("name"))) {
iDisplayStart = jsonObj.getIntValue("value");
} else if ("iDisplayLength".equals(jsonObj.getString("name"))) {
iDisplayLength = jsonObj.getIntValue("value");
}
}
JSONArray ret = JSON.parseArray(OffsetService.getLogSize(topic, group, ip));
int offset = 0;
JSONArray retArr = new JSONArray();
for (Object tmp : ret) {
JSONObject tmp2 = (JSONObject) tmp;
if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) {
JSONObject obj = new JSONObject();
obj.put("partition", tmp2.getInteger("partition"));
if (tmp2.getLong("logSize") == 0) {
obj.put("logsize", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("logsize", tmp2.getLong("logSize"));
}
if (tmp2.getLong("offset") == -1) {
obj.put("offset", "<a class='btn btn-warning btn-xs'>0</a>");
} else {
obj.put("offset", "<a class='btn btn-success btn-xs'>" + tmp2.getLong("offset") + "</a>");
}
obj.put("lag", "<a class='btn btn-danger btn-xs'>" + tmp2.getLong("lag") + "</a>");
obj.put("owner", tmp2.getString("owner"));
obj.put("created", tmp2.getString("create"));
obj.put("modify", tmp2.getString("modify"));
retArr.add(obj);
}
offset++;
}
JSONObject obj = new JSONObject();
obj.put("sEcho", sEcho);
obj.put("iTotalRecords", ret.size());
obj.put("iTotalDisplayRecords", ret.size());
obj.put("aaData", retArr);
try {
byte[] output = GzipUtils.compressToByte(obj.toJSONString());
response.setContentLength(output.length);
OutputStream out = response.getOutputStream();
out.write(output);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
#location 60
#vulnerability type NULL_DEREFERENCE |
#fixed code
private static void saveMD5File(File dataFile, String digestString)
throws IOException {
File md5File = getDigestFileForFile(dataFile);
String md5Line = digestString + " *" + dataFile.getName() + "\n";
try (AtomicFileOutputStream afos
= new AtomicFileOutputStream(md5File)) {
afos.write(md5Line.getBytes(StandardCharsets.UTF_8));
}
if (LOG.isDebugEnabled()) {
LOG.debug("Saved MD5 " + digestString + " to " + md5File);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private static void saveMD5File(File dataFile, String digestString)
throws IOException {
File md5File = getDigestFileForFile(dataFile);
String md5Line = digestString + " *" + dataFile.getName() + "\n";
AtomicFileOutputStream afos = new AtomicFileOutputStream(md5File);
afos.write(md5Line.getBytes(StandardCharsets.UTF_8));
afos.close();
if (LOG.isDebugEnabled()) {
LOG.debug("Saved MD5 " + digestString + " to " + md5File);
}
}
#location 12
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
protected void operation(RaftClient client) throws IOException {
List<String> paths = generateFiles();
FileStoreClient fileStoreClient = new FileStoreClient(client);
System.out.println("Starting Async write now ");
long startTime = System.currentTimeMillis();
long totalWrittenBytes = waitWriteFinish(writeByHeapByteBuffer(paths, fileStoreClient));
long endTime = System.currentTimeMillis();
System.out.println("Total files written: " + getNumFiles());
System.out.println("Each files size: " + getFileSizeInBytes());
System.out.println("Total data written: " + totalWrittenBytes + " bytes");
System.out.println("Total time taken: " + (endTime - startTime) + " millis");
client.close();
System.exit(0);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected void operation(RaftClient client) throws IOException {
int length = Integer.parseInt(size);
int num = Integer.parseInt(numFiles);
AtomicLong totalBytes = new AtomicLong(0);
String entropy = RandomStringUtils.randomAlphanumeric(10);
byte[] fileValue = string2Bytes(RandomStringUtils.randomAscii(length));
FileStoreClient fileStoreClient = new FileStoreClient(client);
System.out.println("Starting load now ");
long startTime = System.currentTimeMillis();
List<CompletableFuture<Long>> futures = new ArrayList<>();
for (int i = 0; i < num; i++) {
String path = "file-" + entropy + "-" + i;
ByteBuffer b = ByteBuffer.wrap(fileValue);
futures.add(fileStoreClient.writeAsync(path, 0, true, b));
}
for (CompletableFuture<Long> future : futures) {
Long writtenLen = future.join();
totalBytes.addAndGet(writtenLen);
if (writtenLen != length) {
System.out.println("File length written is wrong: " + writtenLen + length);
}
}
long endTime = System.currentTimeMillis();
System.out.println("Total files written: " + futures.size());
System.out.println("Each files size: " + length);
System.out.println("Total data written: " + totalBytes + " bytes");
System.out.println("Total time taken: " + (endTime - startTime) + " millis");
client.close();
System.exit(0);
}
#location 20
#vulnerability type RESOURCE_LEAK |
#fixed code
public synchronized void deleteRepoByName(String repositoryName) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.dbConfig.getConnection();
preparedStatement = connection.prepareStatement("delete from repo where name=?;");
preparedStatement.setString(1, repositoryName);
preparedStatement.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(resultSet);
Helpers.closeQuietly(preparedStatement);
Helpers.closeQuietly(connection);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public synchronized void deleteRepoByName(String repositoryName) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.dbConfig.getConnection();
stmt = conn.prepareStatement("delete from repo where name=?;");
stmt.setString(1, repositoryName);
stmt.execute();
this.cache.remove(repositoryName);
this.genericCache.remove(this.repoCountCacheKey);
this.genericCache.remove(this.repoAllRepoCacheKey);
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(rs);
Helpers.closeQuietly(stmt);
Helpers.closeQuietly(conn);
}
}
#location 22
#vulnerability type NULL_DEREFERENCE |
#fixed code
public SlocCount countStats(String contents, String languageName) {
if (contents == null || contents.isEmpty()) {
return new SlocCount();
}
FileClassifierResult fileClassifierResult = this.database.get(languageName);
State currentState = State.S_BLANK;
int endPoint = contents.length() - 1;
String endString = null;
ArrayList<String> endComments = new ArrayList<>();
int linesCount = 0;
int blankCount = 0;
int codeCount = 0;
int commentCount = 0;
int complexity = 0;
for (int index=0; index < contents.length(); index++) {
if (!isWhitespace(contents.charAt(index))) {
switch (currentState) {
case S_CODE:
if (fileClassifierResult.nestedmultiline || endComments.size() == 0) {
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
endComments.add(endString);
currentState = State.S_MULTICOMMENT_CODE;
break;
}
}
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) {
currentState = State.S_COMMENT_CODE;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
} else if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
break;
case S_MULTICOMMENT_BLANK:
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) {
currentState = State.S_COMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
currentState = State.S_MULTICOMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
}
if (!this.isWhitespace(contents.charAt(index))) {
currentState = State.S_CODE;
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
}
break;
case S_STRING:
if (contents.charAt(index - 1) != '\\' && this.checkForMatchSingle(contents.charAt(index), index, endPoint, endString, contents)) {
currentState = State.S_CODE;
}
break;
case S_MULTICOMMENT:
case S_MULTICOMMENT_CODE:
if (this.checkForMatchMultiClose(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents)) {
if (currentState == State.S_MULTICOMMENT_CODE) {
currentState = State.S_CODE;
} else {
// TODO check if out of bounds
if (index + 1 <= endPoint && this.isWhitespace(contents.charAt(index + 1))) {
currentState = State.S_MULTICOMMENT_BLANK;
} else {
currentState = State.S_MULTICOMMENT_CODE;
}
}
}
break;
}
}
// This means the end of processing the line so calculate the stats according to what state
// we are currently in
if (contents.charAt(index) == '\n' || index == endPoint) {
linesCount++;
switch (currentState) {
case S_BLANK:
blankCount++;
break;
case S_COMMENT:
case S_MULTICOMMENT:
case S_MULTICOMMENT_BLANK:
commentCount++;
break;
case S_CODE:
case S_STRING:
case S_COMMENT_CODE:
case S_MULTICOMMENT_CODE:
codeCount++;
break;
}
// If we are in a multiline comment that started after some code then we need
// to move to a multiline comment if a multiline comment then stay there
// otherwise we reset back into a blank state
if (currentState != State.S_MULTICOMMENT && currentState != State.S_MULTICOMMENT_CODE) {
currentState = State.S_BLANK;
} else {
currentState = State.S_MULTICOMMENT;
}
}
}
return new SlocCount(linesCount, blankCount, codeCount, commentCount, complexity);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public SlocCount countStats(String contents, String languageName) {
if (contents == null || contents.isEmpty()) {
return new SlocCount();
}
FileClassifierResult fileClassifierResult = this.database.get(languageName);
State currentState = State.S_BLANK;
int endPoint = contents.length() - 1;
String endString = null;
int linesCount = 0;
int blankCount = 0;
int codeCount = 0;
int commentCount = 0;
int complexity = 0;
for (int index=0; index < contents.length(); index++) {
switch (currentState) {
case S_BLANK:
case S_MULTICOMMENT_BLANK:
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) {
currentState = State.S_COMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
currentState = State.S_MULTICOMMENT;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
}
if (!this.isWhitespace(contents.charAt(index))) {
currentState = State.S_CODE;
if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
}
break;
case S_CODE:
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents);
if (endString != null) {
currentState = State.S_MULTICOMMENT_CODE;
break;
}
endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents);
if (endString != null) {
currentState = State.S_STRING;
break;
} else if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) {
complexity++;
}
break;
case S_STRING:
if (contents.charAt(index-1) != '\\' && this.checkForMatchSingle(contents.charAt(index), index, endPoint, endString, contents)) {
currentState = State.S_CODE;
}
break;
case S_MULTICOMMENT:
case S_MULTICOMMENT_CODE:
if (this.checkForMatchMultiClose(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents)) {
if (currentState == State.S_MULTICOMMENT_CODE) {
currentState = State.S_CODE;
} else {
// TODO check if out of bounds
if (index + 1 <= endPoint && this.isWhitespace(contents.charAt(index+1))) {
currentState = State.S_MULTICOMMENT_BLANK;
} else {
currentState = State.S_MULTICOMMENT_CODE;
}
}
}
break;
}
// This means the end of processing the line so calculate the stats according to what state
// we are currently in
if (contents.charAt(index) == '\n' || index == endPoint) {
linesCount++;
switch (currentState) {
case S_BLANK:
blankCount++;
break;
case S_COMMENT:
case S_MULTICOMMENT:
case S_MULTICOMMENT_BLANK:
commentCount++;
break;
case S_CODE:
case S_STRING:
case S_COMMENT_CODE:
case S_MULTICOMMENT_CODE:
codeCount++;
break;
}
// If we are in a multiline comment that started after some code then we need
// to move to a multiline comment if a multiline comment then stay there
// otherwise we reset back into a blank state
if (currentState != State.S_MULTICOMMENT && currentState != State.S_MULTICOMMENT_CODE) {
currentState = State.S_BLANK;
} else {
currentState = State.S_MULTICOMMENT;
}
}
}
return new SlocCount(linesCount, blankCount, codeCount, commentCount, complexity);
}
#location 22
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void testIsBinaryWhiteListedExtension() {
SearchcodeLib sl = new SearchcodeLib();
ArrayList<String> codeLines = new ArrayList<>();
codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你");
FileClassifier fileClassifier = new FileClassifier();
for(FileClassifierResult fileClassifierResult: fileClassifier.getDatabase()) {
for(String extension: fileClassifierResult.extensions) {
BinaryFinding isBinary = sl.isBinary(codeLines, "myfile." + extension);
assertThat(isBinary.isBinary()).isFalse();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testIsBinaryWhiteListedExtension() {
SearchcodeLib sl = new SearchcodeLib();
ArrayList<String> codeLines = new ArrayList<>();
codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你");
FileClassifier fileClassifier = new FileClassifier();
for(Classifier classifier: fileClassifier.getClassifier()) {
for(String extension: classifier.extensions) {
BinaryFinding isBinary = sl.isBinary(codeLines, "myfile." + extension);
assertThat(isBinary.isBinary()).isFalse();
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public synchronized boolean saveRepo(RepoResult repoResult) {
RepoResult existing = this.getRepoByName(repoResult.getName());
this.cache.remove(repoResult.getName());
boolean isNew = false;
Connection connection = null;
PreparedStatement preparedStatement = null;
// Update with new details
try {
connection = this.dbConfig.getConnection();
if (existing != null) {
preparedStatement = connection.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?");
preparedStatement.setString(8, repoResult.getName());
}
else {
isNew = true;
preparedStatement = connection.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)");
}
preparedStatement.setString(1, repoResult.getName());
preparedStatement.setString(2, repoResult.getScm());
preparedStatement.setString(3, repoResult.getUrl());
preparedStatement.setString(4, repoResult.getUsername());
preparedStatement.setString(5, repoResult.getPassword());
preparedStatement.setString(6, repoResult.getSource());
preparedStatement.setString(7, repoResult.getBranch());
preparedStatement.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(preparedStatement);
Helpers.closeQuietly(connection);
}
this.genericCache.remove(this.repoCountCacheKey);
this.genericCache.remove(this.repoAllRepoCacheKey);
return isNew;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public synchronized boolean saveRepo(RepoResult repoResult) {
RepoResult existing = this.getRepoByName(repoResult.getName());
this.cache.remove(repoResult.getName());
boolean isNew = false;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
if (existing != null) {
// Update with new details
try {
conn = this.dbConfig.getConnection();
stmt = conn.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?");
stmt.setString(1, repoResult.getName());
stmt.setString(2, repoResult.getScm());
stmt.setString(3, repoResult.getUrl());
stmt.setString(4, repoResult.getUsername());
stmt.setString(5, repoResult.getPassword());
stmt.setString(6, repoResult.getSource());
stmt.setString(7, repoResult.getBranch());
// Target the row
stmt.setString(8, repoResult.getName());
stmt.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(rs);
Helpers.closeQuietly(stmt);
Helpers.closeQuietly(conn);
}
}
else {
isNew = true;
try {
conn = this.dbConfig.getConnection();
stmt = conn.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)");
stmt.setString(1, repoResult.getName());
stmt.setString(2, repoResult.getScm());
stmt.setString(3, repoResult.getUrl());
stmt.setString(4, repoResult.getUsername());
stmt.setString(5, repoResult.getPassword());
stmt.setString(6, repoResult.getSource());
stmt.setString(7, repoResult.getBranch());
stmt.execute();
}
catch(SQLException ex) {
LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(rs);
Helpers.closeQuietly(stmt);
Helpers.closeQuietly(conn);
}
}
this.genericCache.remove(this.repoCountCacheKey);
this.genericCache.remove(this.repoAllRepoCacheKey);
return isNew;
}
#location 35
#vulnerability type NULL_DEREFERENCE |
#fixed code
public String getCurrentRevision(String repoLocations, String repoName) {
String currentRevision = "";
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml");
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
BufferedReader bufferedReader = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(Helpers.removeUTF8BOM(line));
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Singleton.getLogger().info("getCurrentRevision: " + repoName + " " + sb.toString());
Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("entry");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
currentRevision = eElement.getAttribute("revision");
}
}
} catch (IOException | ParserConfigurationException | SAXException ex) {
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getCurrentRevision for " + repoName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
Helpers.closeQuietly(bufferedReader);
}
return currentRevision;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public String getCurrentRevision(String repoLocations, String repoName) {
String currentRevision = "";
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml");
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(Helpers.removeUTF8BOM(line));
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Singleton.getLogger().info("getCurrentRevision: " + repoName + " " + sb.toString());
Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("entry");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
currentRevision = eElement.getAttribute("revision");
}
}
} catch (IOException | ParserConfigurationException | SAXException ex) {
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getCurrentRevision for " + repoName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
}
return currentRevision;
}
#location 39
#vulnerability type RESOURCE_LEAK |
#fixed code
public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) {
// svn diff -r 4000:HEAD --summarize --xml
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "diff", "-r", startRevision + ":HEAD", "--summarize", "--xml");
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
BufferedReader bufferedReader = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
bufferedReader = new BufferedReader(isr);
String line;
StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
Singleton.getLogger().info("svn diff: " + line);
sb.append(Helpers.removeUTF8BOM(line));
}
Singleton.getLogger().info("Before XML parsing: " + sb.toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
doc.getDocumentElement().normalize();
Element node = (Element)doc.getElementsByTagName("diff").item(0);
node = (Element)node.getElementsByTagName("paths").item(0);
NodeList nList = node.getElementsByTagName("path");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String type = eElement.getAttribute("item");
String path = eElement.getTextContent();
if ("modified".equals(type) || "added".equals(type)) {
changedFiles.add(path);
}
else {
deletedFiles.add(path);
}
}
}
}
catch(IOException | ParserConfigurationException | SAXException ex) {
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getDiffBetweenRevisions for " + repoName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
Helpers.closeQuietly(bufferedReader);
}
return new RepositoryChanged(true, changedFiles, deletedFiles);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) {
// svn diff -r 4000:HEAD --summarize --xml
List<String> changedFiles = new ArrayList<>();
List<String> deletedFiles = new ArrayList<>();
ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "diff", "-r", startRevision + ":HEAD", "--summarize", "--xml");
processBuilder.directory(new File(repoLocations + repoName));
Process process = null;
try {
process = processBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
Singleton.getLogger().info("svn diff: " + line);
sb.append(Helpers.removeUTF8BOM(line));
}
Singleton.getLogger().info("Before XML parsing: " + sb.toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
doc.getDocumentElement().normalize();
Element node = (Element)doc.getElementsByTagName("diff").item(0);
node = (Element)node.getElementsByTagName("paths").item(0);
NodeList nList = node.getElementsByTagName("path");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String type = eElement.getAttribute("item");
String path = eElement.getTextContent();
if ("modified".equals(type) || "added".equals(type)) {
changedFiles.add(path);
}
else {
deletedFiles.add(path);
}
}
}
}
catch(IOException | ParserConfigurationException | SAXException ex) {
Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getDiffBetweenRevisions for " + repoName + "\n with message: " + ex.getMessage());
}
finally {
Helpers.closeQuietly(process);
}
return new RepositoryChanged(true, changedFiles, deletedFiles);
}
#location 57
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
lifxMap = null;
aGsonHandler = null;
validLifx = bridgeSettings.isValidLifx();
log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured."));
if(validLifx) {
try {
log.info("Open Lifx client....");
InetAddress configuredAddress = InetAddress.getByName(bridgeSettings.getUpnpConfigAddress());
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(configuredAddress);
InetAddress bcastInetAddr = null;
if (networkInterface != null) {
for (InterfaceAddress ifaceAddr : networkInterface.getInterfaceAddresses()) {
InetAddress addr = ifaceAddr.getAddress();
if (addr instanceof Inet4Address) {
bcastInetAddr = ifaceAddr.getBroadcast();
break;
}
}
}
if(bcastInetAddr != null) {
lifxMap = new HashMap<String, LifxDevice>();
log.info("Opening LFX Client with broadcast address: " + bcastInetAddr.getHostAddress());
client = new LFXClient(bcastInetAddr.getHostAddress());
client.getLights().addLightCollectionListener(new MyLightListener(lifxMap));
client.getGroups().addGroupCollectionListener(new MyGroupListener(lifxMap));
client.open(false);
aGsonHandler =
new GsonBuilder()
.create();
} else {
log.warn("Could not open LIFX, no bcast addr available, check your upnp config address.");
client = null;
validLifx = false;
return this;
}
} catch (IOException e) {
log.warn("Could not open LIFX, with IO Exception", e);
client = null;
validLifx = false;
return this;
} catch (InterruptedException e) {
log.warn("Could not open LIFX, with Interruprted Exception", e);
client = null;
validLifx = false;
return this;
}
}
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Home createHome(BridgeSettingsDescriptor bridgeSettings) {
lifxMap = null;
aGsonHandler = null;
validLifx = bridgeSettings.isValidLifx();
log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured."));
if(validLifx) {
try {
log.info("Open Lifx client....");
InetAddress configuredAddress = InetAddress.getByName(bridgeSettings.getUpnpConfigAddress());
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(configuredAddress);
InetAddress bcastInetAddr = null;
if (networkInterface != null) {
for (InterfaceAddress ifaceAddr : networkInterface.getInterfaceAddresses()) {
InetAddress addr = ifaceAddr.getAddress();
if (addr instanceof Inet4Address) {
bcastInetAddr = ifaceAddr.getBroadcast();
break;
}
}
}
lifxMap = new HashMap<String, LifxDevice>();
log.info("Opening LFX Client with broadcast address: " + bcastInetAddr.getHostAddress());
client = new LFXClient(bcastInetAddr.getHostAddress());
client.getLights().addLightCollectionListener(new MyLightListener(lifxMap));
client.getGroups().addGroupCollectionListener(new MyGroupListener(lifxMap));
client.open(false);
} catch (IOException e) {
log.warn("Could not open LIFX, with IO Exception", e);
client = null;
return this;
} catch (InterruptedException e) {
log.warn("Could not open LIFX, with Interruprted Exception", e);
client = null;
return this;
}
aGsonHandler =
new GsonBuilder()
.create();
}
return this;
}
#location 23
#vulnerability type NULL_DEREFERENCE |
#fixed code
private void configWriter(String content, Path filePath) {
if(Files.exists(filePath) && !Files.isWritable(filePath)){
log.error("Error file is not writable: " + filePath);
return;
}
if(Files.notExists(filePath.getParent())) {
try {
Files.createDirectories(filePath.getParent());
} catch (IOException e) {
log.error("Error creating the directory: " + filePath + " message: " + e.getMessage(), e);
}
}
try {
Path target = null;
if(Files.exists(filePath)) {
target = FileSystems.getDefault().getPath(filePath.getParent().toString(), "habridge.config.old");
Files.move(filePath, target);
}
Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE);
// set attributes to be for user only
// using PosixFilePermission to set file permissions
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
// add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
try {
String osName = System.getProperty("os.name");
if(osName.toLowerCase().indexOf("win") < 0)
Files.setPosixFilePermissions(filePath, perms);
} catch(UnsupportedOperationException e) {
log.info("Cannot set permissions for config file on this system as it is not supported. Continuing");
}
if(target != null)
Files.delete(target);
} catch (IOException e) {
log.error("Error writing the file: " + filePath + " message: " + e.getMessage(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void configWriter(String content, Path filePath) {
if(Files.exists(filePath) && !Files.isWritable(filePath)){
log.error("Error file is not writable: " + filePath);
return;
}
if(Files.notExists(filePath.getParent())) {
try {
Files.createDirectories(filePath.getParent());
} catch (IOException e) {
log.error("Error creating the directory: " + filePath + " message: " + e.getMessage(), e);
}
}
try {
Path target = null;
if(Files.exists(filePath)) {
target = FileSystems.getDefault().getPath(filePath.getParent().toString(), "habridge.config.old");
Files.move(filePath, target);
}
Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE);
// set attributes to be for user only
// using PosixFilePermission to set file permissions
Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
// add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
try {
if(System.getProperty("os.name").toLowerCase().indexOf("win") <= 0)
Files.setPosixFilePermissions(filePath, perms);
} catch(UnsupportedOperationException e) {
log.info("Cannot set permissions for config file on this system as it is not supported. Continuing");
}
if(target != null)
Files.delete(target);
} catch (IOException e) {
log.error("Error writing the file: " + filePath + " message: " + e.getMessage(), e);
}
}
#location 31
#vulnerability type NULL_DEREFERENCE |
#fixed code
public byte[] getPDF() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(getCommandAsArray());
StreamEater outputStreamEater = new StreamEater(process.getInputStream());
outputStreamEater.start();
StreamEater errorStreamEater = new StreamEater(process.getErrorStream());
errorStreamEater.start();
outputStreamEater.join();
errorStreamEater.join();
process.waitFor();
if (process.exitValue() != 0) {
throw new RuntimeException("Process (" + getCommand() + ") exited with status code " + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes()));
}
if (outputStreamEater.getError() != null) {
throw outputStreamEater.getError();
}
if (errorStreamEater.getError() != null) {
throw errorStreamEater.getError();
}
return outputStreamEater.getBytes();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public byte[] getPDF() throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(getCommandAsArray());
for (Page page : pages) {
if (page.getType().equals(PageType.htmlAsString)) {
OutputStream stdInStream = process.getOutputStream();
stdInStream.write(page.getSource().getBytes("UTF-8"));
stdInStream.close();
}
}
StreamEater outputStreamEater = new StreamEater(process.getInputStream());
outputStreamEater.start();
StreamEater errorStreamEater = new StreamEater(process.getErrorStream());
errorStreamEater.start();
outputStreamEater.join();
errorStreamEater.join();
process.waitFor();
if (process.exitValue() != 0) {
throw new RuntimeException("Process (" + getCommand() + ") exited with status code " + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes()));
}
if (outputStreamEater.getError() != null) {
throw outputStreamEater.getError();
}
if (errorStreamEater.getError() != null) {
throw errorStreamEater.getError();
}
return outputStreamEater.getBytes();
}
#location 35
#vulnerability type RESOURCE_LEAK |
#fixed code
@SuppressWarnings("unchecked")
@Test
// Add the MetadataLinkListener to the listener chain. The output will render an href to view the metadata
// for the album object.
public void testMetadataHref()
{
String prefixUrl = "/metadata/";
String fileExtension = "test";
Album signOfTheTimes = DataGenerator.signOfTheTimes();
DefaultMetaDataRegistry service = new DefaultMetaDataRegistry();
service.setRootMetaDataUrl( prefixUrl );
service.setCoreSelector( new CoreSelector( populatorRegistry ) );
Map<String,Class<?>> typeMappings = new HashMap<String, Class<?>>();
typeMappings.put( "album", Album.class );
service.setTypeMappings( typeMappings );
MetadataLinkListener metadataLinkListener = new MetadataLinkListener();
metadataLinkListener.setMetaDataRegistry( service );
ResultTraverser traverser = new ResultTraverser();
YogaRequestContext requestContext = new YogaRequestContext( fileExtension, new GDataSelectorParser(),
new DummyHttpServletRequest(), new DummyHttpServletResponse(), metadataLinkListener );
Map<String, Object> objectTree = doTraverse( signOfTheTimes, "", traverser, requestContext );
Map<String,String> metadataMap = (Map<String,String>) objectTree.get( "metadata" );
String metadataHref = prefixUrl + "album." + fileExtension;
Assert.assertEquals( metadataHref, metadataMap.get( "href" ) );
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
@Test
// Add the MetadataLinkListener to the listener chain. The output will render an href to view the metadata
// for the album object.
public void testMetadataHref()
{
String prefixUrl = "/metadata/";
String fileExtension = "test";
Album signOfTheTimes = DataGenerator.signOfTheTimes();
DefaultMetaDataRegistry service = new DefaultMetaDataRegistry();
service.setRootMetaDataUrl( prefixUrl );
service.setCoreSelector( new CoreSelector( populatorRegistry ) );
Map<String,Class<?>> typeMappings = new HashMap<String, Class<?>>();
typeMappings.put( "album", Album.class );
service.setTypeMappings( typeMappings );
MetadataLinkListener metadataLinkListener = new MetadataLinkListener();
metadataLinkListener.setMetaDataRegistry( service );
ResultTraverser traverser = new ResultTraverser();
YogaRequestContext requestContext = new YogaRequestContext( fileExtension,
new DummyHttpServletRequest(), new DummyHttpServletResponse(), metadataLinkListener );
Map<String, Object> objectTree = doTraverse( signOfTheTimes, ":", traverser, requestContext );
Map<String,String> metadataMap = (Map<String,String>) objectTree.get( "metadata" );
String metadataHref = prefixUrl + "album." + fileExtension;
Assert.assertEquals( metadataHref, metadataMap.get( "href" ) );
}
#location 27
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public JimfsFileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
checkArgument(uri.getScheme().equalsIgnoreCase(SCHEME),
"uri (%s) scheme must be '%s'", uri, SCHEME);
checkArgument(env.get(CONFIG_KEY) instanceof JimfsConfiguration,
"env map (%s) must contain key '%s' mapped to an instance of JimfsConfiguration",
env, CONFIG_KEY);
JimfsConfiguration config = (JimfsConfiguration) env.get(CONFIG_KEY);
JimfsFileSystem fileSystem = FileSystemInitializer.createFileSystem(this, uri, config);
if (fileSystems.putIfAbsent(uri, fileSystem) != null) {
throw new FileSystemAlreadyExistsException(uri.toString());
}
return fileSystem;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public JimfsFileSystem newFileSystem(URI uri, Map<String, ?> env) {
checkArgument(uri.getScheme().equalsIgnoreCase(SCHEME),
"uri (%s) scheme must be '%s'", uri, SCHEME);
checkArgument(env.get(CONFIG_KEY) instanceof JimfsConfiguration,
"env map (%s) must contain key '%s' mapped to an instance of JimfsConfiguration",
env, CONFIG_KEY);
JimfsConfiguration config = (JimfsConfiguration) env.get(CONFIG_KEY);
JimfsFileSystem fileSystem = new JimfsFileSystem(this, uri, config);
if (fileSystems.putIfAbsent(uri, fileSystem) != null) {
throw new FileSystemAlreadyExistsException(uri.toString());
}
return fileSystem;
}
#location 9
#vulnerability type RESOURCE_LEAK |
#fixed code
public void init() throws DBException
{
if ( (getProperties().getProperty("debug")!=null) &&
(getProperties().getProperty("debug").compareTo("true")==0) )
{
_debug=true;
}
if (getProperties().containsKey("clientbuffering"))
{
_clientSideBuffering = Boolean.parseBoolean(getProperties().getProperty("clientbuffering"));
}
if (getProperties().containsKey("writebuffersize"))
{
_writeBufferSize = Long.parseLong(getProperties().getProperty("writebuffersize"));
}
if ("false".equals(getProperties().getProperty("hbase.usepagefilter", "true"))) {
_usePageFilter = false;
}
if ("kerberos".equalsIgnoreCase(config.get("hbase.security.authentication"))) {
config.set("hadoop.security.authentication", "Kerberos");
UserGroupInformation.setConfiguration(config);
}
if ( (getProperties().getProperty("principal")!=null) && (getProperties().getProperty("keytab")!=null) ){
try {
UserGroupInformation.loginUserFromKeytab(getProperties().getProperty("principal"), getProperties().getProperty("keytab"));
} catch (IOException e) {
System.err.println("Keytab file is not readable or not found");
throw new DBException(e);
}
}
try {
_hConn = HConnectionManager.createConnection(config);
} catch (IOException e) {
System.err.println("Connection to HBase was not successful");
throw new DBException(e);
}
_columnFamily = getProperties().getProperty("columnfamily");
if (_columnFamily == null)
{
System.err.println("Error, must specify a columnfamily for HBase table");
throw new DBException("No columnfamily specified");
}
_columnFamilyBytes = Bytes.toBytes(_columnFamily);
// Terminate right now if table does not exist, since the client
// will not propagate this error upstream once the workload
// starts.
String table = com.yahoo.ycsb.workloads.CoreWorkload.table;
try
{
HTableInterface ht = _hConn.getTable(table);
ht.getTableDescriptor();
}
catch (IOException e)
{
throw new DBException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void init() throws DBException
{
if ( (getProperties().getProperty("debug")!=null) &&
(getProperties().getProperty("debug").compareTo("true")==0) )
{
_debug=true;
}
if (getProperties().containsKey("clientbuffering"))
{
_clientSideBuffering = Boolean.parseBoolean(getProperties().getProperty("clientbuffering"));
}
if (getProperties().containsKey("writebuffersize"))
{
_writeBufferSize = Long.parseLong(getProperties().getProperty("writebuffersize"));
}
if ("false".equals(getProperties().getProperty("hbase.usepagefilter", "true"))) {
_usePageFilter = false;
}
_columnFamily = getProperties().getProperty("columnfamily");
if (_columnFamily == null)
{
System.err.println("Error, must specify a columnfamily for HBase table");
throw new DBException("No columnfamily specified");
}
_columnFamilyBytes = Bytes.toBytes(_columnFamily);
// Terminate right now if table does not exist, since the client
// will not propagate this error upstream once the workload
// starts.
String table = com.yahoo.ycsb.workloads.CoreWorkload.table;
try
{
HTable ht = new HTable(config, table);
ht.getTableDescriptor();
}
catch (IOException e)
{
throw new DBException(e);
}
}
#location 36
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public int scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
MongoCursor<Document> cursor = null;
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document scanRange = new Document("$gte", startkey);
Document query = new Document("_id", scanRange);
Document sort = new Document("_id", INCLUDE);
Document projection = null;
if (fields != null) {
projection = new Document();
for (String fieldName : fields) {
projection.put(fieldName, INCLUDE);
}
}
cursor = collection.find(query)
.projection(projection).sort(sort).limit(recordcount).iterator();
if (!cursor.hasNext()) {
System.err.println("Nothing found in scan for key " + startkey);
return 1;
}
while (cursor.hasNext()) {
HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>();
Document obj = cursor.next();
fillMap(resultMap, obj);
result.add(resultMap);
}
return 0;
}
catch (Exception e) {
System.err.println(e.toString());
return 1;
}
finally {
if (cursor != null) {
cursor.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public int scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
MongoCursor<Document> cursor = null;
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document scanRange = new Document("$gte", startkey);
Document query = new Document("_id", scanRange);
Document sort = new Document("_id", INCLUDE);
Document projection = null;
if (fields != null) {
projection = new Document();
for (String fieldName : fields) {
projection.put(fieldName, INCLUDE);
}
}
cursor = collection.withReadPreference(readPreference).find(query)
.projection(projection).sort(sort).limit(recordcount).iterator();
if (!cursor.hasNext()) {
System.err.println("Nothing found in scan for key " + startkey);
return 1;
}
while (cursor.hasNext()) {
HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>();
Document obj = cursor.next();
fillMap(resultMap, obj);
result.add(resultMap);
}
return 0;
}
catch (Exception e) {
System.err.println(e.toString());
return 1;
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public boolean doTransaction(DB db, Object threadstate) {
String operation = operationchooser.nextString();
if (operation == null) {
return false;
}
switch (operation) {
case "UPDATE":
doTransactionUpdate(db);
break;
case "INSERT":
doTransactionInsert(db);
break;
case "DELETE":
doTransactionDelete(db);
break;
default:
doTransactionRead(db);
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public boolean doTransaction(DB db, Object threadstate) {
switch (operationchooser.nextString()) {
case "UPDATE":
doTransactionUpdate(db);
break;
case "INSERT":
doTransactionInsert(db);
break;
case "DELETE":
doTransactionDelete(db);
break;
default:
doTransactionRead(db);
}
return true;
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public Status delete(String table, String key) {
if (debug) {
System.out.println("Doing delete for key: " + key);
}
setTable(table);
final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder()
.setRowKey(ByteString.copyFromUtf8(key))
.setTableNameBytes(ByteStringer.wrap(lastTableBytes));
rowMutation.addMutationsBuilder().setDeleteFromRow(
DeleteFromRow.getDefaultInstance());
try {
if (clientSideBuffering) {
bulkMutation.add(rowMutation.build());
} else {
client.mutateRow(rowMutation.build());
}
return Status.OK;
} catch (RuntimeException e) {
System.err.println("Failed to delete key: " + key + " " + e.getMessage());
return Status.ERROR;
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Status delete(String table, String key) {
if (debug) {
System.out.println("Doing delete for key: " + key);
}
setTable(table);
final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder()
.setRowKey(ByteString.copyFromUtf8(key))
.setTableNameBytes(ByteStringer.wrap(lastTableBytes));
rowMutation.addMutationsBuilder().setDeleteFromRow(
DeleteFromRow.getDefaultInstance());
try {
if (clientSideBuffering) {
asyncExecutor.mutateRowAsync(rowMutation.build());
} else {
client.mutateRow(rowMutation.build());
}
return Status.OK;
} catch (ServiceException e) {
System.err.println("Failed to delete key: " + key + " " + e.getMessage());
return Status.ERROR;
} catch (InterruptedException e) {
System.err.println("Interrupted while delete key: " + key + " "
+ e.getMessage());
Thread.currentThread().interrupt();
return Status.ERROR; // never get here, but lets make the compiler happy
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public int insert(String table, String key,
HashMap<String, ByteIterator> values) {
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document toInsert = new Document("_id", key);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
toInsert.put(entry.getKey(), entry.getValue().toArray());
}
bulkInserts.add(toInsert);
if (bulkInserts.size() == batchSize) {
collection.insertMany(bulkInserts, INSERT_MANY_OPTIONS);
bulkInserts.clear();
}
return 0;
}
catch (Exception e) {
System.err.println("Exception while trying bulk insert with "
+ bulkInserts.size());
e.printStackTrace();
return 1;
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public int insert(String table, String key,
HashMap<String, ByteIterator> values) {
try {
MongoCollection<Document> collection = database
.getCollection(table);
Document toInsert = new Document("_id", key);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
toInsert.put(entry.getKey(), entry.getValue().toArray());
}
bulkInserts.add(toInsert);
if (bulkInserts.size() == batchSize) {
collection.withWriteConcern(writeConcern)
.insertMany(bulkInserts, INSERT_MANY_OPTIONS);
bulkInserts.clear();
}
return 0;
}
catch (Exception e) {
System.err.println("Exception while trying bulk insert with "
+ bulkInserts.size());
e.printStackTrace();
return 1;
}
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p = new BufferedMutatorParams(tName);
p.writeBufferSize(writeBufferSize);
this.bufferedMutator = connection.getBufferedMutator(p);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void getHTable(String table) throws IOException {
final TableName tName = TableName.valueOf(table);
synchronized (CONNECTION_LOCK) {
this.currentTable = connection.getTable(tName);
if (clientSideBuffering) {
final BufferedMutatorParams p = new BufferedMutatorParams(tName);
p.writeBufferSize(writeBufferSize);
this.bufferedMutator = connection.getBufferedMutator(p);
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void writeTo( Writer writer, WriterConfig config ) throws IOException {
if( writer == null ) {
throw new NullPointerException( "writer is null" );
}
if( config == null ) {
throw new NullPointerException( "config is null" );
}
WritingBuffer buffer = new WritingBuffer( writer, 128 );
write( config.createWriter( buffer ) );
buffer.flush();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void writeTo( Writer writer, WriterConfig config ) throws IOException {
WritingBuffer buffer = new WritingBuffer( writer, 128 );
write( config == null ? new JsonWriter( buffer ) : config.createWriter( buffer ) );
buffer.flush();
}
#location 4
#vulnerability type RESOURCE_LEAK |
#fixed code
public String save() {
Command<Dataverse> cmd = null;
//TODO change to Create - for now the page is expecting INFO instead.
if (dataverse.getId() == null){
dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null);
cmd = new CreateDataverseCommand(dataverse, session.getUser());
} else {
cmd = new UpdateDataverseCommand(dataverse, facets.getTarget(), session.getUser());
}
try {
dataverse = commandEngine.submit(cmd);
userNotificationService.sendNotification(session.getUser(), dataverse.getCreateDate(), Type.CREATEDV, dataverse.getId());
editMode = null;
} catch (CommandException ex) {
JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage());
return null;
}
return "/dataverse.xhtml?id=" + dataverse.getId() +"&faces-redirect=true";
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public String save() {
Command<Dataverse> cmd = null;
if ( editMode == EditMode.INFO ) {
dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null);
cmd = new CreateDataverseCommand(dataverse, session.getUser());
} else if ( editMode == EditMode.SETUP ) {
cmd = new UpdateDataverseCommand(dataverse, facets.getTarget(), session.getUser());
}
try {
dataverse = commandEngine.submit(cmd);
userNotificationService.sendNotification(session.getUser(), dataverse.getCreateDate(), Type.CREATEDV, dataverse.getId());
editMode = null;
} catch (CommandException ex) {
JH.addMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage());
return null;
}
return "/dataverse.xhtml?id=" + dataverse.getId() +"&faces-redirect=true";
}
#location 13
#vulnerability type NULL_DEREFERENCE |
#fixed code
private List<RuntimeException> validateModelWithDependencies(
Executable executable,
Map<String, Executable> dependencies,
Set<Executable> verifiedExecutables,
List<RuntimeException> errors) {
//validate that all required & non private parameters with no default value of a reference are provided
if(!SlangTextualKeys.FLOW_TYPE.equals(executable.getType()) || verifiedExecutables.contains(executable)){
return errors;
}
verifiedExecutables.add(executable);
Flow flow = (Flow) executable;
Collection<Step> steps = flow.getWorkflow().getSteps();
Set<Executable> flowReferences = new HashSet<>();
for (Step step : steps) {
String refId = step.getRefId();
Executable reference = dependencies.get(refId);
try {
validateMandatoryInputsAreWired(flow, step, reference);
validateStepInputNamesDifferentFromDependencyOutputNames(flow, step, reference);
validateDependenciesResultsHaveMatchingNavigations(executable, refId, step, reference);
} catch (RuntimeException e) {
errors.add(e);
}
flowReferences.add(reference);
}
for (Executable reference : flowReferences) {
validateModelWithDependencies(reference, dependencies, verifiedExecutables, errors);
}
return errors;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private List<RuntimeException> validateModelWithDependencies(
Executable executable,
Map<String, Executable> dependencies,
Set<Executable> verifiedExecutables,
List<RuntimeException> errors) {
//validate that all required & non private parameters with no default value of a reference are provided
if(!SlangTextualKeys.FLOW_TYPE.equals(executable.getType()) || verifiedExecutables.contains(executable)){
return errors;
}
verifiedExecutables.add(executable);
Flow flow = (Flow) executable;
Collection<Step> steps = flow.getWorkflow().getSteps();
Set<Executable> flowReferences = new HashSet<>();
for (Step step : steps) {
String refId = step.getRefId();
Executable reference = dependencies.get(refId);
List<String> mandatoryInputNames = getMandatoryInputNames(reference);
List<String> stepInputNames = getStepInputNames(step);
List<String> inputsNotWired = getInputsNotWired(mandatoryInputNames, stepInputNames);
try {
validateInputNamesEmpty(inputsNotWired, flow, step, reference);
validateStepInputNamesDifferentFromDependencyOutputNames(flow, step, reference);
validateDependenciesResultsHaveMatchingNavigations(executable, refId, step, reference);
} catch (RuntimeException e) {
errors.add(e);
}
flowReferences.add(reference);
}
for (Executable reference : flowReferences) {
validateModelWithDependencies(reference, dependencies, verifiedExecutables, errors);
}
return errors;
}
#location 19
#vulnerability type NULL_DEREFERENCE |
#fixed code
public List<Value> bindAsyncLoopList(
AsyncLoopStatement asyncLoopStatement,
Context flowContext,
Set<SystemProperty> systemProperties,
String nodeName) {
Validate.notNull(asyncLoopStatement, "async loop statement cannot be null");
Validate.notNull(flowContext, "flow context cannot be null");
Validate.notNull(systemProperties, "system properties cannot be null");
Validate.notNull(nodeName, "node name cannot be null");
List<Value> result = new ArrayList<>();
try {
Value evalResult = scriptEvaluator.evalExpr(asyncLoopStatement.getExpression(), flowContext.getImmutableViewOfVariables(), systemProperties);
if (evalResult != null && evalResult.get() != null) {
//noinspection unchecked
for (Serializable serializable : ((List<Serializable>)evalResult.get())) {
Value value = ValueFactory.create(serializable, evalResult.isSensitive());
result.add(value);
}
}
} catch (Throwable t) {
throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, t.getMessage()), t);
}
if (CollectionUtils.isEmpty(result)) {
throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, "expression is empty"));
}
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public List<Value> bindAsyncLoopList(
AsyncLoopStatement asyncLoopStatement,
Context flowContext,
Set<SystemProperty> systemProperties,
String nodeName) {
Validate.notNull(asyncLoopStatement, "async loop statement cannot be null");
Validate.notNull(flowContext, "flow context cannot be null");
Validate.notNull(systemProperties, "system properties cannot be null");
Validate.notNull(nodeName, "node name cannot be null");
List<Value> result = new ArrayList<>();
try {
Value evalResult = scriptEvaluator.evalExpr(asyncLoopStatement.getExpression(), flowContext.getImmutableViewOfVariables(), systemProperties);
if (evalResult.get() != null) {
//noinspection unchecked
for (Serializable serializable : ((List<Serializable>)evalResult.get())) {
Value value = serializable instanceof Value ? (Value)serializable : ValueFactory.create(serializable, evalResult.isSensitive());
result.add(value);
}
}
} catch (Throwable t) {
throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, t.getMessage()), t);
}
if (CollectionUtils.isEmpty(result)) {
throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, "expression is empty"));
}
return result;
}
#location 14
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void beginTask(@Param(ScoreLangConstants.TASK_INPUTS_KEY) List<Input> taskInputs,
@Param(ScoreLangConstants.LOOP_KEY) LoopStatement loop,
@Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
@Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
@Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName,
@Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID,
@Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId,
@Param(ScoreLangConstants.REF_ID) String refId) {
try {
startStepExecutionPathCalc(runEnv);
runEnv.removeCallArguments();
runEnv.removeReturnValues();
Context flowContext = runEnv.getStack().popContext();
Map<String, Serializable> flowVariables = flowContext.getImmutableViewOfVariables();
fireEvent(executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_INPUT_START, "Task inputs start Binding",
Pair.of(LanguageEventData.BOUND_INPUTS,(Serializable)retrieveInputs(taskInputs)),
Pair.of( LanguageEventData.levelName.TASK_NAME.name(), nodeName));
//loops
if (loopStatementExist(loop)) {
LoopCondition loopCondition = loopsBinding.getOrCreateLoopCondition(loop, flowContext, nodeName);
if (!loopCondition.hasMore()) {
runEnv.putNextStepPosition(nextStepId);
runEnv.getStack().pushContext(flowContext);
return;
}
if (loopCondition instanceof ForLoopCondition) {
ForLoopCondition forLoopCondition = (ForLoopCondition) loopCondition;
if (loop instanceof ListForLoopStatement) {
// normal iteration
String varName = ((ListForLoopStatement) loop).getVarName();
loopsBinding.incrementListForLoop(varName, flowContext, forLoopCondition);
} else {
// map iteration
MapForLoopStatement mapForLoopStatement = (MapForLoopStatement) loop;
String keyName = mapForLoopStatement.getKeyName();
String valueName = mapForLoopStatement.getValueName();
loopsBinding.incrementMapForLoop(keyName, valueName, flowContext, forLoopCondition);
}
}
}
// Map<String, Serializable> flowVariables = flowContext.getImmutableViewOfVariables();
Map<String, Serializable> operationArguments = inputsBinding.bindInputs(taskInputs, flowVariables, runEnv.getSystemProperties());
//todo: hook
sendBindingInputsEvent(taskInputs, operationArguments, runEnv, executionRuntimeServices, "Task inputs resolved",
nodeName, LanguageEventData.levelName.TASK_NAME);
updateCallArgumentsAndPushContextToStack(runEnv, flowContext, operationArguments);
// request the score engine to switch to the execution plan of the given ref
requestSwitchToRefExecutableExecutionPlan(runEnv, executionRuntimeServices, RUNNING_EXECUTION_PLAN_ID, refId, nextStepId);
// set the start step of the given ref as the next step to execute (in the new running execution plan that will be set)
runEnv.putNextStepPosition(executionRuntimeServices.getSubFlowBeginStep(refId));
// runEnv.getExecutionPath().down();
} catch (RuntimeException e) {
logger.error("There was an error running the begin task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage());
throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void beginTask(@Param(ScoreLangConstants.TASK_INPUTS_KEY) List<Input> taskInputs,
@Param(ScoreLangConstants.LOOP_KEY) LoopStatement loop,
@Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv,
@Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices,
@Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName,
@Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID,
@Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId,
@Param(ScoreLangConstants.REF_ID) String refId) {
try {
runEnv.getExecutionPath().forward();
runEnv.removeCallArguments();
runEnv.removeReturnValues();
Context flowContext = runEnv.getStack().popContext();
//loops
if (loopStatementExist(loop)) {
LoopCondition loopCondition = loopsBinding.getOrCreateLoopCondition(loop, flowContext, nodeName);
if (!loopCondition.hasMore()) {
runEnv.putNextStepPosition(nextStepId);
runEnv.getStack().pushContext(flowContext);
return;
}
if (loopCondition instanceof ForLoopCondition) {
ForLoopCondition forLoopCondition = (ForLoopCondition) loopCondition;
if (loop instanceof ListForLoopStatement) {
// normal iteration
String varName = ((ListForLoopStatement) loop).getVarName();
loopsBinding.incrementListForLoop(varName, flowContext, forLoopCondition);
} else {
// map iteration
MapForLoopStatement mapForLoopStatement = (MapForLoopStatement) loop;
String keyName = mapForLoopStatement.getKeyName();
String valueName = mapForLoopStatement.getValueName();
loopsBinding.incrementMapForLoop(keyName, valueName, flowContext, forLoopCondition);
}
}
}
Map<String, Serializable> flowVariables = flowContext.getImmutableViewOfVariables();
Map<String, Serializable> operationArguments = inputsBinding.bindInputs(taskInputs, flowVariables, runEnv.getSystemProperties());
//todo: hook
sendBindingInputsEvent(taskInputs, operationArguments, runEnv, executionRuntimeServices, "Task inputs resolved",
nodeName, LanguageEventData.levelName.TASK_NAME);
updateCallArgumentsAndPushContextToStack(runEnv, flowContext, operationArguments);
// request the score engine to switch to the execution plan of the given ref
requestSwitchToRefExecutableExecutionPlan(runEnv, executionRuntimeServices, RUNNING_EXECUTION_PLAN_ID, refId, nextStepId);
// set the start step of the given ref as the next step to execute (in the new running execution plan that will be set)
runEnv.putNextStepPosition(executionRuntimeServices.getSubFlowBeginStep(refId));
runEnv.getExecutionPath().down();
} catch (RuntimeException e) {
logger.error("There was an error running the begin task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage());
throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e);
}
}
#location 18
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
// check uncommitted changes
checkUncommittedChanges();
// git for-each-ref --format='%(refname:short)' refs/heads/hotfix/*
final String hotfixBranches = gitFindBranches(gitFlowConfig
.getHotfixBranchPrefix());
if (StringUtils.isBlank(hotfixBranches)) {
throw new MojoFailureException("There is no hotfix branches.");
}
String[] branches = hotfixBranches.split("\\r?\\n");
List<String> numberedList = new ArrayList<String>();
StringBuilder str = new StringBuilder("Hotfix branches:")
.append(LS);
for (int i = 0; i < branches.length; i++) {
str.append((i + 1) + ". " + branches[i] + LS);
numberedList.add(String.valueOf(i + 1));
}
str.append("Choose hotfix branch to finish");
String hotfixNumber = null;
try {
while (StringUtils.isBlank(hotfixNumber)) {
hotfixNumber = prompter
.prompt(str.toString(), numberedList);
}
} catch (PrompterException e) {
getLog().error(e);
}
String hotfixBranchName = null;
if (hotfixNumber != null) {
int num = Integer.parseInt(hotfixNumber);
hotfixBranchName = branches[num - 1];
}
if (StringUtils.isBlank(hotfixBranchName)) {
throw new MojoFailureException(
"Hotfix name to finish is blank.");
}
// git checkout hotfix/...
gitCheckout(hotfixBranchName);
if (!skipTestProject) {
// mvn clean test
mvnCleanTest();
}
// git checkout master
gitCheckout(gitFlowConfig.getProductionBranch());
// git merge --no-ff hotfix/...
gitMergeNoff(hotfixBranchName);
if (!skipTag) {
String tagVersion = getCurrentProjectVersion();
if (tychoBuild && ArtifactUtils.isSnapshot(tagVersion)) {
tagVersion = tagVersion.replace("-"
+ Artifact.SNAPSHOT_VERSION, "");
}
// git tag -a ...
gitTag(gitFlowConfig.getVersionTagPrefix() + tagVersion,
"tagging hotfix");
}
// check whether release branch exists
// git for-each-ref --count=1 --format="%(refname:short)"
// refs/heads/release/*
final String releaseBranch = executeGitCommandReturn(
"for-each-ref", "--count=1",
"--format=\"%(refname:short)\"", "refs/heads/"
+ gitFlowConfig.getReleaseBranchPrefix() + "*");
// if release branch exists merge hotfix changes into it
if (StringUtils.isNotBlank(releaseBranch)) {
// git checkout release
gitCheckout(releaseBranch);
// git merge --no-ff hotfix/...
gitMergeNoff(hotfixBranchName);
} else {
// git checkout develop
gitCheckout(gitFlowConfig.getDevelopmentBranch());
// git merge --no-ff hotfix/...
gitMergeNoff(hotfixBranchName);
// get current project version from pom
final String currentVersion = getCurrentProjectVersion();
String nextSnapshotVersion = null;
// get next snapshot version
try {
final DefaultVersionInfo versionInfo = new DefaultVersionInfo(
currentVersion);
nextSnapshotVersion = versionInfo.getNextVersion()
.getSnapshotVersionString();
} catch (VersionParseException e) {
if (getLog().isDebugEnabled()) {
getLog().debug(e);
}
}
if (StringUtils.isBlank(nextSnapshotVersion)) {
throw new MojoFailureException(
"Next snapshot version is blank.");
}
// mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false
mvnSetVersions(nextSnapshotVersion);
// git commit -a -m updating for next development version
gitCommit("updating for next development version");
}
if (installProject) {
// mvn clean install
mvnCleanInstall();
}
if (!keepBranch) {
// git branch -d hotfix/...
gitBranchDelete(hotfixBranchName);
}
} catch (CommandLineException e) {
getLog().error(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
try {
// check uncommitted changes
checkUncommittedChanges();
// git for-each-ref --format='%(refname:short)' refs/heads/hotfix/*
final String hotfixBranches = gitFindBranches(gitFlowConfig
.getHotfixBranchPrefix());
if (StringUtils.isBlank(hotfixBranches)) {
throw new MojoFailureException("There is no hotfix branches.");
}
String[] branches = hotfixBranches.split("\\r?\\n");
List<String> numberedList = new ArrayList<String>();
StringBuilder str = new StringBuilder("Hotfix branches:")
.append(LS);
for (int i = 0; i < branches.length; i++) {
str.append((i + 1) + ". " + branches[i] + LS);
numberedList.add(String.valueOf(i + 1));
}
str.append("Choose hotfix branch to finish");
String hotfixNumber = null;
try {
while (StringUtils.isBlank(hotfixNumber)) {
hotfixNumber = prompter
.prompt(str.toString(), numberedList);
}
} catch (PrompterException e) {
getLog().error(e);
}
String hotfixBranchName = null;
if (hotfixNumber != null) {
int num = Integer.parseInt(hotfixNumber);
hotfixBranchName = branches[num - 1];
}
if (StringUtils.isBlank(hotfixBranchName)) {
throw new MojoFailureException(
"Hotfix name to finish is blank.");
}
// git checkout hotfix/...
gitCheckout(hotfixBranchName);
if (!skipTestProject) {
// mvn clean test
mvnCleanTest();
}
// git checkout master
gitCheckout(gitFlowConfig.getProductionBranch());
// git merge --no-ff hotfix/...
gitMergeNoff(hotfixBranchName);
if (!skipTag) {
// git tag -a ...
gitTag(gitFlowConfig.getVersionTagPrefix()
+ hotfixBranchName.replaceFirst(
gitFlowConfig.getHotfixBranchPrefix(), ""),
"tagging hotfix");
}
// check whether release branch exists
// git for-each-ref --count=1 --format="%(refname:short)"
// refs/heads/release/*
final String releaseBranch = executeGitCommandReturn(
"for-each-ref", "--count=1",
"--format=\"%(refname:short)\"", "refs/heads/"
+ gitFlowConfig.getReleaseBranchPrefix() + "*");
// if release branch exists merge hotfix changes into it
if (StringUtils.isNotBlank(releaseBranch)) {
// git checkout release
gitCheckout(releaseBranch);
// git merge --no-ff hotfix/...
gitMergeNoff(hotfixBranchName);
} else {
// git checkout develop
gitCheckout(gitFlowConfig.getDevelopmentBranch());
// git merge --no-ff hotfix/...
gitMergeNoff(hotfixBranchName);
// get current project version from pom
final String currentVersion = getCurrentProjectVersion();
String nextSnapshotVersion = null;
// get next snapshot version
try {
final DefaultVersionInfo versionInfo = new DefaultVersionInfo(
currentVersion);
nextSnapshotVersion = versionInfo.getNextVersion()
.getSnapshotVersionString();
} catch (VersionParseException e) {
if (getLog().isDebugEnabled()) {
getLog().debug(e);
}
}
if (StringUtils.isBlank(nextSnapshotVersion)) {
throw new MojoFailureException(
"Next snapshot version is blank.");
}
// mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false
mvnSetVersions(nextSnapshotVersion);
// git commit -a -m updating for next development version
gitCommit("updating for next development version");
}
if (installProject) {
// mvn clean install
mvnCleanInstall();
}
if (!keepBranch) {
// git branch -d hotfix/...
gitBranchDelete(hotfixBranchName);
}
} catch (CommandLineException e) {
getLog().error(e);
}
}
#location 64
#vulnerability type NULL_DEREFERENCE |
#fixed code
private List<Node<T, S>> createChildren() {
List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength());
// reduce allocations by resusing objects
int numChildren = node.childrenLength();
for (int i = 0; i < numChildren; i++) {
Node_ child = node.children(i);
if (child.childrenLength()>0) {
children.add(new NonLeafFlatBuffers<T, S>(child, context, deserializer));
} else {
children.add(new LeafFlatBuffers<T,S>(child, context, deserializer));
}
}
return children;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private List<Node<T, S>> createChildren() {
List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength());
// reduce allocations by resusing objects
int numChildren = node.childrenLength();
for (int i = 0; i < numChildren; i++) {
Node_ child = node.children(i);
children.add(new NonLeafFlatBuffers<T, S>(child, context, deserializer));
}
return children;
}
#location 7
#vulnerability type NULL_DEREFERENCE |
#fixed code
public boolean isInStruct()
{
return currentContainerIndex >= 0 && currentContainer().type == ContainerType.STRUCT;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean isInStruct()
{
return !containers.isEmpty() && currentContainer().type == ContainerType.STRUCT;
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testGetMovieChangesList() throws MovieDbException {
LOG.info("getMovieChangesList");
List<ChangeListItem> result = instance.getChangeList(MethodBase.MOVIE, null, null, null);
assertFalse("No movie changes.", result.isEmpty());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testGetMovieChangesList() throws MovieDbException {
LOG.info("getMovieChangesList");
TmdbResultsList<ChangedMedia> result = instance.getChangeList(MethodBase.MOVIE, null, null, null);
assertFalse("No movie changes.", result.getResults().isEmpty());
}
#location 4
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void read(String filename){
BufferedReader reader = getReader(filename);
String line = null;
boolean firstline = true;
Coordinate depotCoord = null;
int customerCount=0;
Integer nuOfCustomer = 0;
while((line=readLine(reader))!=null){
String trimedLine = line.trim();
if(trimedLine.startsWith("//")) continue;
String[] tokens = trimedLine.split("\\s+");
if(firstline){
nuOfCustomer=Integer.parseInt(tokens[0]);
customerCount=0;
firstline=false;
}
else if(customerCount<=nuOfCustomer) {
if(customerCount == 0){
depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]));
}
else{
Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0]).addSizeDimension(0, Integer.parseInt(tokens[3]));
serviceBuilder.setCoord(Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])));
vrpBuilder.addJob(serviceBuilder.build());
}
customerCount++;
}
else if(trimedLine.startsWith("v")){
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_"+tokens[1]).addCapacityDimension(0, Integer.parseInt(tokens[2]));
int nuOfVehicles = 1;
if(vrphType.equals(VrphType.FSMF)){
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
}
else if(vrphType.equals(VrphType.FSMFD)){
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
if(tokens.length > 4){
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
else if(vrphType.equals(VrphType.FSMD)){
if(tokens.length > 4){
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
else if(vrphType.equals(VrphType.HVRPD)){
if(tokens.length > 4){
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
nuOfVehicles = Integer.parseInt(tokens[5]);
vrpBuilder.setFleetSize(FleetSize.FINITE);
vrpBuilder.addPenaltyVehicles(5.0, 5000);
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
else if (vrphType.equals(VrphType.HVRPFD)){
if(tokens.length > 4){
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
nuOfVehicles = Integer.parseInt(tokens[5]);
vrpBuilder.setFleetSize(FleetSize.FINITE);
vrpBuilder.addPenaltyVehicles(5.0, 5000);
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
for(int i=0;i<nuOfVehicles;i++){
VehicleTypeImpl type = typeBuilder.build();
Vehicle vehicle = VehicleImpl.Builder.newInstance("vehicle_"+tokens[1]+"_"+i)
.setStartLocationCoordinate(depotCoord).setType(type).build();
vrpBuilder.addVehicle(vehicle);
}
}
}
closeReader(reader);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void read(String filename){
BufferedReader reader = getReader(filename);
String line = null;
boolean firstline = true;
Coordinate depotCoord = null;
int customerCount=0;
Integer nuOfCustomer = 0;
while((line=readLine(reader))!=null){
String trimedLine = line.trim();
if(trimedLine.startsWith("//")) continue;
String[] tokens = trimedLine.split("\\s+");
if(firstline){
nuOfCustomer=Integer.parseInt(tokens[0]);
customerCount=0;
firstline=false;
}
else if(customerCount<=nuOfCustomer) {
if(customerCount == 0){
depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]));
}
else{
Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0], Integer.parseInt(tokens[3]));
serviceBuilder.setCoord(Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])));
vrpBuilder.addJob(serviceBuilder.build());
}
customerCount++;
}
else if(trimedLine.startsWith("v")){
VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_"+tokens[1], Integer.parseInt(tokens[2]));
int nuOfVehicles = 1;
if(vrphType.equals(VrphType.FSMF)){
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
}
else if(vrphType.equals(VrphType.FSMFD)){
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
if(tokens.length > 4){
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
else if(vrphType.equals(VrphType.FSMD)){
if(tokens.length > 4){
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
else if(vrphType.equals(VrphType.HVRPD)){
if(tokens.length > 4){
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
nuOfVehicles = Integer.parseInt(tokens[5]);
vrpBuilder.setFleetSize(FleetSize.FINITE);
vrpBuilder.addPenaltyVehicles(5.0, 5000);
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
else if (vrphType.equals(VrphType.HVRPFD)){
if(tokens.length > 4){
typeBuilder.setFixedCost(Double.parseDouble(tokens[3]));
typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4]));
nuOfVehicles = Integer.parseInt(tokens[5]);
vrpBuilder.setFleetSize(FleetSize.FINITE);
vrpBuilder.addPenaltyVehicles(5.0, 5000);
}
else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance");
}
for(int i=0;i<nuOfVehicles;i++){
VehicleTypeImpl type = typeBuilder.build();
Vehicle vehicle = VehicleImpl.Builder.newInstance("vehicle_"+tokens[1]+"_"+i)
.setLocationCoord(depotCoord).setType(type).build();
vrpBuilder.addVehicle(vehicle);
}
}
}
closeReader(reader);
}
#location 16
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testStatesOfAct1(){
states.informInsertionStarts(Arrays.asList(vehicleRoute), null);
assertEquals(10.0, states.getActivityState(act1, StateFactory.COSTS).toDouble(),0.05);
assertEquals(5.0, states.getActivityState(act1, StateFactory.LOAD).toDouble(),0.05);
assertEquals(20.0, states.getActivityState(act1, StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testStatesOfAct1(){
states.informInsertionStarts(Arrays.asList(vehicleRoute), null);
assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateFactory.COSTS).toDouble(),0.05);
assertEquals(5.0, states.getActivityState(tour.getActivities().get(0), StateFactory.LOAD).toDouble(),0.05);
// assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateTypes.EARLIEST_OPERATION_START_TIME).toDouble(),0.05);
assertEquals(20.0, states.getActivityState(tour.getActivities().get(0), StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05);
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
public HttpResponse execute() throws Exception {
StringBuilder requestBody = new StringBuilder();
if (request.getEntity() != null) {
String content = ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString(request.getEntity());
requestBody.append(content);
} else if (request.hasJson()) {
requestBody.append(request.getJson());
}
try {
connection.setRequestMethod(request.getMethod().name());
if (requestBody.length() > 0) {
System.out.println(requestBody.toString());
connection.setDoOutput(true);
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(requestBody.toString().getBytes());
out.flush();
}
byte[] data = ByteStreams.toByteArray(connection.getInputStream());
System.out.println(new String(data));
return HttpResponseImpl.wrap(connection.getHeaderFields(),
connection.getResponseCode(), connection.getResponseMessage(),
data);
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
} finally {
connection.disconnect();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public HttpResponse execute() throws Exception {
StringBuilder requestBody = new StringBuilder();
if (request.getEntity() != null) {
String content = ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString(request.getEntity());
requestBody.append(content);
} else if (request.hasJson()) {
requestBody.append(request.getJson());
}
StringBuilder contentBuilder = new StringBuilder();
BufferedReader in = null;
try {
connection.setRequestMethod(request.getMethod().name());
if (requestBody.length() > 0) {
System.out.println(requestBody.toString());
connection.setDoOutput(true);
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(requestBody.toString().getBytes());
out.flush();
}
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
contentBuilder.append(inputLine);
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
in = new BufferedReader(new InputStreamReader(
connection.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
contentBuilder.append(inputLine);
}
} finally {
if (in != null) {
in.close();
}
}
HttpResponseImpl responseImpl
= HttpResponseImpl.wrap(connection.getHeaderFields(),
connection.getResponseCode(), connection.getResponseMessage(),
connection.getInputStream());
connection.disconnect();
return responseImpl;
}
#location 35
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testHelpSet() {
final String expected = "1/1 !help set\n"
+ "!set List / set a sqlline variable\n"
+ "\n"
+ "Variables:\n"
+ "\n"
+ "Variable Value Description\n"
+ "=============== ========== "
+ "==================================================\n"
+ "autoCommit true/false "
+ "Enable/disable automatic transaction commit\n"
+ "autoSave true/false Automatically save preferences\n";
checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK),
containsString(expected));
// Make sure that each variable (autoCommit, autoSave, color, etc.) has a
// line in the output of '!help set'
String help = sqlLine.loc("help-set")
+ sqlLine.loc("variables");
final TreeSet<String> propertyNamesMixed =
Arrays.stream(BuiltInProperty.values())
.map(BuiltInProperty::propertyName)
.collect(Collectors.toCollection(TreeSet::new));
for (String p : propertyNamesMixed) {
assertThat(help, containsString("\n" + p + " "));
}
assertThat(propertyNamesMixed.contains("autoCommit"),
is(true));
assertThat(propertyNamesMixed.contains("autocommit"),
is(false));
assertThat(propertyNamesMixed.contains("trimScripts"),
is(true));
while (help.length() > 0) {
int i = help.indexOf("\n", 1);
if (i < 0) {
break;
}
if (i > 78) {
fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i));
}
help = help.substring(i);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testHelpSet() {
final String expected = "1/1 !help set\n"
+ "!set List / set a sqlline variable\n"
+ "\n"
+ "Variables:\n"
+ "\n"
+ "Variable Value Description\n"
+ "=============== ========== "
+ "==================================================\n"
+ "autoCommit true/false "
+ "Enable/disable automatic transaction commit\n"
+ "autoSave true/false Automatically save preferences\n";
checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK),
containsString(expected));
// Make sure that each variable (autoCommit, autoSave, color, etc.) has a
// line in the output of '!help set'
final SqlLine sqlLine = new SqlLine();
String help = sqlLine.loc("help-set")
+ sqlLine.loc("variables");
final TreeSet<String> propertyNamesMixed =
Arrays.stream(BuiltInProperty.values())
.map(BuiltInProperty::propertyName)
.collect(Collectors.toCollection(TreeSet::new));
for (String p : propertyNamesMixed) {
assertThat(help, containsString("\n" + p + " "));
}
assertThat(propertyNamesMixed.contains("autoCommit"),
is(true));
assertThat(propertyNamesMixed.contains("autocommit"),
is(false));
assertThat(propertyNamesMixed.contains("trimScripts"),
is(true));
while (help.length() > 0) {
int i = help.indexOf("\n", 1);
if (i < 0) {
break;
}
if (i > 78) {
fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i));
}
help = help.substring(i);
}
}
#location 21
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testSave() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String testSqllinePropertiesFile = "test.sqlline.properties";
try {
SqlLine.Status status = begin(sqlLine, os, false,
"--propertiesFile=" + testSqllinePropertiesFile, "-e", "!save");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
assertThat(os.toString("UTF8"),
allOf(containsString("Saving preferences to"),
not(containsString("Saving to /dev/null not supported"))));
os.reset();
sqlLine.runCommands(dc, "!set");
assertThat(os.toString("UTF8"),
allOf(containsString("autoCommit"),
not(containsString("Unknown property:"))));
os.reset();
Files.delete(Paths.get(testSqllinePropertiesFile));
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testSave() {
final SqlLine beeLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
SqlLine.Status status = begin(beeLine, os, false,
"-e", "!save");
assertThat(status, equalTo(SqlLine.Status.OK));
final DispatchCallback dc = new DispatchCallback();
assertThat(os.toString("UTF8"),
containsString("Saving preferences to"));
os.reset();
beeLine.runCommands(dc, "!set");
assertThat(os.toString("UTF8"),
allOf(containsString("autoCommit"),
not(containsString("Unknown property:"))));
os.reset();
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta,
@Mocked final JDBCResultSet resultSet) {
try {
new Expectations() {
{
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductName();
result = "hsqldb";
// prevent calls to functions that also call resultSet.next
meta.getSQLKeywords();
result = "";
// prevent calls to functions that also call resultSet.next
meta.getDatabaseProductVersion();
result = "1.0";
// Generate an exception on a call to resultSet.next
resultSet.next();
result = new SQLException("Generated Exception.");
}
};
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream =
new PrintStream(os, false, StandardCharsets.UTF_8.name());
sqlLine.setOutputStream(sqllineOutputStream);
sqlLine.setErrorStream(sqllineOutputStream);
String[] args = {
"-d",
"org.hsqldb.jdbcDriver",
"-u",
"jdbc:hsqldb:res:scott",
"-n",
"SCOTT",
"-p",
"TIGER"
};
DispatchCallback callback = new DispatchCallback();
sqlLine.initArgs(args, callback);
// If sqlline is not initialized, handleSQLException will print
// the entire stack trace.
// To prevent that, forcibly set init to true.
FieldReflection.setFieldValue(
sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true);
sqlLine.getConnection();
sqlLine.runCommands(callback,
"CREATE TABLE rsTest ( a int);",
"insert into rsTest values (1);",
"insert into rsTest values (2);",
"select a from rsTest; ");
String output = os.toString("UTF8");
assertThat(output, containsString("Generated Exception"));
} catch (Throwable t) {
// fail
throw new RuntimeException(t);
}
}
#location 25
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void testCommandHandlerOnStartup() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String[] args = {
"-e", "!set maxwidth 80",
"-ch", "sqlline.extensions.HelloWorldCommandHandler"};
begin(sqlLine, os, false, args);
try {
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!test");
output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello test"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testCommandHandlerOnStartup() {
SqlLine sqlLine = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
final String[] args = {
"-e", "!set maxwidth 80",
"-ch", "sqlline.extensions.HelloWorldCommandHandler"};
begin(sqlLine, os, false, args);
try {
sqlLine.runCommands(new DispatchCallback(), "!hello");
String output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!test");
output = os.toString("UTF8");
assertThat(output, containsString("HELLO WORLD"));
os.reset();
sqlLine.runCommands(new DispatchCallback(), "!help hello");
output = os.toString("UTF8");
assertThat(output, containsString("help for hello test"));
sqlLine.runCommands(new DispatchCallback(), "!quit");
assertTrue(sqlLine.isExit());
} catch (Exception e) {
// fail
throw new RuntimeException(e);
}
}
#location 23
#vulnerability type RESOURCE_LEAK |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.