output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
synchronized (EX_PRECACHE) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
else {
length = this.expr.length;
}
}
}
} | #vulnerable code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
synchronized (EX_PRECACHE) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
}
else {
length = this.expr.length;
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object execute(Object ctx, Map tokens) {
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
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
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, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.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 {
ExpressionParser oParser = new ExpressionParser(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++) {
Object listObject = new ExpressionParser(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++) {
tokens.put(alias[i], iters[i].next());
}
if (foreachContext.getCount() != 0) {
sbuf.append(foreachContext.getSeperator());
}
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 register;
}
else {
return sbuf.toString();
}
}
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[node].getRegister();
String template = EX_TEMPLATE_REGISTRY.get(includeRef.getName());
IncludeRefParam[] params = includeRef.getParams();
Map vars = new HashMap(params.length * 2);
for (int i = 0; i < params.length; i++) {
vars.put(params[i].getIdentifier(), MVEL.eval(params[i].getValue(), ctx, tokens));
}
sbuf.append(Interpreter.parse(template, ctx, vars));
}
}
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);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
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, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
case LITERAL:
return new String(expression);
case INCLUDE_BY_REF: {
IncludeRef includeRef = (IncludeRef) nodes[0].getRegister();
String template = EX_TEMPLATE_REGISTRY.get( includeRef.getName() );
IncludeRefParam[] params = includeRef.getParams();
Map vars = new HashMap( params.length );
for ( int i = 0; i < params.length; i++ ) {
vars.put( params[i].getIdentifier(), parse(params[i].getValue(), ctx, tokens));
}
return Interpreter.parse( template, ctx, vars );
}
}
return new String(expression);
}
Object register = null;
StringAppender sbuf = new StringAppender(10);
Node currNode = null;
try {
ExpressionParser oParser = new ExpressionParser(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++ ) {
Object listObject = new ExpressionParser(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++ ) {
tokens.put(alias[i], iters[i].next());
}
if ( foreachContext.getCount() != 0 ) {
sbuf.append( foreachContext.getSeperator() );
}
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 register;
}
else {
return sbuf.toString();
}
}
}
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);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length || scanTo(']'))
throw new PropertyAccessException("unterminated '['");
prop = new String(property, start, cursor++ - start);
if (ctx instanceof Map) {
return ((Map) ctx).get(eval(prop, ctx, variableFactory));
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof Collection) {
int count = (Integer) eval(prop, ctx, variableFactory);
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory));
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
} | #vulnerable code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length)
throw new PropertyAccessException("unterminated '['");
Object item;
if (scanTo(']'))
throw new PropertyAccessException("unterminated '['");
// String ex = new String(property, start, cursor++ - start);
item = eval(new String(property, start, cursor++ - start), ctx, variableFactory);
if (ctx instanceof Map) {
return ((Map) ctx).get(item);
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) item);
}
else if (ctx instanceof Collection) {
int count = (Integer) item;
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) item);
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) item);
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
}
#location 40
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 12
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 126
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompiledExpression _compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astLinkedList = new ASTLinkedList();
boolean firstLA;
pCtx = getParserContext();
try {
if (verifying) {
getParserContext().initializeTables();
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
if (tk.fields == -1) {
astLinkedList.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof Substatement) {
tk.setAccessor(new ExpressionCompiler(tk.getNameAsArray())._compile());
}
/**
* This kludge of code is to handle _compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral() && tk.getLiteralValue() != LITERALS.get("this")) {
if ((tkOp = nextToken()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a _compile-time
* reduction.
*/
if ((tkLA = nextToken()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduceTrinary();
firstLA = true;
/**
* Now we need to check to see if this is actually a continuing reduction.
*/
while ((tkOp2 = nextToken()) != null) {
if (!tkOp2.isOperator(tkOp.getOperator())) {
/**
* We can't continue any further because we are dealing with
* different operators.
*/
astLinkedList.addTokenNode(new LiteralNode(stk.pop()));
astLinkedList.addTokenNode(tkOp2);
break;
}
else if ((tkLA2 = nextToken()) != null
&& tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduceTrinary();
firstLA = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()), tkOp);
if (tkLA2 != null) astLinkedList.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
continue;
}
else {
astLinkedList.addTokenNode(verify(pCtx, tk), verify(pCtx, tkOp));
if (tkLA != null) astLinkedList.addTokenNode(verify(pCtx, tkLA));
continue;
}
}
else {
astLinkedList.addTokenNode(verify(pCtx, tk));
if (tkOp != null) astLinkedList.addTokenNode(verify(pCtx, tkOp));
continue;
}
}
astLinkedList.addTokenNode(verify(pCtx, tk));
}
if (verifying) {
pCtx.processTables();
}
return new CompiledExpression(new ASTArrayList(astLinkedList), getCurrentSourceFileName());
}
catch (Throwable e) {
parserContext.remove();
if (e instanceof RuntimeException) throw (RuntimeException) e;
else {
throw new CompileException(e.getMessage(), e);
}
}
} | #vulnerable code
public CompiledExpression _compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astLinkedList = new ASTLinkedList();
boolean firstLA;
pCtx = getParserContext();
try {
if (verifying) {
// inputs = new LinkedHashSet<String>();
// locals = new LinkedHashSet<String>();
getParserContext().initializeTables();
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
if (tk.fields == -1) {
astLinkedList.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (pCtx.isStrictTypeEnforcement() && tk instanceof AssignmentNode
&& (pCtx.getInputs() == null
|| !pCtx.getInputs().containsKey(tk.getName()))) {
addFatalError("untyped var not permitted in strict-mode: " + tk.getName());
}
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray());
tk.setAccessor(subCompiler._compile());
//
// if (verifying) {
// inputs.addAll(subCompiler.getInputs());
// }
}
/**
* This kludge of code is to handle _compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral() && tk.getLiteralValue() != LITERALS.get("this")) {
if ((tkOp = nextToken()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a _compile-time
* reduction.
*/
if ((tkLA = nextToken()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduceTrinary();
firstLA = true;
/**
* Now we need to check to see if this is actually a continuing reduction.
*/
while ((tkOp2 = nextToken()) != null) {
if (!tkOp2.isOperator(tkOp.getOperator())) {
/**
* We can't continue any further because we are dealing with
* different operators.
*/
astLinkedList.addTokenNode(new LiteralNode(stk.pop()));
astLinkedList.addTokenNode(tkOp2);
break;
}
else if ((tkLA2 = nextToken()) != null
&& tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduceTrinary();
firstLA = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()), tkOp);
if (tkLA2 != null) astLinkedList.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
continue;
}
else {
astLinkedList.addTokenNode(verify(pCtx, tk), verify(pCtx, tkOp));
if (tkLA != null) astLinkedList.addTokenNode(verify(pCtx, tkLA));
continue;
}
}
else {
astLinkedList.addTokenNode(verify(pCtx, tk));
if (tkOp != null) astLinkedList.addTokenNode(verify(pCtx, tkOp));
continue;
}
}
astLinkedList.addTokenNode(verify(pCtx, tk));
}
if (verifying) {
// for (String s : locals) {
// inputs.remove(s);
// }
pCtx.processTables();
}
if (pCtx.isFatalError()) {
parserContext.remove();
throw new CompileException("Failed to _compile: " + pCtx.getErrorList().size() + " compilation error(s)", pCtx.getErrorList());
}
else if (pCtx.isFatalError()) {
parserContext.remove();
throw new CompileException("Failed to _compile: " + pCtx.getErrorList().size() + " compilation error(s)", pCtx.getErrorList());
}
return new CompiledExpression(new ASTArrayList(astLinkedList), getCurrentSourceFileName());
}
catch (Throwable e) {
parserContext.remove();
if (e instanceof RuntimeException) throw (RuntimeException) e;
else {
throw new CompileException(e.getMessage(), e);
}
}
}
#location 31
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 155
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 57
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 51
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Class getWithProperty(Class ctx) {
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
new WithAccessor(root, subset(expr, start, cursor++ - start), ctx, pCtx.isStrictTypeEnforcement());
return ctx;
} | #vulnerable code
private Class getWithProperty(Class ctx) {
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{');
cursor = res[0];
getParserContext().incrementLineCount(res[1]);
new WithAccessor(root, subset(expr, start, cursor++ - start), ctx, pCtx.isStrictTypeEnforcement());
return ctx;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
Object o = MVEL.eval(name, ctx, factory);
if (o instanceof Integer) {
return ~((Integer) o);
}
else {
throw new CompileException("was expecting type: Integer; but found type: " + (o == null ? "null" : o.getClass().getName()));
}
} | #vulnerable code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
return ~((Integer) MVEL.eval(name, ctx, factory));
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
} | #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 143
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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, 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();
if (expr[cursor] == '\n' || expr[cursor] == '\r') {
skipWhitespaceWithLineAccounting();
}
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 createPropertyToken(start, cursor);
}
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 (debugSymbols && (expr[cursor] == '\n' || expr[cursor] == '\r')) {
skipWhitespaceWithLineAccounting();
}
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);
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
}
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;
for (int level = brace; cursor < length; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
if (--brace < level) {
if (lookAhead(1) == '.') {
ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD);
captureToEOT();
return new Union(expr, trimRight(start + 2), cursor, fields, node);
}
else {
return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD);
}
}
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
}
}
}
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 {
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 (_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 (lookAhead(1) == '.') {
InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields);
captureToEOT();
return new Union(expr, start + 1, cursor, fields, n);
}
else {
return new InlineCollectionNode(expr, start, ++cursor, fields);
}
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
} | #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, 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();
if (expr[cursor] == '\n' || expr[cursor] == '\r') {
skipWhitespaceWithLineAccounting();
}
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 && parserContext.get() != null && parserContext.get().hasImports()) {
char[] _subset = subset(expr, start, cursor - start);
int offset;
if ((offset = findFirst('.', _subset)) != -1) {
String iStr = new String(_subset, 0, offset);
if ("this".equals(iStr)) {
lastWasIdentifier = true;
return lastNode = new ThisValDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields);
}
else if (getParserContext().hasImport(iStr)) {
lastWasIdentifier = true;
return lastNode = new LiteralDeepPropertyNode(subset(_subset, offset + 1, _subset.length - offset - 1), fields, getParserContext().getImport(iStr));
}
}
else {
ASTNode node = new ASTNode(_subset, 0, _subset.length, fields);
lastWasIdentifier = node.isIdentifier();
return lastNode = node;
}
}
// return createPropertyToken(expr, start, cursor, fields);
lastWasIdentifier = true;
lastNode = createPropertyToken(start, cursor);
return lastNode;
}
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 (debugSymbols && (expr[cursor] == '\n' || expr[cursor] == '\r')) {
skipWhitespaceWithLineAccounting();
}
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);
if (lastNode instanceof LineLabel) {
getParserContext().getFirstLineLabel().setLineNumber(line);
}
lastWasComment = true;
}
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;
for (int level = brace; cursor < length; cursor++) {
switch (expr[cursor]) {
case'(':
brace++;
break;
case')':
if (--brace < level) {
if (lookAhead(1) == '.') {
ASTNode node = createToken(expr, trimRight(start), (start = cursor++), ASTNode.FOLD);
captureToEOT();
return new Union(expr, trimRight(start + 2), cursor, fields, node);
}
else {
return createToken(expr, trimRight(start), cursor++, ASTNode.FOLD);
}
}
break;
case'\'':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
case'"':
cursor = captureStringLiteral('\'', expr, cursor, length);
break;
}
}
}
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 (_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 (lookAhead(1) == '.') {
InlineCollectionNode n = new InlineCollectionNode(expr, start, start = ++cursor, fields);
captureToEOT();
return new Union(expr, start + 1, cursor, fields, n);
}
else {
return new InlineCollectionNode(expr, start, ++cursor, fields);
}
default:
cursor++;
}
}
return createPropertyToken(start, cursor);
}
#location 318
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) {
// return Math.sqrt(DataConversion.convert(p0.getValue(ctx, variableFactory), Double.class).doubleValue());
for (Method m : Math.class.getMethods()) {
if ("sqrt".equals(m.getName())) {
return m;
}
}
return null;
} | #vulnerable code
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) {
return Math.sqrt(DataConversion.convert(p0.getValue(ctx, variableFactory), Double.class).doubleValue());
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 69
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
synchronized (EX_PRECACHE) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
else {
length = this.expr.length;
}
}
}
} | #vulnerable code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
synchronized (EX_PRECACHE) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
}
else {
length = this.expr.length;
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
} | #vulnerable code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 48
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected boolean hasImport(String name) {
if (pCtx == null) pCtx = getParserContext();
if (pCtx.hasImport(name)) {
return true;
}
else {
VariableResolverFactory vrf = findClassImportResolverFactory(variableFactory);
return vrf != null && vrf.isResolveable(name);
}
} | #vulnerable code
protected boolean hasImport(String name) {
if (getParserContext().hasImport(name)) {
return true;
}
else {
VariableResolverFactory vrf = findClassImportResolverFactory(variableFactory);
return vrf != null && vrf.isResolveable(name);
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length || scanTo(']'))
throw new PropertyAccessException("unterminated '['");
prop = new String(property, start, cursor++ - start);
if (ctx instanceof Map) {
return ((Map) ctx).get(eval(prop, ctx, variableFactory));
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof Collection) {
int count = (Integer) eval(prop, ctx, variableFactory);
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory));
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
} | #vulnerable code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length)
throw new PropertyAccessException("unterminated '['");
Object item;
if (scanTo(']'))
throw new PropertyAccessException("unterminated '['");
// String ex = new String(property, start, cursor++ - start);
item = eval(new String(property, start, cursor++ - start), ctx, variableFactory);
if (ctx instanceof Map) {
return ((Map) ctx).get(item);
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) item);
}
else if (ctx instanceof Collection) {
int count = (Integer) item;
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) item);
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) item);
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
}
#location 25
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 102
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 171
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
try {
if (!((Boolean) MVEL.eval(this.name, ctx, factory))) {
throw new AssertionError("assertion failed in expression: " + new String(this.name));
}
else {
return true;
}
}
catch (ClassCastException e) {
throw new CompileException("assertion does not contain a boolean statement");
}
} | #vulnerable code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
try {
Boolean bool = (Boolean) MVEL.eval(this.name, ctx, factory);
if (!bool) throw new AssertionError("assertion failed in expression: " + new String(this.name));
return bool;
}
catch (ClassCastException e) {
throw new CompileException("assertion does not contain a boolean statement");
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object getWithProperty(Object ctx) {
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
WithAccessor wa = new WithAccessor(root, subset(expr, start, cursor++ - start), ingressType, false);
addAccessorNode(wa);
return wa.getValue(ctx, thisRef, variableFactory);
} | #vulnerable code
private Object getWithProperty(Object ctx) {
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{');
cursor = res[0];
getParserContext().incrementLineCount(res[1]);
WithAccessor wa = new WithAccessor(root, subset(expr, start, cursor++ - start), ingressType, false);
addAccessorNode(wa);
return wa.getValue(ctx, thisRef, variableFactory);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected Class getImport(String name) {
if (pCtx == null) pCtx = getParserContext();
if (pCtx.hasImport(name)) return pCtx.getImport(name);
VariableResolverFactory vrf = findClassImportResolverFactory(variableFactory);
return (Class) vrf.getVariableResolver(name).getValue();
} | #vulnerable code
protected Class getImport(String name) {
if (getParserContext().hasImport(name)) return getParserContext().getImport(name);
VariableResolverFactory vrf = findClassImportResolverFactory(variableFactory);
return (Class) vrf.getVariableResolver(name).getValue();
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
synchronized (EX_PRECACHE) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
else {
length = this.expr.length;
}
}
}
} | #vulnerable code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
synchronized (EX_PRECACHE) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
}
else {
length = this.expr.length;
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object getWithProperty(Object ctx) {
assert debug("\n ** ENTER -> {with}");
if (first) {
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
first = false;
}
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
// int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
cursor = balancedCaptureWithLineAccounting(expr, cursor, '{', pCtx);
// (pCtx = getParserContext()).incrementLineCount(res[1]);
this.returnType = ctx != null ? ctx.getClass() : null;
for (WithStatementPair aPvp : parseWithExpressions(root, subset(expr, start, cursor++ - start))) {
assert debug("DUP");
mv.visitInsn(DUP);
if (aPvp.getParm() == null) {
// Execute this interpretively now.
MVEL.eval(aPvp.getValue(), ctx, variableFactory);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
}
else {
// Execute interpretively.
MVEL.setProperty(ctx, aPvp.getParm(), MVEL.eval(aPvp.getValue(), ctx, variableFactory));
compiledInputs.add(((ExecutableStatement) MVEL.compileSetExpression(aPvp.getParm(),
getReturnType(ingressType, aPvp.getParm(), pCtx), pCtx)));
assert debug("ALOAD 0");
mv.visitVarInsn(ALOAD, 0);
assert debug("GETFIELD p" + (compiledInputs.size() - 1));
mv.visitFieldInsn(GETFIELD, className, "p" + (compiledInputs.size() - 1), "L" + NAMESPACE + "compiler/ExecutableStatement;");
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
assert debug("ALOAD 2");
mv.visitVarInsn(ALOAD, 2);
assert debug("ALOAD 3");
mv.visitVarInsn(ALOAD, 3);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
assert debug("INVOKEINTERFACE Accessor.setValue");
mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "compiler/ExecutableStatement",
"setValue",
"(Ljava/lang/Object;Ljava/lang/Object;L"
+ NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;");
assert debug("POP");
mv.visitInsn(POP);
}
}
return ctx;
} | #vulnerable code
private Object getWithProperty(Object ctx) {
assert debug("\n ** ENTER -> {with}");
if (first) {
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
first = false;
}
String root = new String(expr, 0, cursor - 1).trim();
int start = cursor + 1;
int[] res = balancedCaptureWithLineAccounting(expr, cursor, '{');
cursor = res[0];
(pCtx = getParserContext()).incrementLineCount(res[1]);
this.returnType = ctx != null ? ctx.getClass() : null;
for (WithStatementPair aPvp : parseWithExpressions(root, subset(expr, start, cursor++ - start))) {
assert debug("DUP");
mv.visitInsn(DUP);
if (aPvp.getParm() == null) {
// Execute this interpretively now.
MVEL.eval(aPvp.getValue(), ctx, variableFactory);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
}
else {
// Execute interpretively.
MVEL.setProperty(ctx, aPvp.getParm(), MVEL.eval(aPvp.getValue(), ctx, variableFactory));
compiledInputs.add(((ExecutableStatement) MVEL.compileSetExpression(aPvp.getParm(),
getReturnType(ingressType, aPvp.getParm(), pCtx), pCtx)));
assert debug("ALOAD 0");
mv.visitVarInsn(ALOAD, 0);
assert debug("GETFIELD p" + (compiledInputs.size() - 1));
mv.visitFieldInsn(GETFIELD, className, "p" + (compiledInputs.size() - 1), "L" + NAMESPACE + "compiler/ExecutableStatement;");
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
assert debug("ALOAD 2");
mv.visitVarInsn(ALOAD, 2);
assert debug("ALOAD 3");
mv.visitVarInsn(ALOAD, 3);
addSubstatement((ExecutableStatement) subCompileExpression(aPvp.getValue().toCharArray()));
assert debug("INVOKEINTERFACE Accessor.setValue");
mv.visitMethodInsn(INVOKEINTERFACE, NAMESPACE + "compiler/ExecutableStatement",
"setValue",
"(Ljava/lang/Object;Ljava/lang/Object;L"
+ NAMESPACE + "integration/VariableResolverFactory;Ljava/lang/Object;)Ljava/lang/Object;");
assert debug("POP");
mv.visitInsn(POP);
}
}
return ctx;
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Object parse(File file, Object ctx, Map tokens, TemplateRegistry registry) throws IOException {
if (!file.exists())
throw new CompileException("cannot find file: " + file.getName());
FileInputStream inStream = null;
ReadableByteChannel fc = null;
try {
inStream = new FileInputStream(file);
fc = inStream.getChannel();
ByteBuffer buf = allocateDirect(10);
StringAppender sb = new StringAppender((int) file.length());
int read = 0;
while (read >= 0) {
buf.rewind();
read = fc.read(buf);
buf.rewind();
for (; read > 0; read--) {
sb.append((char) buf.get());
}
}
//noinspection unchecked
return parse(sb, ctx, tokens, registry);
}
catch (FileNotFoundException e) {
// this can't be thrown, we check for this explicitly.
}
finally {
if (inStream != null) inStream.close();
if (fc != null) fc.close();
}
return null;
} | #vulnerable code
public static Object parse(File file, Object ctx, Map tokens, TemplateRegistry registry) throws IOException {
if (!file.exists())
throw new CompileException("cannot find file: " + file.getName());
FileInputStream inStream = null;
ReadableByteChannel fc = null;
try {
inStream = new FileInputStream(file);
fc = inStream.getChannel();
ByteBuffer buf = allocateDirect(10);
StringAppender sb = new StringAppender((int) file.length());
int read = 0;
while (read >= 0) {
buf.rewind();
read = fc.read(buf);
buf.rewind();
for (; read > 0; read--) {
sb.append((char) buf.get());
}
}
//noinspection unchecked
return parse(sb, ctx, tokens, registry);
}
catch (FileNotFoundException e) {
// this can't be thrown, we check for this explicitly.
}
finally {
if (inStream != null) inStream.close();
if (fc != null) fc.close();
}
return null;
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompiledExpression compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astLinkedList = new ASTLinkedList();
boolean firstLA;
ParserContext pCtx = getParserContext();
if (verifying) {
inputs = new LinkedHashSet<String>();
locals = new LinkedHashSet<String>();
getParserContext().setVariableTable(new HashMap<String, Class>());
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
if (tk.fields == -1) {
astLinkedList.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof TypedVarNode) {
TypedVarNode tv = (TypedVarNode) tk;
pCtx.getVariableTable().put(tv.getName(), tv.getEgressType());
}
else if (pCtx.isStrictTypeEnforcement() && tk instanceof AssignmentNode
&& (pCtx.getInputTable() == null
|| !pCtx.getInputTable().containsKey(tk.getName()))) {
addFatalError("untyped var not permitted in strict-mode: " + tk.getName());
}
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray());
tk.setAccessor(subCompiler.compile());
if (verifying)
inputs.addAll(subCompiler.getInputs());
}
/**
* This kludge of code is to handle compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral() && tk.getLiteralValue() != LITERALS.get("this")) {
if ((tkOp = nextToken()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a compile-time
* reduction.
*/
if ((tkLA = nextToken()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduceTrinary();
firstLA = true;
/**
* Now we need to check to see if this is actually a continuing reduction.
*/
while ((tkOp2 = nextToken()) != null) {
if (!tkOp2.isOperator(tkOp.getOperator())) {
/**
* We can't continue any further because we are dealing with
* different operators.
*/
astLinkedList.addTokenNode(new LiteralNode(stk.pop()));
astLinkedList.addTokenNode(tkOp2);
break;
}
else if ((tkLA2 = nextToken()) != null
&& tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduceTrinary();
firstLA = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()), tkOp);
if (tkLA2 != null) astLinkedList.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
continue;
}
else {
astLinkedList.addTokenNode(verify(tk), verify(tkOp));
if (tkLA != null) astLinkedList.addTokenNode(verify(tkLA));
continue;
}
}
else {
astLinkedList.addTokenNode(verify(tk));
if (tkOp != null) astLinkedList.addTokenNode(verify(tkOp));
continue;
}
}
astLinkedList.addTokenNode(verify(tk));
}
if (verifying) {
for (String s : locals) {
inputs.remove(s);
}
}
if (pCtx.isFatalError()) {
parserContext.set(null);
throw new CompileException("Failed to compile: " + pCtx.getErrorList().size() + " compilation error(s)", pCtx.getErrorList());
}
else if (pCtx.isFatalError()) {
throw new CompileException("Failed to compile: " + pCtx.getErrorList().size() + " compilation error(s)", pCtx.getErrorList());
}
return new CompiledExpression(new ASTArrayList(astLinkedList), getCurrentSourceFileName());
} | #vulnerable code
public CompiledExpression compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astLinkedList = new ASTLinkedList();
boolean firstLA;
ParserContext pCtx = getParserContext();
if (verifying) {
inputs = new LinkedHashSet<String>();
locals = new LinkedHashSet<String>();
getParserContext().setVariableTable(new HashMap<String, Class>());
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
if (tk.fields == -1) {
astLinkedList.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof TypedVarNode) {
TypedVarNode tv = (TypedVarNode) tk;
pCtx.getVariableTable().put(tv.getName(), tv.getEgressType());
}
else if (pCtx.isStrictTypeEnforcement() && tk instanceof AssignmentNode
&& (pCtx.getInputTable() == null
|| !pCtx.getInputTable().containsKey(tk.getName()))) {
pCtx.addError(new ErrorDetail("untyped var not permitted in strict-mode: " + tk.getName(), true));
}
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray());
tk.setAccessor(subCompiler.compile());
if (verifying)
inputs.addAll(subCompiler.getInputs());
}
/**
* This kludge of code is to handle compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral() && tk.getLiteralValue() != LITERALS.get("this")) {
if ((tkOp = nextToken()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a compile-time
* reduction.
*/
if ((tkLA = nextToken()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduceTrinary();
firstLA = true;
/**
* Now we need to check to see if this is actually a continuing reduction.
*/
while ((tkOp2 = nextToken()) != null) {
if (!tkOp2.isOperator(tkOp.getOperator())) {
/**
* We can't continue any further because we are dealing with
* different operators.
*/
astLinkedList.addTokenNode(new LiteralNode(stk.pop()));
astLinkedList.addTokenNode(tkOp2);
break;
}
else if ((tkLA2 = nextToken()) != null
&& tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduceTrinary();
firstLA = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()), tkOp);
if (tkLA2 != null) astLinkedList.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astLinkedList.addTokenNode(new ASTNode(ASTNode.LITERAL, stk.pop()));
continue;
}
else {
astLinkedList.addTokenNode(verify(tk), verify(tkOp));
if (tkLA != null) astLinkedList.addTokenNode(verify(tkLA));
continue;
}
}
else {
astLinkedList.addTokenNode(verify(tk));
if (tkOp != null) astLinkedList.addTokenNode(verify(tkOp));
continue;
}
}
astLinkedList.addTokenNode(verify(tk));
}
if (verifying) {
for (String s : locals) {
inputs.remove(s);
}
}
if (compileFail) {
throw new CompileException("Failed to compile: " + getParserContext().getErrorList().size() + " compilation error(s)", getParserContext().getErrorList());
}
if (pCtx.getRootParser() == this) {
parserContext.set(null);
}
return new CompiledExpression(new ASTArrayList(astLinkedList), getCurrentSourceFileName());
}
#location 150
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver(item);
ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory));
Object iterCond = MVEL.eval(cond, thisValue, factory);
if (itemType != null && itemType.isArray())
enforceTypeSafety(itemType, ParseTools.getBaseComponentType(iterCond.getClass()));
this.compiledBlock = (ExecutableStatement) subCompileExpression(block);
if (iterCond instanceof Iterable) {
for (Object o : (Iterable) iterCond) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond != null && iterCond.getClass().isArray()) {
int len = Array.getLength(iterCond);
for (int i = 0; i < len; i++) {
itemR.setValue(Array.get(iterCond, i));
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof CharSequence) {
for (Object o : iterCond.toString().toCharArray()) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof Integer) {
int max = (Integer) iterCond + 1;
for (int i = 1; i != max; i++) {
itemR.setValue(i);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else {
throw new CompileException("non-iterable type: " + (iterCond != null ? iterCond.getClass().getName() : "null"));
}
return null;
} | #vulnerable code
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
ItemResolverFactory.ItemResolver itemR = new ItemResolverFactory.ItemResolver(item);
ItemResolverFactory itemFactory = new ItemResolverFactory(itemR, new DefaultLocalVariableResolverFactory(factory));
Object iterCond = MVEL.eval(cond, thisValue, factory);
if (itemType != null && itemType.isArray())
enforceTypeSafety(itemType, ParseTools.getBaseComponentType(iterCond.getClass()));
this.compiledBlock = (ExecutableStatement) subCompileExpression(block);
if (iterCond instanceof Iterable) {
for (Object o : (Iterable) iterCond) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond != null && iterCond.getClass().isArray()) {
int len = Array.getLength(iterCond);
for (int i = 0; i < len; i++) {
itemR.setValue(Array.get(iterCond, i));
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof CharSequence) {
for (Object o : iterCond.toString().toCharArray()) {
itemR.setValue(o);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else if (iterCond instanceof Integer) {
int max = (Integer) iterCond + 1;
for (int i = 1; i != max; i++) {
itemR.setValue(i);
compiledBlock.getValue(ctx, thisValue, itemFactory);
}
}
else {
throw new CompileException("non-iterable type: " + iterCond.getClass().getName());
}
return null;
}
#location 39
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 106
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 136
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 22
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) {
// return Math.sqrt(DataConversion.convert(p0.getValue(ctx, variableFactory), Double.class).doubleValue());
return Integer.class;
//return ((CharSequence) ctx).charAt(DataConversion.convert(p0.getValue(ctx, variableFactory), Integer.class));
// return DataConversion.convert(new Integer(5), Integer.class);
} | #vulnerable code
public Object getValue(Object ctx, Object elCtx, VariableResolverFactory variableFactory) {
// return Math.sqrt(DataConversion.convert(p0.getValue(ctx, variableFactory), Double.class).doubleValue());
return ((CharSequence) ctx).charAt(DataConversion.convert(p0.getValue(ctx, variableFactory), Integer.class));
// return DataConversion.convert(new Integer(5), Integer.class);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
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);
}
} | #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 13
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String readInFile(File file) {
try {
FileChannel fc = new FileInputStream(file).getChannel();
ByteBuffer buf = allocateDirect(10);
StringAppender appender = new StringAppender();
int read;
while (true) {
buf.rewind();
if ((read = fc.read(buf)) != -1) {
buf.rewind();
for (; read != 0; read--) {
appender.append((char) buf.get());
}
}
else {
break;
}
}
fc.close();
return appender.toString();
}
catch (FileNotFoundException e) {
throw new TemplateError("cannot include template '" + file.getName() + "': file not found.");
}
catch (IOException e) {
throw new TemplateError("unknown I/O exception while including '" + file.getName() + "' (stacktrace nested)", e);
}
} | #vulnerable code
public static String readInFile(File file) {
try {
FileChannel fc = new FileInputStream(file).getChannel();
ByteBuffer buf = allocateDirect(10);
StringAppender appender = new StringAppender();
int read;
while (true) {
buf.rewind();
if ((read = fc.read(buf)) != -1) {
buf.rewind();
for (; read != 0; read--) {
appender.append((char) buf.get());
}
}
else {
break;
}
}
return appender.toString();
}
catch (FileNotFoundException e) {
throw new TemplateError("cannot include template '" + file.getName() + "': file not found.");
}
catch (IOException e) {
throw new TemplateError("unknown I/O exception while including '" + file.getName() + "' (stacktrace nested)", e);
}
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#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: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (tokens == null) {
tokens = new HashMap();
}
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);
}
} | #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);
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 (tokens == null) {
tokens = new HashMap();
}
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 92
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Class findClass(VariableResolverFactory factory, String name, ParserContext ctx) throws ClassNotFoundException {
try {
if (LITERALS.containsKey(name)) {
return (Class) LITERALS.get(name);
}
else if (factory != null && factory.isResolveable(name)) {
return (Class) factory.getVariableResolver(name).getValue();
}
else {
return createClass(name, ctx);
}
}
catch (ClassNotFoundException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("class not found: " + name, e);
}
} | #vulnerable code
public static Class findClass(VariableResolverFactory factory, String name, ParserContext ctx) throws ClassNotFoundException {
try {
if (LITERALS.containsKey(name)) {
return (Class) LITERALS.get(name);
}
else if (factory != null && factory.isResolveable(name)) {
return (Class) factory.getVariableResolver(name).getValue();
}
else if (ctx != null && ctx.hasImport(name)) {
return getCurrentThreadParserContext().getImport(name);
}
else {
return createClass(name);
}
}
catch (ClassNotFoundException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("class not found: " + name, e);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length || scanTo(']'))
throw new PropertyAccessException("unterminated '['");
prop = new String(property, start, cursor++ - start);
if (ctx instanceof Map) {
return ((Map) ctx).get(eval(prop, ctx, variableFactory));
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof Collection) {
int count = (Integer) eval(prop, ctx, variableFactory);
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) eval(prop, ctx, variableFactory));
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) eval(prop, ctx, variableFactory));
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
} | #vulnerable code
private Object getCollectionProperty(Object ctx, String prop) throws Exception {
if (prop.length() != 0) {
ctx = getBeanProperty(ctx, prop);
}
int start = ++cursor;
whiteSpaceSkip();
if (cursor == length)
throw new PropertyAccessException("unterminated '['");
Object item;
if (scanTo(']'))
throw new PropertyAccessException("unterminated '['");
// String ex = new String(property, start, cursor++ - start);
item = eval(new String(property, start, cursor++ - start), ctx, variableFactory);
if (ctx instanceof Map) {
return ((Map) ctx).get(item);
}
else if (ctx instanceof List) {
return ((List) ctx).get((Integer) item);
}
else if (ctx instanceof Collection) {
int count = (Integer) item;
if (count > ((Collection) ctx).size())
throw new PropertyAccessException("index [" + count + "] out of bounds on collections");
Iterator iter = ((Collection) ctx).iterator();
for (int i = 0; i < count; i++) iter.next();
return iter.next();
}
else if (ctx.getClass().isArray()) {
return Array.get(ctx, (Integer) item);
}
else if (ctx instanceof CharSequence) {
return ((CharSequence) ctx).charAt((Integer) item);
}
else {
throw new PropertyAccessException("illegal use of []: unknown type: " + (ctx == null ? null : ctx.getClass().getName()));
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CompiledExpression _compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astBuild = new ASTLinkedList();
boolean firstLA;
if (pCtx == null) pCtx = getParserContext();
debugSymbols = pCtx.isDebugSymbols();
try {
if (verifying) {
pCtx.initializeTables();
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
/**
* If this is a debug symbol, just add it and continue.
*/
if (tk.fields == -1) {
astBuild.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray(), pCtx);
tk.setAccessor(subCompiler._compile());
returnType = subCompiler.getReturnType();
}
/**
* This kludge of code is to handle compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral()) {
literalOnly = true;
if ((tkOp = nextTokenSkipSymbols()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a compile-time literal
* reduction.
*/
if ((tkLA = nextTokenSkipSymbols()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduce();
firstLA = true;
/**
* Now we need to check to see if this is a continuing reduction.
*/
while ((tkOp2 = nextTokenSkipSymbols()) != null) {
if (isBooleanOperator(tkOp2.getOperator())) {
astBuild.addTokenNode(new LiteralNode(stk.pop()), verify(pCtx, tkOp2));
break;
}
else if ((tkLA2 = nextTokenSkipSymbols()) != null && tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduce();
firstLA = false;
literalOnly = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astBuild.addTokenNode(new LiteralNode(stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astBuild.addTokenNode(new LiteralNode(stk.pop()), tkOp);
if (tkLA2 != null) astBuild.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astBuild.addTokenNode(new LiteralNode(stk.pop()));
continue;
}
else {
astBuild.addTokenNode(verify(pCtx, tk), verify(pCtx, tkOp));
if (tkLA != null) astBuild.addTokenNode(verify(pCtx, tkLA));
continue;
}
}
else {
literalOnly = false;
astBuild.addTokenNode(verify(pCtx, tk));
if (tkOp != null) astBuild.addTokenNode(verify(pCtx, tkOp));
continue;
}
}
else {
literalOnly = false;
}
astBuild.addTokenNode(verify(pCtx, tk));
}
astBuild.finish();
if (verifying) {
pCtx.processTables();
}
if (!stk.isEmpty()) throw new CompileException("COMPILE ERROR: non-empty stack after compile.");
return new CompiledExpression(optimizeAST(astBuild, secondPassOptimization), getCurrentSourceFileName(), returnType, pCtx, literalOnly);
}
catch (Throwable e) {
parserContext.set(null);
if (e instanceof RuntimeException) throw (RuntimeException) e;
else {
throw new CompileException(e.getMessage(), e);
}
}
} | #vulnerable code
public CompiledExpression _compile() {
ASTNode tk;
ASTNode tkOp;
ASTNode tkOp2;
ASTNode tkLA;
ASTNode tkLA2;
ASTLinkedList astBuild = new ASTLinkedList();
boolean firstLA;
debugSymbols = (pCtx = getParserContext()).isDebugSymbols();
try {
if (verifying) {
pCtx.initializeTables();
}
fields |= ASTNode.COMPILE_IMMEDIATE;
while ((tk = nextToken()) != null) {
/**
* If this is a debug symbol, just add it and continue.
*/
if (tk.fields == -1) {
astBuild.addTokenNode(tk);
continue;
}
returnType = tk.getEgressType();
if (tk instanceof Substatement) {
ExpressionCompiler subCompiler = new ExpressionCompiler(tk.getNameAsArray(), pCtx);
tk.setAccessor(subCompiler._compile());
returnType = subCompiler.getReturnType();
}
/**
* This kludge of code is to handle compile-time literal reduction. We need to avoid
* reducing for certain literals like, 'this', ternary and ternary else.
*/
if (tk.isLiteral()) {
literalOnly = true;
if ((tkOp = nextTokenSkipSymbols()) != null && tkOp.isOperator()
&& !tkOp.isOperator(Operator.TERNARY) && !tkOp.isOperator(Operator.TERNARY_ELSE)) {
/**
* If the next token is ALSO a literal, then we have a candidate for a compile-time literal
* reduction.
*/
if ((tkLA = nextTokenSkipSymbols()) != null && tkLA.isLiteral()) {
stk.push(tk.getLiteralValue(), tkLA.getLiteralValue(), tkOp.getLiteralValue());
/**
* Reduce the token now.
*/
reduce();
firstLA = true;
/**
* Now we need to check to see if this is a continuing reduction.
*/
while ((tkOp2 = nextTokenSkipSymbols()) != null) {
if (isBooleanOperator(tkOp2.getOperator())) {
astBuild.addTokenNode(new LiteralNode(stk.pop()), verify(pCtx, tkOp2));
break;
}
else if ((tkLA2 = nextTokenSkipSymbols()) != null && tkLA2.isLiteral()) {
stk.push(tkLA2.getLiteralValue(), tkOp2.getLiteralValue());
reduce();
firstLA = false;
literalOnly = false;
}
else {
if (firstLA) {
/**
* There are more tokens, but we can't reduce anymore. So
* we create a reduced token for what we've got.
*/
astBuild.addTokenNode(new LiteralNode(stk.pop()));
}
else {
/**
* We have reduced additional tokens, but we can't reduce
* anymore.
*/
astBuild.addTokenNode(new LiteralNode(stk.pop()), tkOp);
if (tkLA2 != null) astBuild.addTokenNode(tkLA2);
}
break;
}
}
/**
* If there are no more tokens left to parse, we check to see if
* we've been doing any reducing, and if so we create the token
* now.
*/
if (!stk.isEmpty())
astBuild.addTokenNode(new LiteralNode(stk.pop()));
continue;
}
else {
astBuild.addTokenNode(verify(pCtx, tk), verify(pCtx, tkOp));
if (tkLA != null) astBuild.addTokenNode(verify(pCtx, tkLA));
continue;
}
}
else {
literalOnly = false;
astBuild.addTokenNode(verify(pCtx, tk));
if (tkOp != null) astBuild.addTokenNode(verify(pCtx, tkOp));
continue;
}
}
else {
literalOnly = false;
}
astBuild.addTokenNode(verify(pCtx, tk));
}
astBuild.finish();
if (verifying) {
pCtx.processTables();
}
if (!stk.isEmpty()) throw new CompileException("COMPILE ERROR: non-empty stack after compile.");
return new CompiledExpression(optimizeAST(astBuild, secondPassOptimization), getCurrentSourceFileName(), returnType, pCtx, literalOnly);
}
catch (Throwable e) {
parserContext.set(null);
if (e instanceof RuntimeException) throw (RuntimeException) e;
else {
throw new CompileException(e.getMessage(), e);
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
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);
}
} | #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: {
ForeachContext foreachContext = (ForeachContext) currNode.getRegister();
if (tokens == null) {
tokens = new HashMap();
}
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 51
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 128
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
// Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
} | #vulnerable code
public void runTest(PerfTest test, int count) throws Exception {
int exFlags = test.getRunFlags();
String expression = test.getExpression();
String name = test.getName();
if (!silent) {
System.out.println("Test Name : " + test.getName());
System.out.println("Expression : " + test.getExpression());
System.out.println("Iterations : " + count);
}
long time;
long mem;
long total = 0;
long[] res = new long[TESTITER];
if ((testFlags & INTERPRETED) != 0) {
if (!silent) System.out.println("Interpreted Results :");
if ((testFlags & RUN_OGNL) != 0 && ((exFlags & RUN_OGNL)) != 0) {
try {
// unbenched warm-up
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
Ognl.getValue(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(OGNL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(OGNL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
ognlTotal += total;
}
total = 0;
if ((testFlags & RUN_MVEL) != 0 && ((exFlags & RUN_MVEL) != 0)) {
try {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
MVEL.eval(expression, baseClass);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(MVEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
e.printStackTrace();
if (!silent)
System.out.println("(MVEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
mvelTotal += total;
}
//
// total = 0;
//
// if ((testFlags & RUN_GROOVY) != 0 && ((exFlags & RUN_GROOVY) != 0)) {
// try {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
//
// time = currentTimeMillis();
// mem = Runtime.getRuntime().freeMemory();
// for (int reps = 0; reps < TESTITER; reps++) {
// for (int i = 0; i < count; i++) {
// Binding binding = new Binding();
// for (String var : variables.keySet()) {
// binding.setProperty(var, variables.get(var));
// }
//
// GroovyShell groovyShell = new GroovyShell(binding);
// groovyShell.evaluate(expression);
// }
//
// if (reps == 0) res[0] = total += currentTimeMillis() - time;
// else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
// }
//
// if (!silent)
// System.out.println("(Groovy) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
// + "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
//
// }
// catch (Exception e) {
// e.printStackTrace();
//
// if (!silent)
// System.out.println("(Groovy) : <<COULD NOT EXECUTE>>");
// }
// }
//
// synchronized (this) {
// groovyTotal += total;
// }
//
total = 0;
if ((testFlags & RUN_COMMONS_EL) != 0 && ((exFlags & RUN_COMMONS_EL) != 0)) {
VariableResolver vars = new JSPMapVariableResolver(variables);
String commonsEx = "${" + expression + "}";
try {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
new ExpressionEvaluatorImpl(true).parseExpression(commonsEx, Object.class, null).evaluate(vars);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(CommonsEL) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(CommonsEL) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
commonElTotal += total;
}
}
if ((testFlags & COMPILED) != 0) {
runTestCompiled(name, test.getOgnlCompiled(), test.getMvelCompiled(), test.getGroovyCompiled(), test.getElCompiled(), count, exFlags);
}
total = 0;
if ((testFlags & RUN_JAVA_NATIVE) != 0 && ((exFlags & RUN_JAVA_NATIVE) != 0)) {
NativeTest nt = test.getJavaNative();
try {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
// System.gc();
time = currentTimeMillis();
mem = Runtime.getRuntime().freeMemory();
for (int reps = 0; reps < TESTITER; reps++) {
for (int i = 0; i < count; i++) {
nt.run(baseClass, variables);
}
if (reps == 0) res[0] = total += currentTimeMillis() - time;
else res[reps] = (total * -1) + (total += currentTimeMillis() - time - total);
}
if (!silent)
System.out.println("(JavaNative) : " + new BigDecimal(((currentTimeMillis() - time))).divide(new BigDecimal(TESTITER), 2, RoundingMode.HALF_UP)
+ "ms avg. (mem delta: " + ((Runtime.getRuntime().freeMemory() - mem) / 1024) + "kb) " + resultsToString(res));
}
catch (Exception e) {
if (!silent)
System.out.println("(JavaNative) : <<COULD NOT EXECUTE>>");
}
}
synchronized (this) {
javaNativeTotal += total;
}
if (!silent)
System.out.println("------------------------------------------------");
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
synchronized (EX_PRECACHE) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
else {
length = this.expr.length;
}
}
}
} | #vulnerable code
protected void setExpression(String expression) {
if (expression != null && !"".equals(expression)) {
if ((this.expr = EX_PRECACHE.get(expression)) == null) {
synchronized (EX_PRECACHE) {
length = (this.expr = expression.toCharArray()).length;
// trim any whitespace.
while (length != 0 && isWhitespace(this.expr[length - 1])) length--;
char[] e = new char[length];
for (int i = 0; i != e.length; i++)
e[i] = expr[i];
EX_PRECACHE.put(expression, e);
}
}
else {
length = this.expr.length;
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 16
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 52
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
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, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.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 {
ExpressionParser oParser = new ExpressionParser(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++ ) {
Object listObject = new ExpressionParser(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++ ) {
tokens.put(alias[i], iters[i].next());
}
if ( foreachContext.getCount() != 0 ) {
sbuf.append( foreachContext.getSeperator() );
}
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 register;
}
else {
return sbuf.toString();
}
}
}
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);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
} | #vulnerable code
public Object execute(Object ctx, Map tokens) {
if (nodes == null) {
return new String(expression);
}
else if (nodes.length == 2) {
switch (nodes[0].getToken()) {
case PROPERTY_EX:
//noinspection unchecked
// return ExpressionParser.eval(getInternalSegment(nodes[0]), ctx, tokens);
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, MVEL.compileExpression(s));
return MVEL.executeExpression(EX_PRECOMP_CACHE.get(s), ctx, tokens);
}
}
else {
return MVEL.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 {
ExpressionParser oParser = new ExpressionParser(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: {
String seperator = "";
if (currNode.getRegister() == null || currNode.getRegister() instanceof String) {
try {
String props = ( String) currNode.getRegister();
if ( props != null && props.length() > 0 ) {
seperator = props;
}
String[] lists = getForEachSegment(currNode).split( "," );
Iterator[] iters = new Iterator[lists.length];
for( int i = 0; i < lists.length; i++ ) {
Object listObject = new ExpressionParser(lists[i], ctx, tokens).parse();
if ( listObject instanceof Object[]) {
listObject = Arrays.asList( (Object[]) listObject );
}
iters[i] = ((Collection)listObject).iterator() ;
}
currNode.setRegister( 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 = (Iterator[]) currNode.getRegister();
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++ ) {
tokens.put(alias[i], iters[i].next());
}
sbuf.append( seperator );
}
else {
for ( int i = 0; i < iters.length; i++ ) {
tokens.remove(alias[i]);
}
exitContext();
}
break;
}
case ELSE:
case END:
if (stack.isEmpty()) forwardAndPush();
continue;
case GOTO:
pushNode(currNode.getEndNode());
continue;
case TERMINUS: {
if (nodes.length == 2) {
return register;
}
else {
return sbuf.toString();
}
}
}
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);
}
throw new CompileException("unhandled fatal exception (node:" + node + ")", e);
}
}
#location 102
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 86
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
}
}
} | #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 129
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Class getClassReference(ParserContext ctx, TypeDescriptor tDescr) throws ClassNotFoundException {
Class cls;
if (ctx != null && ctx.hasImport(tDescr.className)) {
cls = ctx.getImport(tDescr.className);
if (tDescr.isArray()) {
cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
}
}
else if (ctx == null && hasContextFreeImport(tDescr.className)) {
cls = getContextFreeImport(tDescr.className);
if (tDescr.isArray()) {
cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
}
}
else {
cls = createClass(tDescr.getClassName(), ctx);
if (tDescr.isArray()) {
cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
}
}
return cls;
} | #vulnerable code
public static Class getClassReference(ParserContext ctx, TypeDescriptor tDescr) throws ClassNotFoundException {
Class cls;
if (ctx.hasImport(tDescr.className)) {
cls = ctx.getImport(tDescr.className);
if (tDescr.isArray()) {
cls = findClass(null, repeatChar('[', tDescr.arraySize.length) + "L" + cls.getName() + ";", ctx);
}
}
else {
cls = createClass(tDescr.getClassName(), ctx);
if (tDescr.isArray()) {
cls = findClass(null, repeatChar('[', tDescr.getArrayLength()) + "L" + cls.getName() + ";", ctx);
}
}
return cls;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void sortXml() {
newDocument = (Document) originalDocument.clone();
final Element rootElement = (Element) originalDocument.getRootElement().clone();
HierarchyRootWrapper rootWrapper = factory.createFromRootElement(rootElement);
rootWrapper.createWrappedStructure(factory);
rootWrapper.detachStructure();
rootWrapper.sortStructureAttributes();
rootWrapper.sortStructureElements();
rootWrapper.connectXmlStructure();
newDocument.setRootElement(rootWrapper.getElementContent().getContent());
} | #vulnerable code
public void sortXml() {
newDocument = (Document) originalDocument.clone();
final Element rootElement = (Element) originalDocument.getRootElement().clone();
HierarchyWrapper rootWrapper = factory.createFromRootElement(rootElement);
rootWrapper.createWrappedStructure(factory);
rootWrapper.detachStructure();
rootWrapper.sortStructureAttributes();
rootWrapper.sortStructureElements();
rootWrapper.connectXmlStructure();
newDocument.setRootElement(rootWrapper.getElementContent().getContent());
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HmilyParticipant preTryParticipant(final HmilyTransactionContext context, final ProceedingJoinPoint point) {
LogUtil.debug(LOGGER, "participant hmily tcc transaction start..:{}", context::toString);
final HmilyParticipant hmilyParticipant = buildHmilyParticipant(point, context.getParticipantId(), context.getParticipantRefId(), HmilyRoleEnum.PARTICIPANT.getCode(), context.getTransId());
HmilyTransactionHolder.getInstance().cacheHmilyParticipant(hmilyParticipant);
HmilyRepositoryStorage.createHmilyParticipant(hmilyParticipant);
//publishEvent
//Nested transaction support
context.setRole(HmilyRoleEnum.PARTICIPANT.getCode());
HmilyContextHolder.set(context);
return hmilyParticipant;
} | #vulnerable code
public HmilyParticipant preTryParticipant(final HmilyTransactionContext context, final ProceedingJoinPoint point) {
LogUtil.debug(LOGGER, "participant hmily tcc transaction start..:{}", context::toString);
final HmilyParticipant hmilyParticipant = buildHmilyParticipant(point, context.getParticipantId(), context.getParticipantRefId(), HmilyRoleEnum.PARTICIPANT.getCode(), context.getTransId());
//cache by guava
if (Objects.nonNull(hmilyParticipant)) {
HmilyParticipantCacheManager.getInstance().cacheHmilyParticipant(hmilyParticipant);
PUBLISHER.publishEvent(hmilyParticipant, EventTypeEnum.CREATE_HMILY_PARTICIPANT.getCode());
}
//publishEvent
//Nested transaction support
context.setRole(HmilyRoleEnum.PARTICIPANT.getCode());
HmilyContextHolder.set(context);
return hmilyParticipant;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean revert(final HmilyParticipantUndo participantUndo) throws SQLRevertException {
try (Connection connection = HmilyResourceManager.get(participantUndo.getResourceId()).getTargetDataSource().getConnection()) {
return doRevertInTransaction(connection, participantUndo.getUndoInvocation().getTuples());
} catch (final SQLException ex) {
log.error("hmily tac rollback exception -> ", ex);
return false;
}
} | #vulnerable code
@Override
public boolean revert(final HmilyParticipantUndo participantUndo) throws SQLRevertException {
RevertSQLUnit revertSQLUnit = SQLImageMapperFactory.newInstance(participantUndo.getUndoInvocation()).cast();
DataSource dataSource = HmilyResourceManager.get(participantUndo.getResourceId()).getTargetDataSource();
return executeUpdate(revertSQLUnit, dataSource) > 0;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver, Context invokationContext, List<TypeUsage> typeParameterValues) {
List<MethodUsage> methods = new ArrayList<>();
for (Method method : Arrays.stream(clazz.getDeclaredMethods()).filter((m) -> m.getName().equals(name)).sorted(new MethodComparator()).collect(Collectors.toList())) {
if (method.isBridge() || method.isSynthetic()) continue;
MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
MethodUsage methodUsage = new MethodUsage(methodDeclaration, typeSolver);
for (int i=0;i<getTypeParameters().size();i++){
String nameToReplace = getTypeParameters().get(i).getName();
TypeUsage newValue = typeParameterValues.get(i);
methodUsage = methodUsage.replaceNameParam(nameToReplace, newValue);
}
methods.add(methodUsage);
}
if (getSuperClass() != null) {
ClassDeclaration superClass = (ClassDeclaration)getSuperClass().getTypeDeclaration();
Optional<MethodUsage> ref = superClass.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext, typeParameterValues);
if (ref.isPresent()) {
methods.add(ref.get());
}
}
for (InterfaceDeclaration interfaceDeclaration : getInterfaces()) {
Optional<MethodUsage> ref = interfaceDeclaration.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext, typeParameterValues);
if (ref.isPresent()) {
methods.add(ref.get());
}
}
Optional<MethodUsage> ref = MethodResolutionLogic.findMostApplicableUsage(methods, name, parameterTypes, typeSolver);
return ref;
} | #vulnerable code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver, Context invokationContext, List<TypeUsage> typeParameterValues) {
List<MethodUsage> methods = new ArrayList<>();
for (Method method : Arrays.stream(clazz.getDeclaredMethods()).filter((m) -> m.getName().equals(name)).sorted(new MethodComparator()).collect(Collectors.toList())) {
if (method.isBridge() || method.isSynthetic()) continue;
MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
MethodUsage methodUsage = new MethodUsage(methodDeclaration, typeSolver);
for (int i=0;i<getTypeParameters().size();i++){
String nameToReplace = getTypeParameters().get(i).getName();
TypeUsage newValue = typeParameterValues.get(i);
methodUsage = methodUsage.replaceNameParam(nameToReplace, newValue);
}
methods.add(methodUsage);
}
if (getSuperClass(typeSolver) != null) {
ClassDeclaration superClass = (ClassDeclaration)getSuperClass(typeSolver).getTypeDeclaration();
Optional<MethodUsage> ref = superClass.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext, typeParameterValues);
if (ref.isPresent()) {
methods.add(ref.get());
}
}
for (InterfaceDeclaration interfaceDeclaration : getInterfaces(typeSolver)) {
Optional<MethodUsage> ref = interfaceDeclaration.solveMethodAsUsage(name, parameterTypes, typeSolver, invokationContext, typeParameterValues);
if (ref.isPresent()) {
methods.add(ref.get());
}
}
Optional<MethodUsage> ref = MethodResolutionLogic.findMostApplicableUsage(methods, name, parameterTypes, typeSolver);
return ref;
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
// TODO consider call of static methods
if (wrappedNode.getScope() != null) {
try {
TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope());
return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
} catch (UnsolvedSymbolException e){
// ok, maybe it was instead a static access, so let's look for a type
if (wrappedNode.getScope() instanceof NameExpr){
String className = ((NameExpr)wrappedNode.getScope()).getName();
SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver);
if (ref.isSolved()) {
SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver);
if (m.isSolved()) {
return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver));
}
}
}
throw e;
}
} else {
if (wrappedNode.getParentNode() instanceof MethodCallExpr) {
MethodCallExpr parent = (MethodCallExpr)wrappedNode.getParentNode();
if (parent.getScope() == wrappedNode) {
return getParent().getParent().solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
//TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
//return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
Context parentContext = getParent();
//System.out.println("NAME "+name);
return parentContext.solveMethodAsUsage(name, parameterTypes, typeSolver);
}
} | #vulnerable code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
// TODO consider call of static methods
if (wrappedNode.getScope() != null) {
try {
TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope());
return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
} catch (UnsolvedSymbolException e){
// ok, maybe it was instead a static access, so let's look for a type
if (wrappedNode.getScope() instanceof NameExpr){
String className = ((NameExpr)wrappedNode.getScope()).getName();
SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver);
if (ref.isSolved()) {
SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver);
if (m.isSolved()) {
return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver));
}
}
}
throw e;
}
} else {
//TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
//return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
return getParent().solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
#location 25
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
return getParent().solveSymbol(name, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
return JavaParserFactory.getContext(wrappedNode.getParentNode()).solveSymbol(name, typeSolver);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CommentsCollection parse(final InputStream in, final String encoding) throws IOException, UnsupportedEncodingException {
boolean lastWasASlashR = false;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
CommentsCollection comments = new CommentsCollection();
int r;
Deque prevTwoChars = new LinkedList<Character>(Arrays.asList('z','z'));
State state = State.CODE;
LineComment currentLineComment = null;
BlockComment currentBlockComment = null;
StringBuffer currentContent = null;
int currLine = 1;
int currCol = 1;
while ((r=br.read()) != -1){
char c = (char)r;
if (c=='\r'){
lastWasASlashR = true;
} else if (c=='\n'&&lastWasASlashR){
lastWasASlashR=false;
continue;
} else {
lastWasASlashR=false;
}
switch (state){
case CODE:
if (prevTwoChars.peekLast().equals('/') && c=='/'){
currentLineComment = new LineComment();
currentLineComment.setBeginLine(currLine);
currentLineComment.setBeginColumn(currCol-1);
state = State.IN_LINE_COMMENT;
currentContent = new StringBuffer();
} else if (prevTwoChars.peekLast().equals('/') && c=='*'){
currentBlockComment= new BlockComment();
currentBlockComment.setBeginLine(currLine);
currentBlockComment.setBeginColumn(currCol-1);
state = State.IN_BLOCK_COMMENT;
currentContent = new StringBuffer();
} else {
// nothing to do
}
break;
case IN_LINE_COMMENT:
if (c=='\n' || c=='\r'){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
state = State.CODE;
} else {
currentContent.append(c);
}
break;
case IN_BLOCK_COMMENT:
if (prevTwoChars.peekLast().equals('*') && c=='/' && !prevTwoChars.peekFirst().equals('/')){
// delete last character
String content = currentContent.deleteCharAt(currentContent.toString().length()-1).toString();
if (content.startsWith("*")){
JavadocComment javadocComment = new JavadocComment();
javadocComment.setContent(content.substring(1));
javadocComment.setBeginLine(currentBlockComment.getBeginLine());
javadocComment.setBeginColumn(currentBlockComment.getBeginColumn());
javadocComment.setEndLine(currLine);
javadocComment.setEndColumn(currCol+1);
comments.addComment(javadocComment);
} else {
currentBlockComment.setContent(content);
currentBlockComment.setEndLine(currLine);
currentBlockComment.setEndColumn(currCol+1);
comments.addComment(currentBlockComment);
}
state = State.CODE;
} else {
currentContent.append(c=='\r'?'\n':c);
}
break;
default:
throw new RuntimeException("Unexpected");
}
switch (c){
case '\n':
case '\r':
currLine+=1;
currCol = 1;
break;
case '\t':
currCol+=COLUMNS_PER_TAB;
break;
default:
currCol+=1;
}
prevTwoChars.remove();
prevTwoChars.add(c);
}
if (state==State.IN_LINE_COMMENT){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
}
return comments;
} | #vulnerable code
public CommentsCollection parse(final InputStream in, final String encoding) throws IOException, UnsupportedEncodingException {
boolean lastWasASlashR = false;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
CommentsCollection comments = new CommentsCollection();
int r;
char prevChar = 'z';
State state = State.CODE;
LineComment currentLineComment = null;
BlockComment currentBlockComment = null;
StringBuffer currentContent = null;
int currLine = 1;
int currCol = 1;
while ((r=br.read()) != -1){
char c = (char)r;
if (c=='\r'){
lastWasASlashR = true;
} else if (c=='\n'&&lastWasASlashR){
lastWasASlashR=false;
continue;
} else {
lastWasASlashR=false;
}
switch (state){
case CODE:
if (prevChar=='/' && c=='/'){
currentLineComment = new LineComment();
currentLineComment.setBeginLine(currLine);
currentLineComment.setBeginColumn(currCol-1);
state = State.IN_LINE_COMMENT;
currentContent = new StringBuffer();
} else if (prevChar=='/' && c=='*'){
currentBlockComment= new BlockComment();
currentBlockComment.setBeginLine(currLine);
currentBlockComment.setBeginColumn(currCol-1);
state = State.IN_BLOCK_COMMENT;
currentContent = new StringBuffer();
} else {
// nothing to do
}
break;
case IN_LINE_COMMENT:
if (c=='\n' || c=='\r'){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
state = State.CODE;
} else {
currentContent.append(c);
}
break;
case IN_BLOCK_COMMENT:
if (prevChar=='*' && c=='/'){
// delete last character
String content = currentContent.deleteCharAt(currentContent.toString().length()-1).toString();
if (content.startsWith("*")){
JavadocComment javadocComment = new JavadocComment();
javadocComment.setContent(content.substring(1));
javadocComment.setBeginLine(currentBlockComment.getBeginLine());
javadocComment.setBeginColumn(currentBlockComment.getBeginColumn());
javadocComment.setEndLine(currLine);
javadocComment.setEndColumn(currCol+1);
comments.addComment(javadocComment);
} else {
currentBlockComment.setContent(content);
currentBlockComment.setEndLine(currLine);
currentBlockComment.setEndColumn(currCol+1);
comments.addComment(currentBlockComment);
}
state = State.CODE;
} else {
currentContent.append(c=='\r'?'\n':c);
}
break;
default:
throw new RuntimeException("Unexpected");
}
switch (c){
case '\n':
case '\r':
currLine+=1;
currCol = 1;
break;
case '\t':
currCol+=COLUMNS_PER_TAB;
break;
default:
currCol+=1;
}
prevChar = c;
}
if (state==State.IN_LINE_COMMENT){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
}
return comments;
}
#location 75
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SymbolReference<MethodDeclaration> solveMethod(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
List<MethodDeclaration> methods = new ArrayList<>();
for (Method method : Arrays.stream(clazz.getDeclaredMethods()).filter((m) -> m.getName().equals(name)).sorted(new MethodComparator()).collect(Collectors.toList())) {
if (method.isBridge() || method.isSynthetic()) continue;
MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
methods.add(methodDeclaration);
}
if (getSuperClass() != null) {
ClassDeclaration superClass = (ClassDeclaration)getSuperClass().getTypeDeclaration();
SymbolReference<MethodDeclaration> ref = superClass.solveMethod(name, parameterTypes, typeSolver);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
}
for (InterfaceDeclaration interfaceDeclaration : getInterfaces()) {
SymbolReference<MethodDeclaration> ref = interfaceDeclaration.solveMethod(name, parameterTypes, typeSolver);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
}
return MethodResolutionLogic.findMostApplicable(methods, name, parameterTypes, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<MethodDeclaration> solveMethod(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
List<MethodDeclaration> methods = new ArrayList<>();
for (Method method : Arrays.stream(clazz.getDeclaredMethods()).filter((m) -> m.getName().equals(name)).sorted(new MethodComparator()).collect(Collectors.toList())) {
if (method.isBridge() || method.isSynthetic()) continue;
MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(method, typeSolver);
methods.add(methodDeclaration);
}
if (getSuperClass(typeSolver) != null) {
ClassDeclaration superClass = (ClassDeclaration)getSuperClass(typeSolver).getTypeDeclaration();
SymbolReference<MethodDeclaration> ref = superClass.solveMethod(name, parameterTypes, typeSolver);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
}
for (InterfaceDeclaration interfaceDeclaration : getInterfaces(typeSolver)) {
SymbolReference<MethodDeclaration> ref = interfaceDeclaration.solveMethod(name, parameterTypes, typeSolver);
if (ref.isSolved()) {
methods.add(ref.getCorrespondingDeclaration());
}
}
return MethodResolutionLogic.findMostApplicable(methods, name, parameterTypes, typeSolver);
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ParseResult<CompilationUnit> tryToParse(String startPackage, String filename, ParserConfiguration configuration) throws IOException {
assertNotNull(startPackage);
assertNotNull(filename);
final Path relativePath = fileInPackageRelativePath(startPackage, filename);
if (cache.containsKey(relativePath)) {
Log.trace("Retrieving cached %s", () -> relativePath);
return cache.get(relativePath);
}
final Path path = root.resolve(relativePath);
Log.trace("Parsing %s", () -> path);
final ParseResult<CompilationUnit> result = new JavaParser(configuration)
.parse(COMPILATION_UNIT, provider(path, configuration.getCharacterEncoding()));
result.getResult().ifPresent(cu -> cu.setStorage(path, configuration.getCharacterEncoding()));
cache.put(relativePath, result);
return result;
} | #vulnerable code
public ParseResult<CompilationUnit> tryToParse(String startPackage, String filename, ParserConfiguration configuration) throws IOException {
assertNotNull(startPackage);
assertNotNull(filename);
final Path relativePath = fileInPackageRelativePath(startPackage, filename);
if (cache.containsKey(relativePath)) {
Log.trace("Retrieving cached %s", () -> relativePath);
return cache.get(relativePath);
}
final Path path = root.resolve(relativePath);
Log.trace("Parsing %s", () -> path);
final ParseResult<CompilationUnit> result = new JavaParser(configuration)
.parse(COMPILATION_UNIT, provider(path));
result.getResult().ifPresent(cu -> cu.setStorage(path, configuration.getCharacterEncoding()));
cache.put(relativePath, result);
return result;
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void parse(String fileName) throws IOException {
Path sourceFile = properSrc.resolve( fileName + ".java");
SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor();
OutputStream outErrStream = new ByteArrayOutputStream();
PrintStream outErr = new PrintStream(outErrStream);
sourceFileInfoExtractor.setOut(outErr);
sourceFileInfoExtractor.setErr(outErr);
sourceFileInfoExtractor.solve(sourceFile);
String output = outErrStream.toString();
String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt";
Path dstFile = adaptPath(root.resolve(path));
if (DEBUG && (sourceFileInfoExtractor.getFailures() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) {
System.err.println(output);
}
assertEquals(0, sourceFileInfoExtractor.getFailures(), "No failures expected when analyzing " + path);
assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path);
String expected = readFile(dstFile);
String[] outputLines = output.split("\n");
String[] expectedLines = expected.split("\n");
for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) {
assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected");
}
assertEquals(expectedLines.length, outputLines.length);
JavaParserFacade.clearInstances();
// If we need to update the file uncomment these lines
//PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8");
//writer.print(output);
//writer.close();
} | #vulnerable code
private void parse(String fileName) throws IOException {
Path sourceFile = properSrc.resolve( fileName + ".java");
SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor();
OutputStream outErrStream = new ByteArrayOutputStream();
PrintStream outErr = new PrintStream(outErrStream);
sourceFileInfoExtractor.setOut(outErr);
sourceFileInfoExtractor.setErr(outErr);
sourceFileInfoExtractor.solve(sourceFile);
String output = outErrStream.toString();
String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt";
Path dstFile = adaptPath(root.resolve(path));
if (DEBUG && (sourceFileInfoExtractor.getKo() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) {
System.err.println(output);
}
assertEquals(0, sourceFileInfoExtractor.getKo(), "No failures expected when analyzing " + path);
assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path);
String expected = readFile(dstFile);
String[] outputLines = output.split("\n");
String[] expectedLines = expected.split("\n");
for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) {
assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected");
}
assertEquals(expectedLines.length, outputLines.length);
JavaParserFacade.clearInstances();
// If we need to update the file uncomment these lines
//PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8");
//writer.print(output);
//writer.close();
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("AND", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 7);
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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("AND", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 7);
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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public List<ReferenceTypeUsage> getAllAncestors() {
List<ReferenceTypeUsage> ancestors = new LinkedList<>();
if (getSuperClass() != null) {
ReferenceTypeUsage superClass = getSuperClass();
ancestors.add(superClass);
ancestors.addAll(getSuperClass().getAllAncestors());
}
ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new ReferenceTypeUsage(i, typeSolver)).collect(Collectors.<ReferenceTypeUsage>toList()));
for (int i=0;i<ancestors.size();i++){
if (ancestors.get(i).getQualifiedName().equals(Object.class.getCanonicalName())) {
ancestors.remove(i);
i--;
}
}
ReferenceTypeUsage object = new ReferenceTypeUsage(new ReflectionClassDeclaration(Object.class, typeSolver), typeSolver);
ancestors.add(object);
return ancestors;
} | #vulnerable 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()));
for (int i=0;i<ancestors.size();i++){
if (ancestors.get(i).getQualifiedName().equals(Object.class.getCanonicalName())) {
ancestors.remove(i);
i--;
}
}
ReferenceTypeUsage object = new ReferenceTypeUsage(new ReflectionClassDeclaration(Object.class, typeSolver), typeSolver);
ancestors.add(object);
return ancestors;
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
}
} | #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 33
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private FileVisitResult callback(Path absolutePath, ParserConfiguration configuration, Callback callback) throws IOException {
Path localPath = root.relativize(absolutePath);
Log.trace("Parsing %s", () -> localPath);
ParseResult<CompilationUnit> result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(absolutePath, configuration.getCharacterEncoding()));
result.getResult().ifPresent(cu -> cu.setStorage(absolutePath, configuration.getCharacterEncoding()));
switch (callback.process(localPath, absolutePath, result)) {
case SAVE:
result.getResult().ifPresent(cu -> save(cu, absolutePath));
case DONT_SAVE:
return CONTINUE;
case TERMINATE:
return TERMINATE;
default:
throw new AssertionError("Return an enum defined in SourceRoot.Callback.Result");
}
} | #vulnerable code
private FileVisitResult callback(Path absolutePath, ParserConfiguration configuration, Callback callback) throws IOException {
Path localPath = root.relativize(absolutePath);
Log.trace("Parsing %s", () -> localPath);
ParseResult<CompilationUnit> result = new JavaParser(configuration).parse(COMPILATION_UNIT, provider(absolutePath));
result.getResult().ifPresent(cu -> cu.setStorage(absolutePath, configuration.getCharacterEncoding()));
switch (callback.process(localPath, absolutePath, result)) {
case SAVE:
result.getResult().ifPresent(cu -> save(cu, absolutePath));
case DONT_SAVE:
return CONTINUE;
case TERMINATE:
return TERMINATE;
default:
throw new AssertionError("Return an enum defined in SourceRoot.Callback.Result");
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public CommentsCollection parse(final InputStream in, final String charsetName) throws IOException {
return parse(new InputStreamReader(in, charsetName));
} | #vulnerable code
public CommentsCollection parse(final InputStream in, final String charsetName) throws IOException, UnsupportedEncodingException {
boolean lastWasASlashR = false;
BufferedReader br = new BufferedReader(new InputStreamReader(in, charsetName));
CommentsCollection comments = new CommentsCollection();
int r;
ParserState parserState = new ParserState();
State state = State.CODE;
LineComment currentLineComment = null;
BlockComment currentBlockComment = null;
StringBuilder currentContent = null;
int currLine = 1;
int currCol = 1;
while ((r=br.read()) != -1){
char c = (char)r;
if (c=='\r'){
lastWasASlashR = true;
} else if (c=='\n'&&lastWasASlashR){
lastWasASlashR=false;
continue;
} else {
lastWasASlashR=false;
}
switch (state) {
case CODE:
if (parserState.isLastChar('/') && c == '/') {
currentLineComment = new LineComment();
currentLineComment.setBeginLine(currLine);
currentLineComment.setBeginColumn(currCol - 1);
state = State.IN_LINE_COMMENT;
currentContent = new StringBuilder();
} else if (parserState.isLastChar('/') && c == '*') {
currentBlockComment = new BlockComment();
currentBlockComment.setBeginLine(currLine);
currentBlockComment.setBeginColumn(currCol - 1);
state = State.IN_BLOCK_COMMENT;
currentContent = new StringBuilder();
} else if (c == '"') {
state = State.IN_STRING;
} else if (c == '\'') {
state = State.IN_CHAR;
} else {
// nothing to do
}
break;
case IN_LINE_COMMENT:
if (c=='\n' || c=='\r'){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
state = State.CODE;
} else {
currentContent.append(c);
}
break;
case IN_BLOCK_COMMENT:
// '/*/' is not a valid block comment: it starts the block comment but it does not close it
// However this sequence can be contained inside a comment and in that case it close the comment
// For example:
// /* blah blah /*/
// At the previous line we had a valid block comment
if (parserState.isLastChar('*') && c=='/' && (!parserState.isSecondToLastChar('/') || currentContent.length() > 0)){
// delete last character
String content = currentContent.deleteCharAt(currentContent.toString().length()-1).toString();
if (content.startsWith("*")){
JavadocComment javadocComment = new JavadocComment();
javadocComment.setContent(content.substring(1));
javadocComment.setBeginLine(currentBlockComment.getBeginLine());
javadocComment.setBeginColumn(currentBlockComment.getBeginColumn());
javadocComment.setEndLine(currLine);
javadocComment.setEndColumn(currCol+1);
comments.addComment(javadocComment);
} else {
currentBlockComment.setContent(content);
currentBlockComment.setEndLine(currLine);
currentBlockComment.setEndColumn(currCol+1);
comments.addComment(currentBlockComment);
}
state = State.CODE;
} else {
currentContent.append(c == '\r' ? System.getProperty("line.separator") : c);
}
break;
case IN_STRING:
if (!parserState.isLastChar('\\') && c == '"') {
state = State.CODE;
}
break;
case IN_CHAR:
if (!parserState.isLastChar('\\') && c == '\'') {
state = State.CODE;
}
break;
default:
throw new RuntimeException("Unexpected");
}
switch (c){
case '\n':
case '\r':
currLine+=1;
currCol = 1;
break;
case '\t':
currCol+=COLUMNS_PER_TAB;
break;
default:
currCol+=1;
}
// ok we have two slashes in a row inside a string
// we want to replace them with... anything else, to not confuse
// the parser
if (state==State.IN_STRING && parserState.isLastChar('\\') && c == '\\') {
parserState.reset();
} else {
parserState.update(c);
}
}
if (state==State.IN_LINE_COMMENT){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
}
return comments;
}
#location 125
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public List<ResolvedConstructorDeclaration> getConstructors() {
return AstResolutionUtils.getConstructors(this.wrappedNode, typeSolver, this);
} | #vulnerable code
@Override
public List<ResolvedConstructorDeclaration> getConstructors() {
List<ResolvedConstructorDeclaration> declared = new LinkedList<>();
for (BodyDeclaration<?> member : wrappedNode.getMembers()) {
if (member instanceof com.github.javaparser.ast.body.ConstructorDeclaration) {
com.github.javaparser.ast.body.ConstructorDeclaration constructorDeclaration = (com.github.javaparser.ast.body.ConstructorDeclaration) member;
declared.add(new JavaParserConstructorDeclaration(this, constructorDeclaration, typeSolver));
}
}
if (declared.isEmpty()) {
// If there are no constructors insert the default constructor
return ImmutableList.of(new DefaultConstructorDeclaration(this));
} else {
return declared;
}
}
#location 2
#vulnerability type CHECKERS_IMMUTABLE_CAST | Below is the vulnerable code, please generate the patch based on the following information. |
#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);
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SymbolReference<TypeDeclaration> solveType(String name, TypeSolver typeSolver) {
return JavaParserFactory.getContext(getParentNode(wrappedNode), typeSolver).solveType(name, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<TypeDeclaration> solveType(String name, TypeSolver typeSolver) {
return JavaParserFactory.getContext(wrappedNode.getParentNode(), typeSolver).solveType(name, typeSolver);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
// TODO consider call of static methods
if (wrappedNode.getScope() != null) {
try {
TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope());
return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
} catch (UnsolvedSymbolException e){
// ok, maybe it was instead a static access, so let's look for a type
if (wrappedNode.getScope() instanceof NameExpr){
String className = ((NameExpr)wrappedNode.getScope()).getName();
SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver);
if (ref.isSolved()) {
if (name.equals("getModifiers") && !ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver).isSolved()){
System.out.println("FOO");
}
SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver);
if (m.isSolved()) {
return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver));
} else {
throw new UnsolvedSymbolException(ref.getCorrespondingDeclaration().toString(), "Method "+name+" with parameterTypes "+parameterTypes);
}
} else {
throw e;
}
} else {
throw e;
}
}
} else {
if (wrappedNode.getParentNode() instanceof MethodCallExpr) {
MethodCallExpr parent = (MethodCallExpr)wrappedNode.getParentNode();
if (parent.getScope() == wrappedNode) {
return getParent().getParent().solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
//TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
//return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
Context parentContext = getParent();
//System.out.println("NAME "+name);
return parentContext.solveMethodAsUsage(name, parameterTypes, typeSolver);
}
} | #vulnerable code
@Override
public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) {
// TODO consider call of static methods
if (wrappedNode.getScope() != null) {
try {
TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope());
return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
} catch (UnsolvedSymbolException e){
// ok, maybe it was instead a static access, so let's look for a type
if (wrappedNode.getScope() instanceof NameExpr){
String className = ((NameExpr)wrappedNode.getScope()).getName();
SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver);
if (ref.isSolved()) {
SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver);
if (m.isSolved()) {
return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver));
} else {
throw new UnsolvedSymbolException(ref.getCorrespondingDeclaration().toString(), "Method "+name+" with parameterTypes "+parameterTypes);
}
} else {
throw e;
}
} else {
throw e;
}
}
} else {
if (wrappedNode.getParentNode() instanceof MethodCallExpr) {
MethodCallExpr parent = (MethodCallExpr)wrappedNode.getParentNode();
if (parent.getScope() == wrappedNode) {
return getParent().getParent().solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
//TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
//return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this);
Context parentContext = getParent();
//System.out.println("NAME "+name);
return parentContext.solveMethodAsUsage(name, parameterTypes, typeSolver);
}
}
#location 38
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) {
if (wrappedNode.getTypes() != null) {
for (TypeDeclaration<?> type : wrappedNode.getTypes()) {
if (type.getName().getId().equals(name)) {
if (type instanceof ClassOrInterfaceDeclaration) {
return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type));
} else if (type instanceof AnnotationDeclaration) {
return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver));
} else if (type instanceof EnumDeclaration) {
return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver));
} else {
throw new UnsupportedOperationException(type.getClass().getCanonicalName());
}
}
}
// look for member classes/interfaces of types in this compilation unit
if (name.indexOf('.') > -1) {
SymbolReference<ResolvedTypeDeclaration> ref = null;
SymbolReference<ResolvedTypeDeclaration> outerMostRef =
solveType(name.substring(0, name.indexOf(".")), typeSolver);
if (outerMostRef.isSolved() &&
outerMostRef.getCorrespondingDeclaration() instanceof JavaParserClassDeclaration) {
ref = ((JavaParserClassDeclaration) outerMostRef.getCorrespondingDeclaration())
.solveType(name.substring(name.indexOf(".") + 1), typeSolver);
}
if (ref != null && ref.isSolved()) {
return ref;
}
}
}
// Look in current package
if (this.wrappedNode.getPackageDeclaration().isPresent()) {
String qName = this.wrappedNode.getPackageDeclaration().get().getName().toString() + "." + name;
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
} else {
// look for classes in the default package
String qName = name;
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
}
if (wrappedNode.getImports() != null) {
int dotPos = name.indexOf('.');
String prefix = null;
if (dotPos > -1) {
prefix = name.substring(0, dotPos);
}
// look into type imports
for (ImportDeclaration importDecl : wrappedNode.getImports()) {
if (!importDecl.isAsterisk()) {
String qName = importDecl.getNameAsString();
boolean defaultPackage = !importDecl.getName().getQualifier().isPresent();
boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name);
if (!found) {
if (prefix != null) {
found = qName.endsWith("." + prefix);
if (found) {
qName = qName + name.substring(dotPos);
}
}
}
if (found) {
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
}
}
}
// look into type imports on demand
for (ImportDeclaration importDecl : wrappedNode.getImports()) {
if (importDecl.isAsterisk()) {
String qName = importDecl.getNameAsString() + "." + name;
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
}
}
}
// Look in the java.lang package
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType("java.lang." + name);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
// DO NOT look for absolute name if this name is not qualified: you cannot import classes from the default package
if (isQualifiedName(name)) {
return SymbolReference.adapt(typeSolver.tryToSolveType(name), ResolvedTypeDeclaration.class);
} else {
return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class);
}
} | #vulnerable code
@Override
public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) {
if (wrappedNode.getTypes() != null) {
for (TypeDeclaration<?> type : wrappedNode.getTypes()) {
if (type.getName().getId().equals(name)) {
if (type instanceof ClassOrInterfaceDeclaration) {
return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type));
} else if (type instanceof AnnotationDeclaration) {
return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver));
} else if (type instanceof EnumDeclaration) {
return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver));
} else {
throw new UnsupportedOperationException(type.getClass().getCanonicalName());
}
}
}
}
// Look in current package
if (this.wrappedNode.getPackageDeclaration().isPresent()) {
String qName = this.wrappedNode.getPackageDeclaration().get().getName().toString() + "." + name;
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
} else {
// look for classes in the default package
String qName = name;
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref != null && ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
}
if (wrappedNode.getImports() != null) {
int dotPos = name.indexOf('.');
String prefix = null;
if (dotPos > -1) {
prefix = name.substring(0, dotPos);
}
// look into type imports
for (ImportDeclaration importDecl : wrappedNode.getImports()) {
if (!importDecl.isAsterisk()) {
String qName = importDecl.getNameAsString();
boolean defaultPackage = !importDecl.getName().getQualifier().isPresent();
boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name);
if (!found) {
if (prefix != null) {
found = qName.endsWith("." + prefix);
if (found) {
qName = qName + name.substring(dotPos);
}
}
}
if (found) {
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
}
}
}
// look into type imports on demand
for (ImportDeclaration importDecl : wrappedNode.getImports()) {
if (importDecl.isAsterisk()) {
String qName = importDecl.getNameAsString() + "." + name;
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName);
if (ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
}
}
}
// Look in the java.lang package
SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType("java.lang." + name);
if (ref.isSolved()) {
return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class);
}
// DO NOT look for absolute name if this name is not qualified: you cannot import classes from the default package
if (isQualifiedName(name)) {
return SymbolReference.adapt(typeSolver.tryToSolveType(name), ResolvedTypeDeclaration.class);
} else {
return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class);
}
}
#location 57
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void saveAll() throws FileNotFoundException, UnsupportedEncodingException {
saveAll(root);
} | #vulnerable code
public void saveAll() throws FileNotFoundException, UnsupportedEncodingException {
for (CompilationUnit cu : compilationUnits) {
Path filename = cu.getData(ORIGINAL_LOCATION);
System.out.println("Saving " + filename);
filename.getParent().toFile().mkdirs();
String code = new PrettyPrinter().print(cu);
try (PrintWriter out = new PrintWriter(filename.toFile(), UTF8.toString())) {
out.println(code);
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> parameterTypes) {
Context ctx = getContext();
return ctx.solveMethod(name, parameterTypes, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> parameterTypes) {
return getContext().solveMethod(name, parameterTypes, typeSolver());
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void solveMethodCalls(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(".java")) {
if (printFileName) {
out.println("- parsing " + file.toAbsolutePath());
}
CompilationUnit cu = JavaParser.parse(file);
solveMethodCalls(cu);
}
return FileVisitResult.CONTINUE;
}
});
} | #vulnerable code
public void solveMethodCalls(Path path) throws IOException {
File file = path.toFile();
if (file.isDirectory()) {
for (File f : file.listFiles()) {
solveMethodCalls(f.toPath());
}
} else {
if (file.getName().endsWith(".java")) {
if (printFileName) {
out.println("- parsing " + file.getAbsolutePath());
}
CompilationUnit cu = JavaParser.parse(file);
solveMethodCalls(cu);
}
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#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.name());
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());
} | #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), 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());
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
}
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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;
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void parse(String fileName) throws IOException {
Path sourceFile = properSrc.resolve( fileName + ".java");
SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor();
OutputStream outErrStream = new ByteArrayOutputStream();
PrintStream outErr = new PrintStream(outErrStream);
sourceFileInfoExtractor.setOut(outErr);
sourceFileInfoExtractor.setErr(outErr);
sourceFileInfoExtractor.solve(sourceFile);
String output = outErrStream.toString();
String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt";
Path dstFile = adaptPath(root.resolve(path));
if (DEBUG && (sourceFileInfoExtractor.getFailures() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) {
System.err.println(output);
}
assertEquals(0, sourceFileInfoExtractor.getFailures(), "No failures expected when analyzing " + path);
assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path);
String expected = readFile(dstFile);
String[] outputLines = output.split("\n");
String[] expectedLines = expected.split("\n");
for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) {
assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected");
}
assertEquals(expectedLines.length, outputLines.length);
JavaParserFacade.clearInstances();
// If we need to update the file uncomment these lines
//PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8");
//writer.print(output);
//writer.close();
} | #vulnerable code
private void parse(String fileName) throws IOException {
Path sourceFile = properSrc.resolve( fileName + ".java");
SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor();
OutputStream outErrStream = new ByteArrayOutputStream();
PrintStream outErr = new PrintStream(outErrStream);
sourceFileInfoExtractor.setOut(outErr);
sourceFileInfoExtractor.setErr(outErr);
sourceFileInfoExtractor.solve(sourceFile);
String output = outErrStream.toString();
String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt";
Path dstFile = adaptPath(root.resolve(path));
if (DEBUG && (sourceFileInfoExtractor.getKo() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) {
System.err.println(output);
}
assertEquals(0, sourceFileInfoExtractor.getKo(), "No failures expected when analyzing " + path);
assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path);
String expected = readFile(dstFile);
String[] outputLines = output.split("\n");
String[] expectedLines = expected.split("\n");
for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) {
assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected");
}
assertEquals(expectedLines.length, outputLines.length);
JavaParserFacade.clearInstances();
// If we need to update the file uncomment these lines
//PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8");
//writer.print(output);
//writer.close();
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 6);
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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Optional<Value> solveSymbolAsValue(String name, TypeSolver typeSolver) {
return getParent().solveSymbolAsValue(name, typeSolver);
} | #vulnerable code
@Override
public Optional<Value> solveSymbolAsValue(String name, TypeSolver typeSolver) {
return JavaParserFactory.getContext(wrappedNode.getParentNode()).solveSymbolAsValue(name, typeSolver);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
if (wrappedNode.getFieldExpr().toString().equals(name)) {
if (wrappedNode.getScope() instanceof ThisExpr) {
Type typeOfThis = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
return new SymbolSolver(typeSolver).solveSymbolInType(typeOfThis.asReferenceType().getTypeDeclaration(), name);
}
}
return JavaParserFactory.getContext(getParentNode(wrappedNode), typeSolver).solveSymbol(name, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
if (wrappedNode.getFieldExpr().toString().equals(name)) {
if (wrappedNode.getScope() instanceof ThisExpr) {
Type typeOfThis = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
return new SymbolSolver(typeSolver).solveSymbolInType(typeOfThis.asReferenceType().getTypeDeclaration(), name);
}
}
return JavaParserFactory.getContext(wrappedNode.getParentNode(), typeSolver).solveSymbol(name, typeSolver);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Optional<Value> solveSymbolAsValue(String name, Node node) {
Context context = JavaParserFactory.getContext(node);
return solveSymbolAsValue(name, context);
} | #vulnerable code
public Optional<Value> solveSymbolAsValue(String name, Node node) {
return solveSymbolAsValue(name, JavaParserFactory.getContext(node));
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException {
File src = new File("src/test/resources/internalClassInInterface");
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("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4);
assertTrue(fae.isPresent());
assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe());
assertEquals("ADDITION", fae.get().resolve().getName());
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 6);
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 | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 6);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("OR", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException {
File src = new File("src/test/resources/enumLiteralsInAnnotatedClass");
File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar"
+ File.separator + "differentpackage" + File.separator + "AClass2.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 == 6);
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 | Below is the vulnerable code, please generate the patch based on the following information. |
#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());
} | #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 | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.