instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTokenPattern() { TokenPattern pattern = TokenPattern.builder() .compile("(method|hidden|local) [static] <return-type> <name>(<parameters>) \\{ <body> \\}[;]") .build(); LexicalPatternElement content = pattern.getPatternContent(); Assertions.assertNotNull(content); TokenExtractorResult result = pattern.extract(SOURCE); Assertions.assertNotNull(result); //Assertions.assertTrue(result.isMatched()); }
#vulnerable code @Test public void testTokenPattern() { TokenPattern pattern = TokenPattern.builder() .compile("(method|hidden|local) [static] <return-type> <name>(<parameters>) \\{ <body> \\}[;]") .build(); LexicalPatternElement content = pattern.getPatternContent(); Assertions.assertNotNull(content); TokenExtractorResult result = pattern.extract(SOURCE); Assertions.assertNotNull(result); Assertions.assertTrue(result.isMatched()); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Expression parse(ParserInfo info, TokenizedSource expressionSource) { if (expressionSource.size() == 1) { Token token = expressionSource.getToken(0); String value = token.getTokenValue(); if (token.getType() == TokenType.LITERAL) { switch (token.getTokenValue()) { case "null": return new Expression(new PandaValue(null, null)); case "true": return toSimpleKnownExpression("panda.lang:Boolean", true); case "false": return toSimpleKnownExpression("panda.lang:Boolean", false); case "this": ClassPrototype type = info.getComponent(Components.CLASS_PROTOTYPE); return new Expression(type, new ThisExpressionCallback()); default: throw new PandaParserException("Unknown literal: " + token); } } if (token.getType() == TokenType.SEQUENCE) { switch (token.getName()) { case "String": return toSimpleKnownExpression("panda.lang:String", value); default: throw new PandaParserException("Unknown sequence: " + token); } } if (NumberUtils.isNumber(value)) { return toSimpleKnownExpression("panda.lang:Int", Integer.parseInt(value)); } ScopeLinker scopeLinker = info.getComponent(Components.SCOPE_LINKER); Scope scope = scopeLinker.getCurrentScope(); Variable variable = VariableParserUtils.getVariable(scope, value); if (variable != null) { int memoryIndex = VariableParserUtils.indexOf(scope, variable); return new Expression(variable.getType(), new VariableExpressionCallback(memoryIndex)); } ClassPrototype prototype = info.getComponent(Components.CLASS_PROTOTYPE); Field field = prototype.getField(value); if (field != null) { int memoryIndex = prototype.getFields().indexOf(field); return new Expression(field.getType(), new FieldExpressionCallback(ThisExpressionCallback.asExpression(prototype), field, memoryIndex)); } } else if (TokenUtils.equals(expressionSource.get(0), TokenType.KEYWORD, "new")) { InstanceExpressionParser callbackParser = new InstanceExpressionParser(); callbackParser.parse(expressionSource, info); InstanceExpressionCallback callback = callbackParser.toCallback(); return new Expression(callback.getReturnType(), callback); } PandaTokenReader expressionReader = new PandaTokenReader(expressionSource); List<TokenizedSource> methodMatches = MethodInvokerExpressionParser.PATTERN.match(expressionReader); if (methodMatches != null && methodMatches.size() > 0) { MethodInvokerExpressionParser callbackParser = new MethodInvokerExpressionParser(methodMatches); callbackParser.parse(expressionSource, info); MethodInvokerExpressionCallback callback = callbackParser.toCallback(); return new Expression(callback.getReturnType(), callback); } List<TokenizedSource> fieldMatches = FIELD_PATTERN.match(expressionReader); if (fieldMatches != null && fieldMatches.size() == 2) { Expression instanceExpression = parse(info, fieldMatches.get(0)); ClassPrototype instanceType = instanceExpression.getReturnType(); Field instanceField = instanceType.getField(fieldMatches.get(1).getLast().getToken().getTokenValue()); if (instanceField == null) { } int memoryIndex = instanceType.getFields().indexOf(instanceField); return new Expression(instanceType, new FieldExpressionCallback(instanceExpression, instanceField, memoryIndex)); } throw new PandaParserException("Cannot recognize expression: " + expressionSource.toString()); }
#vulnerable code public Expression parse(ParserInfo info, TokenizedSource expressionSource) { if (expressionSource.size() == 1) { Token token = expressionSource.getToken(0); String value = token.getTokenValue(); if (token.getType() == TokenType.LITERAL) { switch (token.getTokenValue()) { case "null": return new Expression(new PandaValue(null, null)); case "true": return toSimpleKnownExpression("panda.lang:Boolean", true); case "false": return toSimpleKnownExpression("panda.lang:Boolean", false); case "this": ClassPrototype type = info.getComponent(Components.CLASS_PROTOTYPE); return new Expression(type, new ThisExpressionCallback()); default: throw new PandaParserException("Unknown literal: " + token); } } if (token.getType() == TokenType.SEQUENCE) { switch (token.getName()) { case "String": return toSimpleKnownExpression("panda.lang:String", value); default: throw new PandaParserException("Unknown sequence: " + token); } } if (NumberUtils.isNumber(value)) { return toSimpleKnownExpression("panda.lang:Int", Integer.parseInt(value)); } ScopeLinker scopeLinker = info.getComponent(Components.SCOPE_LINKER); Scope scope = scopeLinker.getCurrentScope(); Variable variable = VariableParserUtils.getVariable(scope, value); if (variable != null) { int memoryIndex = VariableParserUtils.indexOf(scope, variable); return new Expression(variable.getType(), new VariableExpressionCallback(memoryIndex)); } ClassPrototype prototype = info.getComponent(Components.CLASS_PROTOTYPE); Field field = prototype.getField(value); if (field != null) { int memoryIndex = prototype.getFields().indexOf(field); return new Expression(field.getType(), new FieldExpressionCallback(field, memoryIndex)); } } else if (TokenUtils.equals(expressionSource.get(0), TokenType.KEYWORD, "new")) { InstanceExpressionParser callbackParser = new InstanceExpressionParser(); callbackParser.parse(expressionSource, info); InstanceExpressionCallback callback = callbackParser.toCallback(); return new Expression(callback.getReturnType(), callback); } PandaTokenReader expressionReader = new PandaTokenReader(expressionSource); List<TokenizedSource> methodMatches = MethodInvokerExpressionParser.PATTERN.match(expressionReader); if (methodMatches != null && methodMatches.size() > 0) { MethodInvokerExpressionParser callbackParser = new MethodInvokerExpressionParser(methodMatches); callbackParser.parse(expressionSource, info); MethodInvokerExpressionCallback callback = callbackParser.toCallback(); return new Expression(callback.getReturnType(), callback); } List<TokenizedSource> fieldMatches = FieldParser.PATTERN.match(expressionReader); if (fieldMatches != null && fieldMatches.size() > 0) { } throw new PandaParserException("Cannot recognize expression: " + expressionSource.toString()); } #location 58 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Essence run(Particle particle) { while (factors[0].getValue(PBoolean.class).isTrue()) { Essence o = super.run(particle); if (o != null) { return o; } } return null; }
#vulnerable code @Override public Essence run(Particle particle) { while (parameters[0].getValue(PBoolean.class).isTrue()) { Essence o = super.run(particle); if (o != null) { return o; } } return null; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isPublic(Object o) { if (o == null) { return false; } if (o instanceof ClassFile) { return AccessFlag.isPublic(((ClassFile) o).getAccessFlags()); } if (o instanceof MethodInfo) { return AccessFlag.isPublic(((MethodInfo) o).getAccessFlags()); } if (o instanceof FieldInfo) { return AccessFlag.isPublic(((FieldInfo) o).getAccessFlags()); } return false; }
#vulnerable code public boolean isPublic(Object o) { int accessFlags = o instanceof ClassFile ? ((ClassFile) o).getAccessFlags() : o instanceof FieldInfo ? ((FieldInfo) o).getAccessFlags() : o instanceof MethodInfo ? ((MethodInfo) o).getAccessFlags() : null; return AccessFlag.isPublic(accessFlags); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean extract(TokenizedSource tokenizedSource) { TokenPatternUnit[] units = pattern.getUnits(); ArrayDistributor<TokenPatternUnit> unitsDistributor = new ArrayDistributor<>(units); TokenReader tokenReader = new PandaTokenReader(tokenizedSource); TokenHollow hollow = new TokenHollow(); for (int unitIndex = 0; unitIndex < units.length; unitIndex++) { TokenPatternUnit unit = unitsDistributor.get(unitIndex); tokenReader.synchronize(); for (TokenRepresentation representation : tokenReader) { Token token = representation.getToken(); if (unit.equals(token)) { tokenReader.read(); break; } if (!unit.isHollow()) { return false; } TokenPatternUnit nextUnit = unitsDistributor.get(unitIndex + 1); if (!token.equals(nextUnit) || extractorOpposites.isLocked()) { extractorOpposites.report(token); tokenReader.read(); hollow.addToken(token); continue; } hollows.add(hollow); hollow = new TokenHollow(); break; } } return tokenReader.getIndex() + 1 >= tokenizedSource.size(); }
#vulnerable code public boolean extract(TokenizedSource tokenizedSource) { TokenPatternUnit[] units = pattern.getUnits(); ArrayDistributor<TokenPatternUnit> unitsDistributor = new ArrayDistributor<>(units); TokenReader tokenReader = new PandaTokenReader(tokenizedSource); Stack<Separator> separators = new Stack<>(); for (int unitIndex = 0; unitIndex < units.length; unitIndex++) { TokenPatternUnit unit = unitsDistributor.get(unitIndex); TokenPatternUnit nextUnit = unitsDistributor.get(unitIndex + 1); loop: if (!unit.isHollow()) { } else { } } return tokenReader.getIndex() >= tokenizedSource.size(); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public @Nullable Expression parse(ParserData data, TokenizedSource expressionSource, boolean silence) { ModuleRegistry registry = data.getComponent(PandaComponents.MODULE_REGISTRY); if (expressionSource.size() == 1) { Token token = expressionSource.getToken(0); if (token == null) { throw new PandaParserException("Internal error, token is null"); } String value = token.getTokenValue(); if (token.getType() == TokenType.LITERAL) { switch (token.getTokenValue()) { case "null": return new PandaExpression(new PandaValue(null, null)); case "true": return toSimpleKnownExpression(registry, "boolean", true); case "false": return toSimpleKnownExpression(registry, "boolean", false); case "this": ClassPrototype type = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE); return new PandaExpression(type, new ThisExpressionCallback()); default: throw new PandaParserException("Unknown literal: " + token); } } if (token.getType() == TokenType.SEQUENCE) { switch (token.getName()) { case "String": return toSimpleKnownExpression(registry, "java.lang:String", value); default: throw new PandaParserException("Unknown sequence: " + token); } } NumberExpressionParser numberExpressionParser = new NumberExpressionParser(); Value numericValue = numberExpressionParser.parse(data, expressionSource); if (numericValue != null) { return new PandaExpression(numericValue); } ScopeLinker scopeLinker = data.getComponent(PandaComponents.SCOPE_LINKER); Scope scope = scopeLinker.getCurrentScope(); Variable variable = VariableParserUtils.getVariable(scope, value); if (variable != null) { int memoryIndex = VariableParserUtils.indexOf(scope, variable); return new PandaExpression(variable.getType(), new VariableExpressionCallback(memoryIndex)); } ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE); if (prototype != null) { PrototypeField field = prototype.getField(value); if (field != null) { int memoryIndex = prototype.getFields().indexOf(field); return new PandaExpression(field.getType(), new FieldExpressionCallback(ThisExpressionCallback.asExpression(prototype), field, memoryIndex)); } } } if (TokenUtils.equals(expressionSource.getFirst(), Operators.NOT)) { Expression expression = parse(data, expressionSource.subSource(1, expressionSource.size())); return new PandaExpression(expression.getReturnType(), new NotLogicalExpressionCallback(expression)); } MethodInvokerExpressionParser methodInvokerParser = MethodInvokerExpressionUtils.match(expressionSource); if (methodInvokerParser != null) { methodInvokerParser.parse(expressionSource, data); MethodInvokerExpressionCallback callback = methodInvokerParser.toCallback(); return new PandaExpression(callback.getReturnType(), callback); } TokenReader expressionReader = new PandaTokenReader(expressionSource); List<TokenizedSource> constructorMatches = ExpressionPatterns.INSTANCE_PATTERN.match(expressionReader); if (constructorMatches != null && constructorMatches.size() == 3 && constructorMatches.get(2).size() == 0) { InstanceExpressionParser callbackParser = new InstanceExpressionParser(); callbackParser.parse(expressionSource, data); InstanceExpressionCallback callback = callbackParser.toCallback(); return new PandaExpression(callback.getReturnType(), callback); } List<TokenizedSource> fieldMatches = ExpressionPatterns.FIELD_PATTERN.match(expressionReader); if (fieldMatches != null && fieldMatches.size() == 2 && !NumberUtils.startsWithNumber(fieldMatches.get(1))) { PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT); ImportRegistry importRegistry = script.getImportRegistry(); TokenizedSource instanceSource = fieldMatches.get(0); ClassPrototype instanceType = null; Expression fieldLocationExpression = null; if (instanceSource.size() == 1) { instanceType = importRegistry.forClass(fieldMatches.get(0).asString()); } if (instanceType == null) { fieldLocationExpression = parse(data, fieldMatches.get(0)); instanceType = fieldLocationExpression.getReturnType(); } if (instanceType == null) { throw new PandaParserException("Unknown instance source at line " + TokenUtils.getLine(instanceSource)); } String instanceFieldName = fieldMatches.get(1).asString(); PrototypeField instanceField = instanceType.getField(instanceFieldName); if (instanceField == null) { throw new PandaParserException("Class " + instanceType.getClassName() + " does not contain field " + instanceFieldName + " at " + TokenUtils.getLine(expressionSource)); } int memoryIndex = instanceType.getFields().indexOf(instanceField); return new PandaExpression(instanceField.getType(), new FieldExpressionCallback(fieldLocationExpression, instanceField, memoryIndex)); } NumberExpressionParser numberExpressionParser = new NumberExpressionParser(); Value numericValue = numberExpressionParser.parse(data, expressionSource); if (numericValue != null) { return new PandaExpression(numericValue); } if (MathExpressionUtils.isMathExpression(expressionSource)) { MathParser mathParser = new MathParser(); MathExpressionCallback expression = mathParser.parse(expressionSource, data); return new PandaExpression(expression.getReturnType(), expression); } if (!silence) { throw new PandaParserException("Cannot recognize expression: " + expressionSource); } return null; }
#vulnerable code public @Nullable Expression parse(ParserData data, TokenizedSource expressionSource, boolean silence) { ModuleRegistry registry = data.getComponent(PandaComponents.MODULE_REGISTRY); if (expressionSource.size() == 1) { Token token = expressionSource.getToken(0); String value = token.getTokenValue(); if (token.getType() == TokenType.LITERAL) { switch (token.getTokenValue()) { case "null": return new PandaExpression(new PandaValue(null, null)); case "true": return toSimpleKnownExpression(registry, "boolean", true); case "false": return toSimpleKnownExpression(registry, "boolean", false); case "this": ClassPrototype type = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE); return new PandaExpression(type, new ThisExpressionCallback()); default: throw new PandaParserException("Unknown literal: " + token); } } if (token.getType() == TokenType.SEQUENCE) { switch (token.getName()) { case "String": return toSimpleKnownExpression(registry, "java.lang:String", value); default: throw new PandaParserException("Unknown sequence: " + token); } } NumberExpressionParser numberExpressionParser = new NumberExpressionParser(); Value numericValue = numberExpressionParser.parse(data, expressionSource); if (numericValue != null) { return new PandaExpression(numericValue); } ScopeLinker scopeLinker = data.getComponent(PandaComponents.SCOPE_LINKER); Scope scope = scopeLinker.getCurrentScope(); Variable variable = VariableParserUtils.getVariable(scope, value); if (variable != null) { int memoryIndex = VariableParserUtils.indexOf(scope, variable); return new PandaExpression(variable.getType(), new VariableExpressionCallback(memoryIndex)); } ClassPrototype prototype = data.getComponent(ClassPrototypeComponents.CLASS_PROTOTYPE); if (prototype != null) { PrototypeField field = prototype.getField(value); if (field != null) { int memoryIndex = prototype.getFields().indexOf(field); return new PandaExpression(field.getType(), new FieldExpressionCallback(ThisExpressionCallback.asExpression(prototype), field, memoryIndex)); } } } if (TokenUtils.equals(expressionSource.getFirst(), Operators.NOT)) { Expression expression = parse(data, expressionSource.subSource(1, expressionSource.size())); return new PandaExpression(expression.getReturnType(), new NotLogicalExpressionCallback(expression)); } MethodInvokerExpressionParser methodInvokerParser = MethodInvokerExpressionUtils.match(expressionSource); if (methodInvokerParser != null) { methodInvokerParser.parse(expressionSource, data); MethodInvokerExpressionCallback callback = methodInvokerParser.toCallback(); return new PandaExpression(callback.getReturnType(), callback); } TokenReader expressionReader = new PandaTokenReader(expressionSource); List<TokenizedSource> constructorMatches = ExpressionPatterns.INSTANCE_PATTERN.match(expressionReader); if (constructorMatches != null && constructorMatches.size() == 3 && constructorMatches.get(2).size() == 0) { InstanceExpressionParser callbackParser = new InstanceExpressionParser(); callbackParser.parse(expressionSource, data); InstanceExpressionCallback callback = callbackParser.toCallback(); return new PandaExpression(callback.getReturnType(), callback); } List<TokenizedSource> fieldMatches = ExpressionPatterns.FIELD_PATTERN.match(expressionReader); if (fieldMatches != null && fieldMatches.size() == 2 && !NumberUtils.startsWithNumber(fieldMatches.get(1))) { PandaScript script = data.getComponent(PandaComponents.PANDA_SCRIPT); ImportRegistry importRegistry = script.getImportRegistry(); TokenizedSource instanceSource = fieldMatches.get(0); ClassPrototype instanceType = null; Expression fieldLocationExpression = null; if (instanceSource.size() == 1) { instanceType = importRegistry.forClass(fieldMatches.get(0).asString()); } if (instanceType == null) { fieldLocationExpression = parse(data, fieldMatches.get(0)); instanceType = fieldLocationExpression.getReturnType(); } if (instanceType == null) { throw new PandaParserException("Unknown instance source at line " + TokenUtils.getLine(instanceSource)); } String instanceFieldName = fieldMatches.get(1).asString(); PrototypeField instanceField = instanceType.getField(instanceFieldName); if (instanceField == null) { throw new PandaParserException("Class " + instanceType.getClassName() + " does not contain field " + instanceFieldName + " at " + TokenUtils.getLine(expressionSource)); } int memoryIndex = instanceType.getFields().indexOf(instanceField); return new PandaExpression(instanceField.getType(), new FieldExpressionCallback(fieldLocationExpression, instanceField, memoryIndex)); } NumberExpressionParser numberExpressionParser = new NumberExpressionParser(); Value numericValue = numberExpressionParser.parse(data, expressionSource); if (numericValue != null) { return new PandaExpression(numericValue); } if (MathExpressionUtils.isMathExpression(expressionSource)) { MathParser mathParser = new MathParser(); MathExpressionCallback expression = mathParser.parse(expressionSource, data); return new PandaExpression(expression.getReturnType(), expression); } if (!silence) { throw new PandaParserException("Cannot recognize expression: " + expressionSource.toString()); } return null; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Variable createVariable(ParserData data, ModuleLoader loader, Scope scope, boolean mutable, boolean nullable, String type, String name) { if (StringUtils.isEmpty(type)) { throw new PandaParserFailure("Type does not specified", data); } Optional<ClassPrototypeReference> prototype = loader.forClass(type); if (!prototype.isPresent()) { throw new PandaParserFailure("Cannot recognize variable type: " + type, data); } Variable variable = new PandaVariable(prototype.get(), name, 0, mutable, nullable); scope.addVariable(variable); return variable; }
#vulnerable code public Variable createVariable(ParserData data, ModuleLoader loader, Scope scope, boolean mutable, boolean nullable, String type, String name) { ClassPrototype prototype = loader.forClass(type).fetch(); if (!StringUtils.isEmpty(type) && prototype == null) { throw new PandaParserFailure("Cannot recognize variable type: " + type, data); } Variable variable = new PandaVariable(prototype, name, 0, mutable, nullable); scope.addVariable(variable); return variable; } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Parameter> parse(ParserData info, @Nullable Tokens tokens) { if (TokensUtils.isEmpty(tokens)) { return new ArrayList<>(0); } TokenRepresentation[] tokenRepresentations = tokens.toArray(); List<Parameter> parameters = new ArrayList<>(tokenRepresentations.length / 3 + 1); if (tokens.size() == 0) { return parameters; } for (int i = 0; i < tokenRepresentations.length; i += 3) { TokenRepresentation parameterTypeRepresentation = tokenRepresentations[i]; TokenRepresentation parameterNameRepresentation = tokenRepresentations[i + 1]; String parameterType = parameterTypeRepresentation.getToken().getTokenValue(); String parameterName = parameterNameRepresentation.getToken().getTokenValue(); PandaScript script = info.getComponent(PandaComponents.PANDA_SCRIPT); ModuleLoader moduleLoader = script.getModuleLoader(); ClassPrototypeReference type = moduleLoader.forClass(parameterType); if (type == null) { throw new PandaParserException("Unknown type '" + parameterType + "'"); } Parameter parameter = new PandaParameter(type, parameterName); parameters.add(parameter); if (i + 2 < tokenRepresentations.length) { TokenRepresentation separatorRepresentation = tokenRepresentations[i + 2]; Token separator = separatorRepresentation.getToken(); if (separator.getType() != TokenType.SEPARATOR) { throw new PandaParserException("Unexpected token " + separatorRepresentation); } } } return parameters; }
#vulnerable code public List<Parameter> parse(ParserData info, @Nullable Tokens tokens) { if (TokensUtils.isEmpty(tokens)) { return new ArrayList<>(0); } TokenRepresentation[] tokenRepresentations = tokens.toArray(); List<Parameter> parameters = new ArrayList<>(tokenRepresentations.length / 3 + 1); if (tokens.size() == 0) { return parameters; } for (int i = 0; i < tokenRepresentations.length; i += 3) { TokenRepresentation parameterTypeRepresentation = tokenRepresentations[i]; TokenRepresentation parameterNameRepresentation = tokenRepresentations[i + 1]; String parameterType = parameterTypeRepresentation.getToken().getTokenValue(); String parameterName = parameterNameRepresentation.getToken().getTokenValue(); PandaScript script = info.getComponent(PandaComponents.PANDA_SCRIPT); ModuleLoader moduleLoader = script.getModuleLoader(); ClassPrototype type = moduleLoader.forClass(parameterType).get(); if (type == null) { throw new PandaParserException("Unknown type '" + parameterType + "'"); } Parameter parameter = new PandaParameter(type, parameterName); parameters.add(parameter); if (i + 2 < tokenRepresentations.length) { TokenRepresentation separatorRepresentation = tokenRepresentations[i + 2]; Token separator = separatorRepresentation.getToken(); if (separator.getType() != TokenType.SEPARATOR) { throw new PandaParserException("Unexpected token " + separatorRepresentation); } } } return parameters; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SafeVarargs @SuppressWarnings("unchecked") public static <T> T[] mergeArrays(T[]... arrays) { if (isEmpty(arrays)) { throw new IllegalArgumentException("Merge arrays requires at least one array as argument"); } return mergeArrays(length -> (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length), arrays); }
#vulnerable code @SafeVarargs @SuppressWarnings("unchecked") public static <T> T[] mergeArrays(T[]... arrays) { int size = 0; Class<?> type = null; for (T[] array : arrays) { size += array.length; type = array.getClass().getComponentType(); } T[] mergedArray = (T[]) Array.newInstance(type, size); int index = 0; for (T[] array : arrays) { for (T element : array) { mergedArray[index++] = element; } } return mergedArray; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public PrototypeMethod generate(ModuleRegistry registry) { ClassPrototype returnType = PandaModuleRegistryAssistant.forClass(registry, method.getReturnType()); ClassPrototype[] parametersTypes = PandaClassPrototypeUtils.toTypes(registry, method.getParameterTypes()); if (returnType == null) { throw new PandaRuntimeException("Cannot generate method for 'null' return type"); } boolean isVoid = returnType.getClassName().equals("void"); // TODO: Generate bytecode MethodCallback<Object> methodBody = (branch, instance, parameters) -> { try { int amountOfArgs = parameters.length; int parameterCount = method.getParameterCount(); Object varargs = null; if (amountOfArgs != parameterCount) { if (parameterCount < 1) { throw new PandaRuntimeException("Too many arguments"); } Class<?> last = method.getParameterTypes()[parameterCount - 1]; String lastName = last.getName(); Class<?> rootLast = Class.forName(lastName.substring(2, lastName.length() - 1)); if (amountOfArgs + 1 != parameterCount || !last.isArray()) { throw new PandaRuntimeException("Cannot invoke mapped mapped method (args.length != parameters.length)"); } varargs = Array.newInstance(rootLast, 0); amountOfArgs++; } Object[] args = new Object[amountOfArgs]; for (int i = 0; i < parameters.length; i++) { Value parameter = parameters[i]; if (parameter == null) { continue; } args[i] = parameter.getValue(); } if (varargs != null) { args[amountOfArgs - 1] = varargs; } Object returnValue = method.invoke(instance, args); if (isVoid) { return; } Value value = new PandaValue(returnType, returnValue); branch.setReturnValue(value); } catch (Exception e) { e.printStackTrace(); } }; return PandaMethod.builder() .prototype(prototype) .visibility(MethodVisibility.PUBLIC) .isStatic(Modifier.isStatic(method.getModifiers())) .returnType(returnType) .methodName(method.getName()) .methodBody(methodBody) .parameterTypes(parametersTypes) .build(); }
#vulnerable code public PrototypeMethod generate(ModuleRegistry registry) { ClassPrototype returnType = PandaModuleRegistryAssistant.forClass(registry, method.getReturnType()); ClassPrototype[] parametersTypes = PandaClassPrototypeUtils.toTypes(registry, method.getParameterTypes()); boolean isVoid = returnType.getClassName().equals("void"); // TODO: Generate bytecode MethodCallback<Object> methodBody = (branch, instance, parameters) -> { try { int amountOfArgs = parameters.length; int parameterCount = method.getParameterCount(); Object varargs = null; if (amountOfArgs != parameterCount) { if (parameterCount < 1) { throw new PandaRuntimeException("Too many arguments"); } Class<?> last = method.getParameterTypes()[parameterCount - 1]; String lastName = last.getName(); Class<?> rootLast = Class.forName(lastName.substring(2, lastName.length() - 1)); if (amountOfArgs + 1 != parameterCount || !last.isArray()) { throw new PandaRuntimeException("Cannot invoke mapped mapped method (args.length != parameters.length)"); } varargs = Array.newInstance(rootLast, 0); ++amountOfArgs; } Object[] args = new Object[amountOfArgs]; for (int i = 0; i < parameters.length; i++) { Value parameter = parameters[i]; if (parameter == null) { continue; } args[i] = parameter.getValue(); } if (varargs != null) { args[amountOfArgs - 1] = varargs; } Object returnValue = method.invoke(instance, args); if (isVoid) { return; } Value value = new PandaValue(returnType, returnValue); branch.setReturnValue(value); } catch (Exception e) { e.printStackTrace(); } }; return PandaMethod.builder() .prototype(prototype) .visibility(MethodVisibility.PUBLIC) .isStatic(Modifier.isStatic(method.getModifiers())) .returnType(returnType) .methodName(method.getName()) .methodBody(methodBody) .parameterTypes(parametersTypes) .build(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void getURLContent() { Result<String, IOException> result = IOUtils.fetchContent("https://panda-lang.org/"); assertTrue(result.isDefined()); assertNotNull(result.getValue()); assertTrue(result.getValue().contains("<html")); }
#vulnerable code @Test void getURLContent() { String urlContent = IOUtils.getURLContent("https://panda-lang.org/"); Assertions.assertNotNull(urlContent); Assertions.assertTrue(urlContent.contains("<html")); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Expression parse(ParserData data, SourceStream source, ExpressionParserSettings settings) { return parse(data, source, settings, null); }
#vulnerable code public Expression parse(ParserData data, SourceStream source, ExpressionParserSettings settings) { ExpressionContext context = new ExpressionContext(this, data, source); ExpressionParserWorker worker = new ExpressionParserWorker(this, context, source, subparsers, settings.isCombined()); for (TokenRepresentation representation : context.getDiffusedSource()) { if (!worker.next(context.withUpdatedToken(representation))) { break; } } worker.finish(context); // if something went wrong if (worker.hasError()) { throw new ExpressionParserException(worker.getError().getErrorMessage(), context, worker.getError().getSource()); } // if context does not contain any results if (!context.hasResults()) { throw new ExpressionParserException("Unknown expression", context, source.toSnippet()); } for (ExpressionResultProcessor processor : new ReversedIterable<>(context.getProcessors())) { ExpressionResult<Expression> result = processor.process(context, context.getResults()); if (result.containsError()) { throw new ExpressionParserException("Error occurred while processing the result: ", result.getErrorMessage(), context, context.getSource().toSnippet()); } context.getResults().push(result.get()); } // if worker couldn't prepare the final result if (context.getResults().size() > 1) { throw new ExpressionParserException("Source contains " + context.getResults().size() + " expressions", context, source.toSnippet()); } source.read(worker.getLastSucceededRead()); return context.getResults().pop(); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public PandaMethodBuilder parameterTypes(ModuleLoader moduleLoader, String... parameterTypes) { ClassPrototypeReference[] prototypes = new ClassPrototypeReference[parameterTypes.length]; for (int i = 0; i < prototypes.length; i++) { prototypes[i] = moduleLoader.forClass(parameterTypes[i]); } this.parameterTypes = prototypes; return this; }
#vulnerable code public PandaMethodBuilder parameterTypes(ModuleLoader moduleLoader, String... parameterTypes) { ClassPrototype[] prototypes = new ClassPrototype[parameterTypes.length]; for (int i = 0; i < prototypes.length; i++) { prototypes[i] = moduleLoader.forClass(parameterTypes[i]).get(); } this.parameterTypes = prototypes; return this; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTokenPattern() { TokenPattern pattern = TokenPattern.builder() .compile("class <name> [extends <inherited>] `{ <*body> `}") .build(); LexicalPatternElement content = pattern.getPatternContent(); Assertions.assertNotNull(content); TokenExtractorResult result = pattern.extract(SOURCE); Assertions.assertNotNull(result); if (result.hasErrorMessage()) { System.out.println("Error message: " + result.getErrorMessage()); } Assertions.assertTrue(result.isMatched()); Assertions.assertNotNull(result.getWildcards()); System.out.println(result.getWildcards()); Assertions.assertEquals(2, result.getWildcards().size()); Assertions.assertEquals("Foo", result.getWildcards().get("name").asString()); Assertions.assertEquals("methodanotherEcho(Stringmessage){Console.print(message);}", result.getWildcards().get("*body").asString()); }
#vulnerable code @Test public void testTokenPattern() { TokenPattern pattern = TokenPattern.builder() .compile("(method|hidden|local) [static] <return-type> <name> `(<*parameters>`) `{ <*body> `}[;]") .build(); LexicalPatternElement content = pattern.getPatternContent(); Assertions.assertNotNull(content); TokenExtractorResult result = pattern.extract(SOURCE); Assertions.assertNotNull(result); if (result.hasErrorMessage()) { System.out.println("Error message: " + result.getErrorMessage()); } Assertions.assertTrue(result.isMatched()); Assertions.assertNotNull(result.getWildcards()); Assertions.assertEquals(4, result.getWildcards().size()); Assertions.assertEquals("void", result.getWildcards().get("return-type").asString()); Assertions.assertEquals("test", result.getWildcards().get("name").asString()); Assertions.assertEquals("15,()25", result.getWildcards().get("*parameters").asString()); Assertions.assertEquals("Console.print(test)", result.getWildcards().get("*body").asString()); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void prepare() { AbyssExtractorOpposites opposites = new AbyssExtractorOpposites(); for (int i = 0; i < tokenizedSource.size(); i++) { TokenRepresentation representation = tokenizedSource.get(i); if (representation == null) { throw new PandaRuntimeException("Representation is null"); } Token token = representation.getToken(); boolean levelUp = opposites.report(token); int nestingLevel = levelUp ? opposites.getNestingLevel() - 1 : opposites.getNestingLevel(); AbyssTokenRepresentation abyssRepresentation = new AbyssTokenRepresentation(representation, nestingLevel); abyssRepresentations[i] = abyssRepresentation; } }
#vulnerable code private void prepare() { AbyssExtractorOpposites opposites = new AbyssExtractorOpposites(); for (int i = 0; i < tokenizedSource.size(); i++) { TokenRepresentation representation = tokenizedSource.get(i); Token token = representation.getToken(); boolean levelUp = opposites.report(token); int nestingLevel = levelUp ? opposites.getNestingLevel() - 1 : opposites.getNestingLevel(); AbyssTokenRepresentation abyssRepresentation = new AbyssTokenRepresentation(representation, nestingLevel); abyssRepresentations[i] = abyssRepresentation; } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public NamedExecutable parse(Atom atom) { final String source = atom.getSourcesDivider().getLine(); final StringBuilder groupBuilder = new StringBuilder(); boolean nsFlag = false; for (char c : source.toCharArray()) { if (Character.isWhitespace(c)) { nsFlag = true; } else if (c == ';') { break; } else if (nsFlag) { groupBuilder.append(c); } } String groupName = groupBuilder.toString(); Group group = GroupCenter.getGroup(groupName); atom.getPandaParser().getPandaBlock().setGroup(group); return group; }
#vulnerable code @Override public NamedExecutable parse(Atom atom) { final String source = atom.getSourceCode(); final StringBuilder groupBuilder = new StringBuilder(); boolean nsFlag = false; for (char c : source.toCharArray()) { if (Character.isWhitespace(c)) { nsFlag = true; } else if (c == ';') { break; } else if (nsFlag) { groupBuilder.append(c); } } String groupName = groupBuilder.toString(); Group group = GroupCenter.getGroup(groupName); atom.getPandaParser().getPandaBlock().setGroup(group); return group; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Type getArrayOf(Module module, Referencable baseReferencable, int dimensions) { Reference baseReference = baseReferencable.toReference(); Class<?> componentType = ArrayUtils.getDimensionalArrayType(baseReference.getAssociatedClass().fetchImplementation(), dimensions); Class<?> arrayType = ArrayUtils.getArrayClass(componentType); Reference componentReference; if (componentType.isArray()) { componentReference = fetch(module, componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> { throw new PandaFrameworkException("Cannot fetch array class for array type " + componentType); }); } else { componentReference = module.forClass(componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> { throw new PandaFrameworkException("Cannot fetch array class for " + componentType); }); } ArrayType arraType = new ArrayType(module, arrayType, componentReference.fetch()); ARRAY_PROTOTYPES.put(baseReference.getName() + dimensions, arraType); ModuleLoader loader = module.getModuleLoader(); arraType.getMethods().declare("size", () -> ArrayClassTypeConstants.SIZE.apply(loader)); arraType.getMethods().declare("toString", () -> ArrayClassTypeConstants.TO_STRING.apply(loader)); module.add(arraType); return arraType; }
#vulnerable code public static Type getArrayOf(Module module, Referencable baseReferencable, int dimensions) { Reference baseReference = baseReferencable.toReference(); Class<?> componentType = ArrayUtils.getDimensionalArrayType(baseReference.getAssociatedClass().fetchImplementation(), dimensions); Class<?> arrayType = ArrayUtils.getArrayClass(componentType); Reference componentReference; if (componentType.isArray()) { componentReference = fetch(module, componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> { throw new PandaFrameworkException("Cannot fetch array class for array type " + componentType); }); } else { componentReference = module.forClass(componentType).getOrElseThrow((Supplier<PandaFrameworkException>) () -> { throw new PandaFrameworkException("Cannot fetch array class for " + componentType); }); } ArrayType arrayPrototype = new ArrayType(module, arrayType, componentReference.fetch()); ARRAY_PROTOTYPES.put(baseReference.getName() + dimensions, arrayPrototype); ModuleLoader loader = module.getModuleLoader(); arrayPrototype.getMethods().declare("size", () -> ArrayClassTypeConstants.SIZE.apply(loader)); arrayPrototype.getMethods().declare("toString", () -> ArrayClassTypeConstants.TO_STRING.apply(loader)); module.add(arrayPrototype); return arrayPrototype; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void assumeDocker() throws Exception { assumeDocker(new VersionNumber(DEFAULT_MINIMUM_VERSION)); }
#vulnerable code public static void assumeDocker() throws Exception { Launcher.LocalLauncher localLauncher = new Launcher.LocalLauncher(StreamTaskListener.NULL); try { Assume.assumeThat("Docker working", localLauncher.launch().cmds(DockerTool.getExecutable(null, null, null, null), "ps").start().joinWithTimeout(DockerClient.CLIENT_TIMEOUT, TimeUnit.SECONDS, localLauncher.getListener()), is(0)); } catch (IOException x) { Assume.assumeNoException("have Docker installed", x); } DockerClient dockerClient = new DockerClient(localLauncher, null, null); Assume.assumeFalse("Docker version not < 1.3", dockerClient.version().isOlderThan(new VersionNumber("1.3"))); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void extractConfigurationParameters() { super.extractConfigurationParameters(); // Load configuration parameters. configColor = ChatColor.getByChar(mainConfig.getString("Color", "5")); configIcon = mainConfig.getString("Icon", "\u2618"); configAdditionalEffects = mainConfig.getBoolean("AdditionalEffects", true); configSound = mainConfig.getBoolean("Sound", true); configSoundStats = mainConfig.getString("SoundStats", "ENTITY_FIREWORK_ROCKET_BLAST").toUpperCase(); langNumberAchievements = pluginHeader + LangHelper.get(CmdLang.NUMBER_ACHIEVEMENTS, langConfig) + " " + configColor; }
#vulnerable code @Override public void extractConfigurationParameters() { super.extractConfigurationParameters(); // Load configuration parameters. configColor = ChatColor.getByChar(mainConfig.getString("Color", "5")); configIcon = StringEscapeUtils.unescapeJava(mainConfig.getString("Icon", "\u2618")); configAdditionalEffects = mainConfig.getBoolean("AdditionalEffects", true); configSound = mainConfig.getBoolean("Sound", true); configSoundStats = mainConfig.getString("SoundStats", "ENTITY_FIREWORK_ROCKET_BLAST").toUpperCase(); langNumberAchievements = pluginHeader + LangHelper.get(CmdLang.NUMBER_ACHIEVEMENTS, langConfig) + " " + configColor; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Reader getConfigContent(File file) throws IOException { if (!file.exists()) return null; int commentNum = 0; String addLine; String currentLine; StringBuilder whole = new StringBuilder(""); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); while ((currentLine = reader.readLine()) != null) { // Rework comment line so it becomes a normal value in the config file. // This workaround allows the comment to be saved in the Yaml file. if (currentLine.startsWith("#")) { addLine = currentLine.replace(":", "_COLON_").replace("|", "_VERT_").replace("-", "_HYPHEN_") .replaceFirst("#", plugin.getDescription().getName() + "_COMMENT_" + commentNum + ": "); whole.append(addLine + "\n"); commentNum++; } else { whole.append(currentLine + "\n"); } } String config = whole.toString(); StringReader configStream = new StringReader(config); return configStream; } catch (IOException e) { throw e; } finally { if (reader != null) reader.close(); } }
#vulnerable code public Reader getConfigContent(File file) throws IOException { if (!file.exists()) return null; int commentNum = 0; String addLine; String currentLine; StringBuilder whole = new StringBuilder(""); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); while ((currentLine = reader.readLine()) != null) { // Rework comment line so it becomes a normal value in the config file. // This workaround allows the comment to be saved in the Yaml file. if (currentLine.startsWith("#")) { addLine = currentLine.replace(":", "_COLON_").replace("|", "_VERT_").replace("-", "_HYPHEN_") .replaceFirst("#", plugin.getDescription().getName() + "_COMMENT_" + commentNum + ": "); whole.append(addLine + "\n"); commentNum++; } else { whole.append(currentLine + "\n"); } } String config = whole.toString(); StringReader configStream = new StringReader(config); reader.close(); return configStream; } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent event) { ItemStack item = event.getCurrentItem(); if (event.getInventory().getType() != InventoryType.BREWING || event.getAction() == InventoryAction.NOTHING || event.getClick() == ClickType.NUMBER_KEY && event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD || !isBrewablePotion(item)) { return; } Player player = (Player) event.getWhoClicked(); int eventAmount = item.getAmount(); if (event.isShiftClick()) { eventAmount = Math.min(eventAmount, inventoryHelper.getAvailableSpace(player, item)); if (eventAmount == 0) { return; } } updateStatisticAndAwardAchievementsIfAvailable(player, eventAmount, event.getRawSlot()); }
#vulnerable code @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getType() != InventoryType.BREWING || event.getAction() == InventoryAction.NOTHING || event.getClick() == ClickType.NUMBER_KEY && event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD || !isBrewablePotion(event)) { return; } Player player = (Player) event.getWhoClicked(); int eventAmount = event.getCurrentItem().getAmount(); if (event.isShiftClick()) { eventAmount = Math.min(eventAmount, inventoryHelper.getAvailableSpace(player, event.getCurrentItem())); if (eventAmount == 0) { return; } } updateStatisticAndAwardAchievementsIfAvailable(player, eventAmount, event.getRawSlot()); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void copyResource(InputStream resource, File file) throws IOException { OutputStream out = null; try { out = new FileOutputStream(file); int length; byte[] buf = new byte[1024]; while ((length = resource.read(buf)) > 0) out.write(buf, 0, length); } catch (IOException e) { throw e; } finally { if (out != null) out.close(); resource.close(); } }
#vulnerable code private void copyResource(InputStream resource, File file) throws IOException { OutputStream out = new FileOutputStream(file); int length; byte[] buf = new byte[1024]; while ((length = resource.read(buf)) > 0) out.write(buf, 0, length); out.close(); resource.close(); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void parseDisabledCategories() throws PluginLoadError { extractDisabledCategoriesFromConfig(); // Need PetMaster with a minimum version of 1.4 for PetMasterGive and PetMasterReceive categories. if ((!disabledCategories.contains(NormalAchievements.PETMASTERGIVE) || !disabledCategories.contains(NormalAchievements.PETMASTERRECEIVE)) && (!Bukkit.getPluginManager().isPluginEnabled("PetMaster") || getPetMasterMinorVersion() < 4)) { disabledCategories.add(NormalAchievements.PETMASTERGIVE); disabledCategories.add(NormalAchievements.PETMASTERRECEIVE); logger.warning("Overriding configuration: disabling PetMasterGive and PetMasterReceive categories."); logger.warning( "Ensure you have placed Pet Master with a minimum version of 1.4 in your plugins folder or add PetMasterGive and PetMasterReceive to the DisabledCategories list in config.yml."); } // Elytras introduced in Minecraft 1.9. if (!disabledCategories.contains(NormalAchievements.DISTANCEGLIDING) && serverVersion < 9) { disabledCategories.add(NormalAchievements.DISTANCEGLIDING); logger.warning("Overriding configuration: disabling DistanceGliding category."); logger.warning( "Elytra are not available in your Minecraft version, please add DistanceGliding to the DisabledCategories list in config.yml."); } // Llamas introduced in Minecraft 1.11. if (!disabledCategories.contains(NormalAchievements.DISTANCELLAMA) && serverVersion < 11) { disabledCategories.add(NormalAchievements.DISTANCELLAMA); logger.warning("Overriding configuration: disabling DistanceLlama category."); logger.warning( "Llamas not available in your Minecraft version, please add DistanceLlama to the DisabledCategories list in config.yml."); } // Breeding event introduced in Bukkit 1.10.2. if (!disabledCategories.contains(MultipleAchievements.BREEDING) && serverVersion < 10) { disabledCategories.add(MultipleAchievements.BREEDING); logger.warning("Overriding configuration: disabling Breeding category."); logger.warning( "The breeding event is not available in your server version, please add Breeding to the DisabledCategories list in config.yml."); } // Proper ProjectileHitEvent introduced in Bukkit 1.11. if (!disabledCategories.contains(MultipleAchievements.TARGETSSHOT) && serverVersion < 11) { disabledCategories.add(MultipleAchievements.TARGETSSHOT); logger.warning("Overriding configuration: disabling TargetsShot category."); logger.warning( "The projectile hit event is not fully available in your server version, please add TargetsShot to the DisabledCategories list in config.yml."); } }
#vulnerable code private void parseDisabledCategories() throws PluginLoadError { extractDisabledCategoriesFromConfig(); // Need PetMaster with a minimum version of 1.4 for PetMasterGive and PetMasterReceive categories. if ((!disabledCategories.contains(NormalAchievements.PETMASTERGIVE) || !disabledCategories.contains(NormalAchievements.PETMASTERRECEIVE)) && (!Bukkit.getPluginManager().isPluginEnabled("PetMaster") || Integer.parseInt(Character.toString( Bukkit.getPluginManager().getPlugin("PetMaster").getDescription().getVersion().charAt(2))) < 4)) { disabledCategories.add(NormalAchievements.PETMASTERGIVE); disabledCategories.add(NormalAchievements.PETMASTERRECEIVE); logger.warning("Overriding configuration: disabling PetMasterGive and PetMasterReceive categories."); logger.warning( "Ensure you have placed Pet Master with a minimum version of 1.4 in your plugins folder or add PetMasterGive and PetMasterReceive to the DisabledCategories list in config.yml."); } // Elytras introduced in Minecraft 1.9. if (!disabledCategories.contains(NormalAchievements.DISTANCEGLIDING) && serverVersion < 9) { disabledCategories.add(NormalAchievements.DISTANCEGLIDING); logger.warning("Overriding configuration: disabling DistanceGliding category."); logger.warning( "Elytra are not available in your Minecraft version, please add DistanceGliding to the DisabledCategories list in config.yml."); } // Llamas introduced in Minecraft 1.11. if (!disabledCategories.contains(NormalAchievements.DISTANCELLAMA) && serverVersion < 11) { disabledCategories.add(NormalAchievements.DISTANCELLAMA); logger.warning("Overriding configuration: disabling DistanceLlama category."); logger.warning( "Llamas not available in your Minecraft version, please add DistanceLlama to the DisabledCategories list in config.yml."); } // Breeding event introduced in Bukkit 1.10.2. if (!disabledCategories.contains(MultipleAchievements.BREEDING) && serverVersion < 10) { disabledCategories.add(MultipleAchievements.BREEDING); logger.warning("Overriding configuration: disabling Breeding category."); logger.warning( "The breeding event is not available in your server version, please add Breeding to the DisabledCategories list in config.yml."); } // Proper ProjectileHitEvent introduced in Bukkit 1.11. if (!disabledCategories.contains(MultipleAchievements.TARGETSSHOT) && serverVersion < 11) { disabledCategories.add(MultipleAchievements.TARGETSSHOT); logger.warning("Overriding configuration: disabling TargetsShot category."); logger.warning( "The projectile hit event is not fully available in your server version, please add TargetsShot to the DisabledCategories list in config.yml."); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent event) { Inventory inventory = event.getInventory(); if (!(inventory.getHolder() instanceof AchievementInventoryHolder) || event.getRawSlot() < 0) { return; } // Prevent players from taking items out of the GUI. event.setCancelled(true); // Clicking empty slots should do nothing if (event.getCurrentItem() == null) { return; } int currentPage = ((AchievementInventoryHolder) inventory.getHolder()).getPageIndex(); Player player = (Player) event.getWhoClicked(); if (currentPage == MAIN_GUI_PAGE) { // Main GUI, check whether player can interact with the selected item. if (event.getCurrentItem().getType() != lockedMaterial && event.getRawSlot() < getMainGUIItemCount()) { categoryGUI.displayCategoryGUI(event.getCurrentItem(), player, 0); } return; } ItemStack categoryItem = inventory.getItem(0); // Check whether a navigation button was clicked in a category GUI. if (isButtonClicked(event, guiItems.getBackButton())) { mainGUI.displayMainGUI(player); } else if (isButtonClicked(event, guiItems.getPreviousButton())) { categoryGUI.displayCategoryGUI(categoryItem, player, currentPage - 1); } else if (isButtonClicked(event, guiItems.getNextButton())) { categoryGUI.displayCategoryGUI(categoryItem, player, currentPage + 1); } }
#vulnerable code @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onInventoryClick(InventoryClickEvent event) { Inventory inventory = event.getInventory(); if (!(inventory.getHolder() instanceof AchievementInventoryHolder) || event.getRawSlot() < 0) { return; } // Prevent players from taking items out of the GUI. event.setCancelled(true); int currentPage = ((AchievementInventoryHolder) inventory.getHolder()).getPageIndex(); Player player = (Player) event.getWhoClicked(); if (currentPage == MAIN_GUI_PAGE) { // Main GUI, check whether player can interact with the selected item. if (event.getCurrentItem().getType() != lockedMaterial && event.getRawSlot() < getMainGUIItemCount()) { categoryGUI.displayCategoryGUI(event.getCurrentItem(), player, 0); } return; } ItemStack categoryItem = inventory.getItem(0); // Check whether a navigation button was clicked in a category GUI. if (isButtonClicked(event, guiItems.getBackButton())) { mainGUI.displayMainGUI(player); } else if (isButtonClicked(event, guiItems.getPreviousButton())) { categoryGUI.displayCategoryGUI(categoryItem, player, currentPage - 1); } else if (isButtonClicked(event, guiItems.getNextButton())) { categoryGUI.displayCategoryGUI(categoryItem, player, currentPage + 1); } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private int getCommentsAmount(File file) throws IOException { if (!file.exists()) return 0; int comments = 0; String currentLine; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); while ((currentLine = reader.readLine()) != null) if (currentLine.startsWith("#")) comments++; return comments; } catch (IOException e) { throw e; } finally { if (reader != null) reader.close(); } }
#vulnerable code private int getCommentsAmount(File file) throws IOException { if (!file.exists()) return 0; int comments = 0; String currentLine; BufferedReader reader = new BufferedReader(new FileReader(file)); while ((currentLine = reader.readLine()) != null) if (currentLine.startsWith("#")) comments++; reader.close(); return comments; } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSimpleArrayWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartArray(); gen.writeNumber(13); gen.writeBoolean(true); gen.writeString("foobar"); gen.writeEndArray(); gen.close(); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(13, jp.getIntValue()); assertEquals(JsonToken.VALUE_TRUE, jp.nextToken()); assertEquals(JsonToken.VALUE_STRING, jp.nextToken()); assertEquals("foobar", jp.getText()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(null, jp.nextToken()); jp.close(); }
#vulnerable code public void testSimpleArrayWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); gen.writeStartArray(); gen.writeNumber(13); gen.writeBoolean(true); gen.writeString("foobar"); gen.writeEndArray(); gen.close(); String docStr = sw.toString(); JsonParser jp = createParserUsingReader(docStr); assertEquals(JsonToken.START_ARRAY, jp.nextToken()); assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(13, jp.getIntValue()); assertEquals(JsonToken.VALUE_TRUE, jp.nextToken()); assertEquals(JsonToken.VALUE_STRING, jp.nextToken()); assertEquals("foobar", jp.getText()); assertEquals(JsonToken.END_ARRAY, jp.nextToken()); assertEquals(null, jp.nextToken()); jp.close(); } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Deprecated protected JsonParser _createJsonParser(Reader r, IOContext ctxt) throws IOException, JsonParseException { return _createParser(r, ctxt); }
#vulnerable code @Deprecated protected JsonParser _createJsonParser(Reader r, IOContext ctxt) throws IOException, JsonParseException { return new ReaderBasedJsonParser(ctxt, _parserFeatures, r, _objectCodec, _rootCharSymbols.makeChild(isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES), isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES))); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Deprecated protected JsonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException { return _createUTF8Generator(out, ctxt); }
#vulnerable code @Deprecated protected JsonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException { UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt, _generatorFeatures, _objectCodec, out); if (_characterEscapes != null) { gen.setCharacterEscapes(_characterEscapes); } SerializableString rootSep = _rootValueSeparator; if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { gen.setRootValueSeparator(rootSep); } return gen; } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testWriteLongCustomEscapes() throws Exception { JsonFactory jf = new JsonFactory(); jf.setCharacterEscapes(ESC_627); // must set to trigger bug StringBuilder longString = new StringBuilder(); while (longString.length() < 2000) { longString.append("\u65e5\u672c\u8a9e"); } StringWriter writer = new StringWriter(); // must call #createGenerator(Writer), #createGenerator(OutputStream) doesn't trigger bug JsonGenerator jgen = jf.createGenerator(writer); jgen.setHighestNonEscapedChar(127); // must set to trigger bug jgen.writeString(longString.toString()); }
#vulnerable code public void testWriteLongCustomEscapes() throws Exception { JsonFactory jf = new JsonFactory(); jf.setCharacterEscapes(ESC_627); // must set to trigger bug StringBuilder longString = new StringBuilder(); while (longString.length() < 2000) { longString.append("\u65e5\u672c\u8a9e"); } StringWriter writer = new StringWriter(); // must call #createJsonGenerator(Writer), #createJsonGenerator(OutputStream) doesn't trigger bug JsonGenerator jgen = jf.createJsonGenerator(writer); jgen.setHighestNonEscapedChar(127); // must set to trigger bug jgen.writeString(longString.toString()); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testAutoFlushOrNot() throws Exception { JsonFactory f = new JsonFactory(); assertTrue(f.isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)); MyChars sw = new MyChars(); JsonGenerator jg = f.createGenerator(sw); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, sw.flushed); jg.flush(); assertEquals(1, sw.flushed); jg.close(); // ditto with stream MyBytes bytes = new MyBytes(); jg = f.createGenerator(bytes, JsonEncoding.UTF8); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, bytes.flushed); jg.flush(); assertEquals(1, bytes.flushed); assertEquals(2, bytes.toByteArray().length); jg.close(); // then disable and we should not see flushing again... f.disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM); // first with a Writer sw = new MyChars(); jg = f.createGenerator(sw); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, sw.flushed); jg.flush(); assertEquals(0, sw.flushed); jg.close(); assertEquals("[]", sw.toString()); // and then with OutputStream bytes = new MyBytes(); jg = f.createGenerator(bytes, JsonEncoding.UTF8); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, bytes.flushed); jg.flush(); assertEquals(0, bytes.flushed); jg.close(); assertEquals(2, bytes.toByteArray().length); }
#vulnerable code public void testAutoFlushOrNot() throws Exception { JsonFactory f = new JsonFactory(); assertTrue(f.isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)); MyChars sw = new MyChars(); JsonGenerator jg = f.createJsonGenerator(sw); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, sw.flushed); jg.flush(); assertEquals(1, sw.flushed); jg.close(); // ditto with stream MyBytes bytes = new MyBytes(); jg = f.createJsonGenerator(bytes, JsonEncoding.UTF8); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, bytes.flushed); jg.flush(); assertEquals(1, bytes.flushed); assertEquals(2, bytes.toByteArray().length); jg.close(); // then disable and we should not see flushing again... f.disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM); // first with a Writer sw = new MyChars(); jg = f.createJsonGenerator(sw); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, sw.flushed); jg.flush(); assertEquals(0, sw.flushed); jg.close(); assertEquals("[]", sw.toString()); // and then with OutputStream bytes = new MyBytes(); jg = f.createJsonGenerator(bytes, JsonEncoding.UTF8); jg.writeStartArray(); jg.writeEndArray(); assertEquals(0, bytes.flushed); jg.flush(); assertEquals(0, bytes.flushed); jg.close(); assertEquals(2, bytes.toByteArray().length); } #location 48 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testFieldValueWrites() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartObject(); gen.writeNumberField("long", 3L); gen.writeNumberField("double", 0.25); gen.writeNumberField("float", -0.25f); gen.writeEndObject(); gen.close(); assertEquals("{\"long\":3,\"double\":0.25,\"float\":-0.25}", sw.toString().trim()); }
#vulnerable code public void testFieldValueWrites() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); gen.writeStartObject(); gen.writeNumberField("long", 3L); gen.writeNumberField("double", 0.25); gen.writeNumberField("float", -0.25f); gen.writeEndObject(); gen.close(); assertEquals("{\"long\":3,\"double\":0.25,\"float\":-0.25}", sw.toString().trim()); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String _writeNumbers(JsonFactory jf) throws IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createGenerator(sw); jg.writeStartArray(); jg.writeNumber(1); jg.writeNumber(2L); jg.writeNumber(1.25); jg.writeNumber(2.25f); jg.writeNumber(BigInteger.valueOf(3001)); jg.writeNumber(BigDecimal.valueOf(0.5)); jg.writeNumber("-1"); jg.writeEndArray(); jg.close(); return sw.toString(); }
#vulnerable code private String _writeNumbers(JsonFactory jf) throws IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createJsonGenerator(sw); jg.writeStartArray(); jg.writeNumber(1); jg.writeNumber(2L); jg.writeNumber(1.25); jg.writeNumber(2.25f); jg.writeNumber(BigInteger.valueOf(3001)); jg.writeNumber(BigDecimal.valueOf(0.5)); jg.writeNumber("-1"); jg.writeEndArray(); jg.close(); return sw.toString(); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testInvalidObjectWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createGenerator(sw); gen.writeStartObject(); // Mismatch: try { gen.writeEndArray(); fail("Expected an exception for mismatched array/object write"); } catch (JsonGenerationException e) { verifyException(e, "Current context not an array"); } }
#vulnerable code public void testInvalidObjectWrite() throws Exception { StringWriter sw = new StringWriter(); JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); gen.writeStartObject(); // Mismatch: try { gen.writeEndArray(); fail("Expected an exception for mismatched array/object write"); } catch (JsonGenerationException e) { verifyException(e, "Current context not an array"); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCopyRootTokens() throws IOException { JsonFactory jf = new JsonFactory(); final String DOC = "\"text\\non two lines\" true false 2.0"; JsonParser jp = jf.createParser(new StringReader(DOC)); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); JsonToken t; while ((t = jp.nextToken()) != null) { gen.copyCurrentEvent(jp); // should not change parser state: assertToken(t, jp.getCurrentToken()); } jp.close(); gen.close(); assertEquals("\"text\\non two lines\" true false 2.0", sw.toString()); }
#vulnerable code public void testCopyRootTokens() throws IOException { JsonFactory jf = new JsonFactory(); final String DOC = "\"text\\non two lines\" true false 2.0"; JsonParser jp = jf.createJsonParser(new StringReader(DOC)); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createJsonGenerator(sw); JsonToken t; while ((t = jp.nextToken()) != null) { gen.copyCurrentEvent(jp); // should not change parser state: assertToken(t, jp.getCurrentToken()); } jp.close(); gen.close(); assertEquals("\"text\\non two lines\" true false 2.0", sw.toString()); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void _testNonNumericQuoting(JsonFactory jf, boolean quoted) throws IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createGenerator(sw); jg.writeStartObject(); jg.writeFieldName("double"); jg.writeNumber(Double.NaN); jg.writeEndObject(); jg.writeStartObject(); jg.writeFieldName("float"); jg.writeNumber(Float.NaN); jg.writeEndObject(); jg.close(); String result = sw.toString(); if (quoted) { assertEquals("{\"double\":\"NaN\"} {\"float\":\"NaN\"}", result); } else { assertEquals("{\"double\":NaN} {\"float\":NaN}", result); } }
#vulnerable code private void _testNonNumericQuoting(JsonFactory jf, boolean quoted) throws IOException { StringWriter sw = new StringWriter(); JsonGenerator jg = jf.createJsonGenerator(sw); jg.writeStartObject(); jg.writeFieldName("double"); jg.writeNumber(Double.NaN); jg.writeEndObject(); jg.writeStartObject(); jg.writeFieldName("float"); jg.writeNumber(Float.NaN); jg.writeEndObject(); jg.close(); String result = sw.toString(); if (quoted) { assertEquals("{\"double\":\"NaN\"} {\"float\":\"NaN\"}", result); } else { assertEquals("{\"double\":NaN} {\"float\":NaN}", result); } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testIsClosed() throws IOException { JsonFactory jf = new JsonFactory(); for (int i = 0; i < 2; ++i) { boolean stream = ((i & 1) == 0); JsonGenerator jg = stream ? jf.createGenerator(new StringWriter()) : jf.createGenerator(new ByteArrayOutputStream(), JsonEncoding.UTF8) ; assertFalse(jg.isClosed()); jg.writeStartArray(); jg.writeNumber(-1); jg.writeEndArray(); assertFalse(jg.isClosed()); jg.close(); assertTrue(jg.isClosed()); jg.close(); assertTrue(jg.isClosed()); } }
#vulnerable code public void testIsClosed() throws IOException { JsonFactory jf = new JsonFactory(); for (int i = 0; i < 2; ++i) { boolean stream = ((i & 1) == 0); JsonGenerator jg = stream ? jf.createJsonGenerator(new StringWriter()) : jf.createJsonGenerator(new ByteArrayOutputStream(), JsonEncoding.UTF8) ; assertFalse(jg.isClosed()); jg.writeStartArray(); jg.writeNumber(-1); jg.writeEndArray(); assertFalse(jg.isClosed()); jg.close(); assertTrue(jg.isClosed()); jg.close(); assertTrue(jg.isClosed()); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void _testStreaming(boolean useBytes) throws IOException { final int[] SIZES = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 12, 100, 350, 1900, 6000, 19000, 65000, 139000 }; JsonFactory jsonFactory = new JsonFactory(); final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); StringWriter chars = null; for (int size : SIZES) { byte[] data = _generateData(size); JsonGenerator g; if (useBytes) { bytes.reset(); g = jsonFactory.createGenerator(bytes, JsonEncoding.UTF8); } else { chars = new StringWriter(); g = jsonFactory.createGenerator(chars); } g.writeStartObject(); g.writeFieldName("b"); g.writeBinary(data); g.writeEndObject(); g.close(); // and verify JsonParser p; if (useBytes) { p = jsonFactory.createParser(bytes.toByteArray()); } else { p = jsonFactory.createParser(chars.toString()); } assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("b", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); ByteArrayOutputStream result = new ByteArrayOutputStream(size); int gotten = p.readBinaryValue(result); assertEquals(size, gotten); assertArrayEquals(data, result.toByteArray()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } }
#vulnerable code private void _testStreaming(boolean useBytes) throws IOException { final int[] SIZES = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 12, 100, 350, 1900, 6000, 19000, 65000, 139000 }; JsonFactory jsonFactory = new JsonFactory(); final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); StringWriter chars = null; for (int size : SIZES) { byte[] data = _generateData(size); JsonGenerator g; if (useBytes) { bytes.reset(); g = jsonFactory.createJsonGenerator(bytes, JsonEncoding.UTF8); } else { chars = new StringWriter(); g = jsonFactory.createJsonGenerator(chars); } g.writeStartObject(); g.writeFieldName("b"); g.writeBinary(data); g.writeEndObject(); g.close(); // and verify JsonParser p; if (useBytes) { p = jsonFactory.createJsonParser(bytes.toByteArray()); } else { p = jsonFactory.createJsonParser(chars.toString()); } assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("b", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); ByteArrayOutputStream result = new ByteArrayOutputStream(size); int gotten = p.readBinaryValue(result); assertEquals(size, gotten); assertArrayEquals(data, result.toByteArray()); assertToken(JsonToken.END_OBJECT, p.nextToken()); assertNull(p.nextToken()); p.close(); } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testLongerObjects() throws Exception { JsonFactory jf = new JsonFactory(); for (int i = 0; i < 2; ++i) { boolean useChars = (i == 0); JsonGenerator jgen; ByteArrayOutputStream bout = new ByteArrayOutputStream(200); if (useChars) { jgen = jf.createGenerator(new OutputStreamWriter(bout, "UTF-8")); } else { jgen = jf.createGenerator(bout, JsonEncoding.UTF8); } jgen.writeStartObject(); for (int rounds = 0; rounds < 1500; ++rounds) { for (int letter = 'a'; letter <= 'z'; ++letter) { for (int index = 0; index < 20; ++index) { String name; if (letter > 'f') { name = "X"+letter+index; } else if (letter > 'p') { name = ""+letter+index; } else { name = "__"+index+letter; } jgen.writeFieldName(name); jgen.writeNumber(index-1); } jgen.writeRaw('\n'); } } jgen.writeEndObject(); jgen.close(); byte[] json = bout.toByteArray(); JsonParser jp = jf.createParser(json); assertToken(JsonToken.START_OBJECT, jp.nextToken()); for (int rounds = 0; rounds < 1500; ++rounds) { for (int letter = 'a'; letter <= 'z'; ++letter) { for (int index = 0; index < 20; ++index) { assertToken(JsonToken.FIELD_NAME, jp.nextToken()); String name; if (letter > 'f') { name = "X"+letter+index; } else if (letter > 'p') { name = ""+letter+index; } else { name = "__"+index+letter; } assertEquals(name, jp.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(index-1, jp.getIntValue()); } } } assertToken(JsonToken.END_OBJECT, jp.nextToken()); } }
#vulnerable code public void testLongerObjects() throws Exception { JsonFactory jf = new JsonFactory(); for (int i = 0; i < 2; ++i) { boolean useChars = (i == 0); JsonGenerator jgen; ByteArrayOutputStream bout = new ByteArrayOutputStream(200); if (useChars) { jgen = jf.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8")); } else { jgen = jf.createJsonGenerator(bout, JsonEncoding.UTF8); } jgen.writeStartObject(); for (int rounds = 0; rounds < 1500; ++rounds) { for (int letter = 'a'; letter <= 'z'; ++letter) { for (int index = 0; index < 20; ++index) { String name; if (letter > 'f') { name = "X"+letter+index; } else if (letter > 'p') { name = ""+letter+index; } else { name = "__"+index+letter; } jgen.writeFieldName(name); jgen.writeNumber(index-1); } jgen.writeRaw('\n'); } } jgen.writeEndObject(); jgen.close(); byte[] json = bout.toByteArray(); JsonParser jp = jf.createJsonParser(json); assertToken(JsonToken.START_OBJECT, jp.nextToken()); for (int rounds = 0; rounds < 1500; ++rounds) { for (int letter = 'a'; letter <= 'z'; ++letter) { for (int index = 0; index < 20; ++index) { assertToken(JsonToken.FIELD_NAME, jp.nextToken()); String name; if (letter > 'f') { name = "X"+letter+index; } else if (letter > 'p') { name = ""+letter+index; } else { name = "__"+index+letter; } assertEquals(name, jp.getCurrentName()); assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken()); assertEquals(index-1, jp.getIntValue()); } } } assertToken(JsonToken.END_OBJECT, jp.nextToken()); } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void _testEscapeCustom(boolean useStream) throws Exception { JsonFactory f = new JsonFactory().setCharacterEscapes(new MyEscapes()); final String STR_IN = "[abcd/"+((char) TWO_BYTE_ESCAPED)+"/"+((char) THREE_BYTE_ESCAPED)+"]"; final String STR_OUT = "[\\A\\u0062c[D]/"+TWO_BYTE_ESCAPED_STRING+"/"+THREE_BYTE_ESCAPED_STRING+"]"; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); JsonGenerator jgen; // First: output normally; should not add escaping if (useStream) { jgen = f.createGenerator(bytes, JsonEncoding.UTF8); } else { jgen = f.createGenerator(new OutputStreamWriter(bytes, "UTF-8")); } jgen.writeStartObject(); jgen.writeStringField(STR_IN, STR_IN); jgen.writeEndObject(); jgen.close(); String json = bytes.toString("UTF-8"); assertEquals("{"+quote(STR_OUT)+":"+quote(STR_OUT)+"}", json); }
#vulnerable code private void _testEscapeCustom(boolean useStream) throws Exception { JsonFactory f = new JsonFactory().setCharacterEscapes(new MyEscapes()); final String STR_IN = "[abcd/"+((char) TWO_BYTE_ESCAPED)+"/"+((char) THREE_BYTE_ESCAPED)+"]"; final String STR_OUT = "[\\A\\u0062c[D]/"+TWO_BYTE_ESCAPED_STRING+"/"+THREE_BYTE_ESCAPED_STRING+"]"; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); JsonGenerator jgen; // First: output normally; should not add escaping if (useStream) { jgen = f.createJsonGenerator(bytes, JsonEncoding.UTF8); } else { jgen = f.createJsonGenerator(new OutputStreamWriter(bytes, "UTF-8")); } jgen.writeStartObject(); jgen.writeStringField(STR_IN, STR_IN); jgen.writeEndObject(); jgen.close(); String json = bytes.toString("UTF-8"); assertEquals("{"+quote(STR_OUT)+":"+quote(STR_OUT)+"}", json); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void _testSurrogates(JsonFactory f, boolean checkText) throws IOException { byte[] json = "{\"text\":\"\uD83D\uDE03\"}".getBytes("UTF-8"); // first JsonParser jp = f.createParser(json); assertToken(JsonToken.START_OBJECT, jp.nextToken()); assertToken(JsonToken.FIELD_NAME, jp.nextToken()); if (checkText) { assertEquals("text", jp.getText()); } assertToken(JsonToken.VALUE_STRING, jp.nextToken()); if (checkText) { assertEquals("\uD83D\uDE03", jp.getText()); } assertToken(JsonToken.END_OBJECT, jp.nextToken()); }
#vulnerable code private void _testSurrogates(JsonFactory f, boolean checkText) throws IOException { byte[] json = "{\"text\":\"\uD83D\uDE03\"}".getBytes("UTF-8"); // first JsonParser jp = f.createJsonParser(json); assertToken(JsonToken.START_OBJECT, jp.nextToken()); assertToken(JsonToken.FIELD_NAME, jp.nextToken()); if (checkText) { assertEquals("text", jp.getText()); } assertToken(JsonToken.VALUE_STRING, jp.nextToken()); if (checkText) { assertEquals("\uD83D\uDE03", jp.getText()); } assertToken(JsonToken.END_OBJECT, jp.nextToken()); } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Version versionFor(Class<?> cls) { final InputStream in = cls.getResourceAsStream(VERSION_FILE); if (in == null) return Version.unknownVersion(); try { InputStreamReader reader = new InputStreamReader(in, "UTF-8"); try { return doReadVersion(reader); } finally { try { reader.close(); } catch (IOException ignored) { } } } catch (UnsupportedEncodingException e) { return Version.unknownVersion(); } finally { try { in.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
#vulnerable code public static Version versionFor(Class<?> cls) { InputStream in; Version version = null; try { in = cls.getResourceAsStream(VERSION_FILE); if (in != null) { try { BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String groupStr = null, artifactStr = null; String versionStr = br.readLine(); if (versionStr != null) { groupStr = br.readLine(); if (groupStr != null) { groupStr = groupStr.trim(); artifactStr = br.readLine(); if (artifactStr != null) { artifactStr = artifactStr.trim(); } } } version = parseVersion(versionStr, groupStr, artifactStr); } finally { try { in.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } catch (IOException e) { } return (version == null) ? Version.unknownVersion() : version; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void updateGC() { if (perfDataSupport) { ygcCount.update((Long) ygcCountCounter.getValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); fullgcCount.update((Long) fullGcCountCounter.getValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } else if (isJmxStateOk()) { try { ygcCount.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionCount()); ygcTimeMills.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionTime()); fullgcCount.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionCount()); fullgcTimeMills.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionTime()); } catch (Exception e) { handleJmxFetchDataError(e); } } }
#vulnerable code private void updateGC() { if (perfDataSupport) { ygcCount.update((Long) ygcCountCounter.getValue()); ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter)); fullgcCount.update((Long) fullGcCountCounter.getValue()); fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter)); } else if (isJmxStateOk()) { try { ygcCount.update(jmxClient.getYoungCollector().getCollectionCount()); ygcTimeMills.update(jmxClient.getYoungCollector().getCollectionTime()); fullgcCount.update(jmxClient.getFullCollector().getCollectionCount()); fullgcTimeMills.update(jmxClient.getFullCollector().getCollectionTime()); } catch (Exception e) { handleJmxFetchDataError(e); } } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { logger.info("ProactiveGcTask starting, oldGenOccupancyFraction:" + oldGenOccupancyFraction); try { long usedOldBytes = logOldGenStatus(); if (needTriggerGc(maxOldBytes, usedOldBytes, oldGenOccupancyFraction)) { preGc(); doGc(); postGc(); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { scheduler.reschedule(this); } }
#vulnerable code public void run() { log.info("ProactiveGcTask starting, oldGenOccupancyFraction:" + oldGenOccupancyFraction + ", datetime: " + new Date()); try { oldMemoryPool = getOldMemoryPool(); long maxOldBytes = getMemoryPoolMaxOrCommitted(oldMemoryPool); long oldUsedBytes = oldMemoryPool.getUsage().getUsed(); log.info(String.format("max old gen: %.2f MB, used old gen: %.2f MB, available old gen: %.2f MB.", SizeUnit.BYTES.toMegaBytes(maxOldBytes), SizeUnit.BYTES.toMegaBytes(oldUsedBytes), SizeUnit.BYTES.toMegaBytes(maxOldBytes - oldUsedBytes))); if (needTriggerGc(maxOldBytes, oldUsedBytes, oldGenOccupancyFraction)) { preGc(); doGc(); postGc(); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (!scheduler.isShutdown()) { // reschedule this task try { scheduler.reschedule(this); } catch (Exception e) { log.error(e.getMessage(), e); } } } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void updateMemoryPool() throws IOException { JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager(); edenUsedBytes = memoryPoolManager.getEdenMemoryPool().getUsage().getUsed(); edenMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getEdenMemoryPool()); MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool(); if (survivorMemoryPool != null) { surUsedBytes = survivorMemoryPool.getUsage().getUsed(); surMaxBytes = getMemoryPoolMaxOrCommited(survivorMemoryPool); } oldUsedBytes = memoryPoolManager.getOldMemoryPool().getUsage().getUsed(); oldMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getOldMemoryPool()); permUsedBytes = memoryPoolManager.getPermMemoryPool().getUsage().getUsed(); permMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getPermMemoryPool()); if (jvmMajorVersion >= 8) { MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool(); if (compressedClassSpaceMemoryPool != null) { ccsUsedBytes = compressedClassSpaceMemoryPool.getUsage().getUsed(); ccsMaxBytes = getMemoryPoolMaxOrCommited(compressedClassSpaceMemoryPool); } } codeCacheUsedBytes = memoryPoolManager.getCodeCacheMemoryPool().getUsage().getUsed(); codeCacheMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getCodeCacheMemoryPool()); directUsedBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed(); directMaxBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity(); mapUsedBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed(); mapMaxBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity(); }
#vulnerable code private void updateMemoryPool() throws IOException { MemoryPoolMXBean survivorMemoryPool = jmxClient.getMemoryPoolManager().getSurvivorMemoryPool(); if (survivorMemoryPool != null) { surUsedBytes = survivorMemoryPool.getUsage().getUsed(); surMaxBytes = getMemoryPoolMaxOrCommited(survivorMemoryPool); } edenUsedBytes = jmxClient.getMemoryPoolManager().getEdenMemoryPool().getUsage().getUsed(); edenMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getEdenMemoryPool()); oldUsedBytes = jmxClient.getMemoryPoolManager().getOldMemoryPool().getUsage().getUsed(); oldMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getOldMemoryPool()); permUsedBytes = jmxClient.getMemoryPoolManager().getPermMemoryPool().getUsage().getUsed(); permMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getPermMemoryPool()); if (jvmMajorVersion >= 8) { ccsUsedBytes = jmxClient.getMemoryPoolManager().getCompressedClassSpaceMemoryPool().getUsage().getUsed(); ccsMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager() .getCompressedClassSpaceMemoryPool()); } codeCacheUsedBytes = jmxClient.getMemoryPoolManager().getCodeCacheMemoryPool().getUsage().getUsed(); codeCacheMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getCodeCacheMemoryPool()); directUsedBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed(); directMaxBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity(); mapUsedBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed(); mapMaxBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity(); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void printHelp() throws Exception { tty.println(" t [tid]: print stack trace for the thread you choose"); tty.println(" a : list all thread's id and name"); tty.println(" m : change threads display mode and ordering"); tty.println(" i [num]: change flush interval seconds"); tty.println(" l [num]: change number of display threads"); tty.println(" f [name]: set thread name filter"); tty.println(" q : quit"); tty.println(" h : print help"); app.preventFlush(); waitForEnter(); app.continueFlush(); }
#vulnerable code private void printHelp() throws Exception { tty.println(" t [tid]: print stack trace for the thread you choose"); tty.println(" a : list all thread's id and name"); tty.println(" m : change threads display mode and ordering"); tty.println(" i : change flush interval seconds"); tty.println(" l : change number of display threads"); tty.println(" q : quit"); tty.println(" h : print help"); app.preventFlush(); String command = waitForEnter(); app.continueFlush(); if (command.length() > 0) { handleCommand(command); } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void init() throws IOException { Map<String, Counter> perfCounters = null; try { perfData = PerfData.connect(Integer.parseInt(pid)); perfCounters = perfData.getAllCounters(); initPerfCounters(perfCounters); perfDataSupport = true; } catch (Throwable ignored) { } if (perfDataSupport) { vmArgs = (String) perfCounters.get("java.rt.vmArgs").getValue(); } else { vmArgs = Formats.join(jmxClient.getRuntimeMXBean().getInputArguments(), " "); } startTime = jmxClient.getRuntimeMXBean().getStartTime(); Map<String, String> taregetVMSystemProperties = jmxClient.getRuntimeMXBean().getSystemProperties(); osUser = taregetVMSystemProperties.get("user.name"); jvmVersion = taregetVMSystemProperties.get("java.version"); jvmMajorVersion = getJavaMajorVersion(jvmVersion); permGenName = jvmMajorVersion >= 8 ? "metaspace" : "perm"; threadStackSize = 1024 * Long.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("ThreadStackSize").getValue()); maxDirectMemorySize = Long .parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("MaxDirectMemorySize").getValue()); maxDirectMemorySize = maxDirectMemorySize == 0 ? -1 : maxDirectMemorySize; threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported(); threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported(); processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors(); warningRule.updateProcessor(processors); isLinux = System.getProperty("os.name").toLowerCase(Locale.US).contains("linux"); }
#vulnerable code private void init() throws IOException { Map<String, Counter> perfCounters = null; try { perfData = PerfData.connect(Integer.parseInt(pid)); perfCounters = perfData.getCounters(); initPerfCounters(perfCounters); perfDataSupport = true; } catch (Throwable ignored) { } if (perfDataSupport) { vmArgs = (String) perfCounters.get("java.rt.vmArgs").getValue(); } else { vmArgs = Formats.join(jmxClient.getRuntimeMXBean().getInputArguments(), " "); } startTime = jmxClient.getRuntimeMXBean().getStartTime(); Map<String, String> taregetVMSystemProperties = jmxClient.getRuntimeMXBean().getSystemProperties(); osUser = taregetVMSystemProperties.get("user.name"); jvmVersion = taregetVMSystemProperties.get("java.version"); jvmMajorVersion = getJavaMajorVersion(jvmVersion); permGenName = jvmMajorVersion >= 8 ? "metaspace" : "perm"; threadStackSize = 1024 * Long.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("ThreadStackSize").getValue()); maxDirectMemorySize = Long .parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("MaxDirectMemorySize").getValue()); maxDirectMemorySize = maxDirectMemorySize == 0 ? -1 : maxDirectMemorySize; threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported(); threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported(); processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors(); warningRule.updateProcessor(processors); isLinux = System.getProperty("os.name").toLowerCase(Locale.US).contains("linux"); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { try { // 1. create option parser OptionParser parser = createOptionParser(); OptionSet optionSet = parser.parse(args); if (optionSet.has("help")) { printHelper(parser); System.exit(0); } // 2. create vminfo String pid = parsePid(parser, optionSet); VMInfo vminfo = VMInfo.processNewVM(pid); if (vminfo.state != VMInfoState.ATTACHED) { System.out.println("\nERROR: Could not attach to process, please find reason in README\n"); return; } // 3. create view VMDetailView.DetailMode displayMode = parseDisplayMode(optionSet); Integer width = null; if (optionSet.hasArgument("width")) { width = (Integer) optionSet.valueOf("width"); } VMDetailView view = new VMDetailView(vminfo, displayMode, width); if (optionSet.hasArgument("limit")) { Integer limit = (Integer) optionSet.valueOf("limit"); view.threadLimit = limit; } // 4. create main application VJTop app = new VJTop(); app.mainThread = Thread.currentThread(); app.view = view; Integer interval = DEFAULT_INTERVAL; if (optionSet.hasArgument("interval")) { interval = (Integer) (optionSet.valueOf("interval")); if (interval < 1) { throw new IllegalArgumentException("Interval cannot be set below 1.0"); } } app.interval = interval; if (optionSet.hasArgument("n")) { Integer iterations = (Integer) optionSet.valueOf("n"); app.maxIterations = iterations; } // 5. start thread to get user input if (app.maxIterations == -1) { InteractiveTask task = new InteractiveTask(app); if (task.inputEnabled()) { view.displayCommandHints = true; Thread interactiveThread = new Thread(task, "InteractiveThread"); interactiveThread.setDaemon(true); interactiveThread.start(); } } // 6. run app app.run(view); } catch (Exception e) { e.printStackTrace(System.out); System.out.flush(); } }
#vulnerable code public static void main(String[] args) { try { // 1. create option parser OptionParser parser = createOptionParser(); OptionSet optionSet = parser.parse(args); if (optionSet.has("help")) { printHelper(parser); System.exit(0); } // 2. create vminfo String pid = parsePid(parser, optionSet); VMInfo vminfo = VMInfo.processNewVM(pid); if (vminfo.state != VMInfoState.ATTACHED) { System.out.println("\nERROR: Could not attach to process, please find reason in README\n"); return; } // 3. create view VMDetailView.DetailMode displayMode = parseDisplayMode(optionSet); Integer width = null; if (optionSet.hasArgument("width")) { width = (Integer) optionSet.valueOf("width"); } VMDetailView view = new VMDetailView(vminfo, displayMode, width); if (optionSet.hasArgument("limit")) { Integer limit = (Integer) optionSet.valueOf("limit"); view.threadLimit = limit; } // 4. create main application VJTop app = new VJTop(); app.mainThread = Thread.currentThread(); app.view = view; Integer interval = DEFAULT_INTERVAL; if (optionSet.hasArgument("interval")) { interval = (Integer) (optionSet.valueOf("interval")); if (interval < 1) { throw new IllegalArgumentException("Interval cannot be set below 1.0"); } } app.interval = interval; if (optionSet.hasArgument("n")) { Integer iterations = (Integer) optionSet.valueOf("n"); app.maxIterations = iterations; } // 5. start thread to get user input Thread interactiveThread = new Thread(new InteractiveTask(app), "InteractiveThread"); interactiveThread.setDaemon(true); interactiveThread.start(); // 6. run app app.run(view); } catch (Exception e) { e.printStackTrace(System.out); System.out.flush(); } } #location 56 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void updateMemoryPool() throws IOException { JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager(); eden = new Usage(memoryPoolManager.getEdenMemoryPool().getUsage()); old = new Usage(memoryPoolManager.getOldMemoryPool().getUsage()); warning.updateOld(old.max); MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool(); if (survivorMemoryPool != null) { sur = new Usage(survivorMemoryPool.getUsage()); } else { sur = new Usage(); } perm = new Usage(memoryPoolManager.getPermMemoryPool().getUsage()); warning.updatePerm(perm.max); if (jvmMajorVersion >= 8) { MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool(); if (compressedClassSpaceMemoryPool != null) { ccs = new Usage(compressedClassSpaceMemoryPool.getUsage()); } } codeCache = new Usage(memoryPoolManager.getCodeCacheMemoryPool().getUsage()); direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed(), jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity(), maxDirectMemorySize); // 取巧用法,将count 放入无用的max中。 map = new Usage(jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed(), jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity(), jmxClient.getBufferPoolManager().getMappedBufferPool().getCount()); }
#vulnerable code private void updateMemoryPool() throws IOException { JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager(); eden = new Usage(memoryPoolManager.getEdenMemoryPool().getUsage()); old = new Usage(memoryPoolManager.getOldMemoryPool().getUsage()); warning.updateOld(old.max); MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool(); if (survivorMemoryPool != null) { sur = new Usage(survivorMemoryPool.getUsage()); } else { sur = new Usage(); } perm = new Usage(memoryPoolManager.getPermMemoryPool().getUsage()); warning.updatePerm(perm.max); if (jvmMajorVersion >= 8) { MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool(); if (compressedClassSpaceMemoryPool != null) { ccs = new Usage(compressedClassSpaceMemoryPool.getUsage()); } } codeCache = new Usage(memoryPoolManager.getCodeCacheMemoryPool().getUsage()); direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPool()); map = new Usage(jmxClient.getBufferPoolManager().getMappedBufferPool()); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { // background执行时,console为Null if (console == null) { return; } while (true) { try { String command = readLine(""); if (command == null) { break; } handleCommand(command); if (!app.view.shouldExit()) { tty.print(" Input command (h for help):"); } } catch (Exception e) { e.printStackTrace(tty); } } }
#vulnerable code @Override public void run() { while (true) { try { String command = readLine(); handleCommand(command); if (!app.view.shouldExit()) { tty.print(" Input command (h for help):"); } } catch (Exception e) { e.printStackTrace(tty); } } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void updateMemoryPool() { if (!isJmxStateOk()) { return; } try { JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager(); MemoryPoolMXBean edenMXBean = memoryPoolManager.getEdenMemoryPool(); if (edenMXBean != null) { eden = new Usage(edenMXBean.getUsage()); } else { eden = new Usage(); } MemoryPoolMXBean oldMXBean = memoryPoolManager.getOldMemoryPool(); if (oldMXBean != null) { old = new Usage(oldMXBean.getUsage()); warningRule.updateOld(old.max); } else { old = new Usage(); } MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool(); if (survivorMemoryPool != null) { sur = new Usage(survivorMemoryPool.getUsage()); } else { sur = new Usage(); } MemoryPoolMXBean permMXBean = memoryPoolManager.getPermMemoryPool(); if (permMXBean != null) { perm = new Usage(permMXBean.getUsage()); warningRule.updatePerm(perm.max); } else { perm = new Usage(); } if (jvmMajorVersion >= 8) { MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool(); if (compressedClassSpaceMemoryPool != null) { ccs = new Usage(compressedClassSpaceMemoryPool.getUsage()); } else { ccs = new Usage(); } } MemoryPoolMXBean memoryPoolMXBean = memoryPoolManager.getCodeCacheMemoryPool(); if (memoryPoolMXBean != null) { codeCache = new Usage(memoryPoolMXBean.getUsage()); } else { codeCache = new Usage(); } direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPoolUsed(), jmxClient.getBufferPoolManager().getDirectBufferPoolCapacity(), maxDirectMemorySize); // 取巧用法,将count 放入无用的max中。 long mapUsed = jmxClient.getBufferPoolManager().getMappedBufferPoolUsed(); map = new Usage(mapUsed, jmxClient.getBufferPoolManager().getMappedBufferPoolCapacity(), mapUsed == 0 ? 0 : jmxClient.getBufferPoolManager().getMappedBufferPoolCount()); } catch (Exception e) { handleJmxFetchDataError(e); } }
#vulnerable code private void updateMemoryPool() { if (!isJmxStateOk()) { return; } try { JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager(); eden = new Usage(memoryPoolManager.getEdenMemoryPool().getUsage()); old = new Usage(memoryPoolManager.getOldMemoryPool().getUsage()); warningRule.updateOld(old.max); MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool(); if (survivorMemoryPool != null) { sur = new Usage(survivorMemoryPool.getUsage()); } else { sur = new Usage(); } perm = new Usage(memoryPoolManager.getPermMemoryPool().getUsage()); warningRule.updatePerm(perm.max); if (jvmMajorVersion >= 8) { MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool(); if (compressedClassSpaceMemoryPool != null) { ccs = new Usage(compressedClassSpaceMemoryPool.getUsage()); } else { ccs = new Usage(); } } codeCache = new Usage(memoryPoolManager.getCodeCacheMemoryPool().getUsage()); direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPoolUsed(), jmxClient.getBufferPoolManager().getDirectBufferPoolCapacity(), maxDirectMemorySize); // 取巧用法,将count 放入无用的max中。 long mapUsed = jmxClient.getBufferPoolManager().getMappedBufferPoolUsed(); map = new Usage(mapUsed, jmxClient.getBufferPoolManager().getMappedBufferPoolCapacity(), mapUsed == 0 ? 0 : jmxClient.getBufferPoolManager().getMappedBufferPoolCount()); } catch (Exception e) { handleJmxFetchDataError(e); } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void clearTerminal() { if (Utils.isWindows) { System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n"); } else { System.out.print(CLEAR_TERMINAL_ANSI_CMD); } }
#vulnerable code private static void clearTerminal() { if (System.getProperty("os.name").contains("Windows")) { // hack System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n"); } else if (System.getProperty("vjtop.altClear") != null) { System.out.print('\f'); } else { System.out.print(CLEAR_TERMINAL_ANSI_CMD); } } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { while (true) { try { String command = reader.readLine().trim().toLowerCase(); if (command.equals("t")) { printStacktrace(); } else if (command.equals("d")) { changeDisplayMode(); } else if (command.equals("q")) { app.exit(); return; } else if (command.equalsIgnoreCase("h") || command.equalsIgnoreCase("help")) { printHelp(); } else if (command.equals("")) { } else { tty.println("Unkown command: " + command); printHelp(); } tty.print(" Input command (h for help):"); } catch (Exception e) { e.printStackTrace(tty); } } }
#vulnerable code public void run() { while (true) { try { String command = new BufferedReader(new InputStreamReader(System.in)).readLine().trim(); if (command.equals("t")) { vjtop.setNeedForFurtherInput(true); System.err.print(" Input TID for stack:"); String pidStr = new BufferedReader(new InputStreamReader(System.in)).readLine(); try { long pid = Long.parseLong(pidStr); view.printStack(pid); } catch (NumberFormatException e) { System.err.println(" Wrong number format"); } //block the flush to let user see the result Utils.sleep(10000); vjtop.setNeedForFurtherInput(false); } else if (command.equals("d")) { vjtop.setNeedForFurtherInput(true); System.err.print( " Input number of Display Mode(1.cpu, 2.syscpu 3.total cpu 4.total syscpu 5.memory 6.total memory): "); String mode = new BufferedReader(new InputStreamReader(System.in)).readLine(); switch (mode) { case "1": view.setMode(DetailMode.cpu); break; case "2": view.setMode(DetailMode.syscpu); break; case "3": view.setMode(DetailMode.totalcpu); break; case "4": view.setMode(DetailMode.totalsyscpu); break; case "5": view.setMode(DetailMode.memory); break; case "6": view.setMode(DetailMode.totalmemory); break; default: System.err.println(" Wrong option for display mode"); break; } System.err.println(" Display mode changed to " + view.getMode() + " for next flush"); vjtop.setNeedForFurtherInput(false); } else if (command.equals("q")) { view.exit(); mainThread.interrupt(); System.err.println(" Quit."); return; } else if (command.equals("h")) { System.err.println(" t : print stack trace for the thread you choose"); System.err.println(" d : change threads display mode and ordering"); System.err.println(" q : quit"); System.err.println(" h : print help"); } else if (command.equals("")) { } else { System.err.println("Unkown command: " + command); } view.waitForCommand(); } catch (Exception e) { } } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/rocketmq-consumer.xml"); context.registerShutdownHook(); }
#vulnerable code public static void main(String[] args) { new ClassPathXmlApplicationContext("spring/rocketmq-consumer.xml"); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"}); context.start(); // 异步调用 async(context); // dubbo protocol DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理 String hello = demoService.sayHello("dubbo"); // 执行远程方法 System.out.println(hello); // 显示调用结果 // hessian protocol 直连 DemoService demoService2 = (DemoService) context.getBean("demoService2"); String hello2 = demoService2.sayHello("hessian直连"); System.out.println(hello2); // hessian protocol DemoService demoService3 = (DemoService) context.getBean("demoService3"); String hello3 = demoService3.sayHello("hessian"); System.out.println(hello3); // service group DemoService demoService4 = (DemoService) context.getBean("demoService4"); String hello4 = demoService4.sayHello("group:new"); System.out.println(hello4); // 回声测试可用性 EchoService echoService = (EchoService) demoService; Object status = echoService.$echo("OK"); System.out.println("回声测试:" + status.equals("OK")); System.out.println("#######################ALL SUCCESSFUL##########################"); }
#vulnerable code public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"}); context.start(); // dubbo protocol DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理 String hello = demoService.sayHello("dubbo"); // 执行远程方法 System.out.println(hello); // 显示调用结果 // hessian protocol 直连 DemoService demoService2 = (DemoService) context.getBean("demoService2"); String hello2 = demoService2.sayHello("hessian直连"); System.out.println(hello2); // hessian protocol DemoService demoService3 = (DemoService) context.getBean("demoService3"); String hello3 = demoService3.sayHello("hessian"); System.out.println(hello3); // service group DemoService demoService4 = (DemoService) context.getBean("demoService4"); String hello4 = demoService4.sayHello("group:new"); System.out.println(hello4); // 回声测试可用性 EchoService echoService = (EchoService) demoService; Object status = echoService.$echo("OK"); System.out.println("回声测试:" + status.equals("OK")); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { BitSet bitSet = new BitSet(Integer.MAX_VALUE);//hashcode的值域 String url = "http://baidu.com/a"; int hashcode = url.hashCode() & 0x7FFFFFFF; bitSet.set(hashcode); System.out.println(bitSet.cardinality());//着色位的个数 System.out.println(bitSet.get(hashcode));//检测存在性 bitSet.clear(hashcode);//清除位数据 }
#vulnerable code public static void main(String[] args) throws Exception { String path = "E:/btdata/bt_cumulation.txt"; BufferedReader br = new BufferedReader(new FileReader(path)); String line = null; br.readLine(); PrintWriter pw = new PrintWriter("E:/btdata/bt_cumulation2.txt"); int i = 0; while ((line = br.readLine()) != null) { //System.out.println("'" + line + "',"); String[] ss = line.split(","); String pin = ss[1]; pw.println(pin); if (i++ % 10 == 0) { pw.flush(); System.out.println(i); } } br.close(); pw.close(); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { long start = System.currentTimeMillis(); REQUEST_START_TIME.set(start); String url = WebTools.getHomeUrl(request); request.setAttribute("basePath", url); request.setAttribute("baseWithHostPath", WebTools.getHomeUrlWithHostNotProtocol(request)); request.setAttribute("pageEndTag", PAGE_END_TAG); String ext = null; if (target.contains("/")) { String name = target.substring(target.lastIndexOf('/')); if (name.contains(".")) { ext = name.substring(name.lastIndexOf('.')); } } try { AdminTokenVO adminTokenVO = new AdminTokenService().getAdminTokenVO(request); final ResponseRenderPrintWriter responseRenderPrintWriter = new ResponseRenderPrintWriter(response.getOutputStream(), url, PAGE_END_TAG, request, response, adminTokenVO); response = new MyHttpServletResponseWrapper(response,responseRenderPrintWriter); if (ext != null) { if (!FORBIDDEN_URI_EXT_SET.contains(ext)) { // 处理静态化文件,仅仅缓存文章页(变化较小) if (target.endsWith(".html") && target.startsWith("/" + Constants.getArticleUri())) { target = target.substring(0, target.lastIndexOf(".")); if (Constants.isStaticHtmlStatus() && adminTokenVO == null) { String path = new String(request.getServletPath().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + path)); } else { this.next.handle(target, request, response, isHandled); } } else { this.next.handle(target, request, response, isHandled); } } else { //非法请求, 返回403 response.sendError(403); } } else { //首页静态化 if ("/".equals(target) && Constants.isStaticHtmlStatus() && adminTokenVO == null) { responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + "/index.html")); } else { this.next.handle(target, request, response, isHandled); //JFinal, JsonRender 移除了 flush(),需要手动 flush,针对JFinal3.3 以后版本 response.getWriter().flush(); } } } catch (Exception e) { LOGGER.error("", e); } finally { I18nUtil.removeI18n(); //开发环境下面打印整个请求的耗时,便于优化代码 if (BlogBuildInfoUtil.isDev()) { LOGGER.info("{} used time {}", request.getServletPath(), System.currentTimeMillis() - start); } //仅保留非静态资源请求或者是以 .html结尾的 if (ZrLogConfig.isInstalled() && !target.contains(".") || target.endsWith(".html")) { RequestInfo requestInfo = new RequestInfo(); requestInfo.setIp(WebTools.getRealIp(request)); requestInfo.setUrl(url); requestInfo.setUserAgent(request.getHeader("User-Agent")); requestInfo.setRequestTime(System.currentTimeMillis()); requestInfo.setRequestUri(target); RequestStatisticsPlugin.record(requestInfo); } } REQUEST_START_TIME.remove(); }
#vulnerable code @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { long start = System.currentTimeMillis(); REQUEST_START_TIME.set(start); String url = WebTools.getHomeUrl(request); request.setAttribute("basePath", url); request.setAttribute("baseWithHostPath", WebTools.getHomeUrlWithHostNotProtocol(request)); request.setAttribute("pageEndTag", PAGE_END_TAG); String ext = null; if (target.contains("/")) { String name = target.substring(target.lastIndexOf('/')); if (name.contains(".")) { ext = name.substring(name.lastIndexOf('.')); } } try { AdminTokenVO adminTokenVO = new AdminTokenService().getAdminTokenVO(request); final ResponseRenderPrintWriter responseRenderPrintWriter = new ResponseRenderPrintWriter(response.getOutputStream(), url, PAGE_END_TAG, request, response, adminTokenVO); response = new HttpServletResponseWrapper(response) { @Override public PrintWriter getWriter() { return responseRenderPrintWriter; } }; if (ext != null) { if (!FORBIDDEN_URI_EXT_SET.contains(ext)) { // 处理静态化文件,仅仅缓存文章页(变化较小) if (target.endsWith(".html") && target.startsWith("/" + Constants.getArticleUri())) { target = target.substring(0, target.lastIndexOf(".")); if (Constants.isStaticHtmlStatus() && adminTokenVO == null) { String path = new String(request.getServletPath().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + path)); } else { this.next.handle(target, request, response, isHandled); } } else { this.next.handle(target, request, response, isHandled); } } else { //非法请求, 返回403 response.sendError(403); } } else { //首页静态化 if ("/".equals(target) && Constants.isStaticHtmlStatus() && adminTokenVO == null) { responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + "/index.html")); } else { this.next.handle(target, request, response, isHandled); } } } catch (Exception e) { LOGGER.error("", e); } finally { I18nUtil.removeI18n(); //开发环境下面打印整个请求的耗时,便于优化代码 if (BlogBuildInfoUtil.isDev()) { LOGGER.info("{} used time {}", request.getServletPath(), System.currentTimeMillis() - start); } //仅保留非静态资源请求或者是以 .html结尾的 if (ZrLogConfig.isInstalled() && !target.contains(".") || target.endsWith(".html")) { RequestInfo requestInfo = new RequestInfo(); requestInfo.setIp(WebTools.getRealIp(request)); requestInfo.setUrl(url); requestInfo.setUserAgent(request.getHeader("User-Agent")); requestInfo.setRequestTime(System.currentTimeMillis()); requestInfo.setRequestUri(target); RequestStatisticsPlugin.record(requestInfo); } } REQUEST_START_TIME.remove(); } #location 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void serializeToJsonIteratorWithEmbeddedMap() throws Exception { Graph g = TinkerGraph.open(null); final Vertex v = g.addVertex(); final Map<String, Object> map = new HashMap<>(); map.put("x", 500); map.put("y", "some"); final ArrayList friends = new ArrayList(); friends.add("x"); friends.add(5); friends.add(map); v.setProperty("friends", friends); final Iterator iterable = g.query().vertices().iterator(); final String results = ResultSerializer.JSON_RESULT_SERIALIZER.serialize(iterable, new Context(msg, null, null, null)); final JSONObject json = new JSONObject(results); assertNotNull(json); assertEquals(msg.requestId.toString(), json.getString(ResultSerializer.JsonResultSerializer.TOKEN_REQUEST)); final JSONArray converted = json.getJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_RESULT); assertNotNull(converted); assertEquals(1, converted.length()); final JSONObject vertexAsJson = converted.optJSONObject(0); assertNotNull(vertexAsJson); final JSONObject properties = vertexAsJson.optJSONObject(ResultSerializer.JsonResultSerializer.TOKEN_PROPERTIES); assertNotNull(properties); final JSONArray friendsProperty = properties.optJSONArray("friends"); assertNotNull(friendsProperty); assertEquals(3, friends.size()); final String object1 = friendsProperty.getString(0); assertEquals("x", object1); final int object2 = friendsProperty.getInt(1); assertEquals(5, object2); final JSONObject object3 = friendsProperty.getJSONObject(2); assertEquals(500, object3.getInt("x")); assertEquals("some", object3.getString("y")); }
#vulnerable code @Test public void serializeToJsonIteratorWithEmbeddedMap() throws Exception { final Graph g = new TinkerGraph(); final Vertex v = g.addVertex(); final Map<String, Object> map = new HashMap<>(); map.put("x", 500); map.put("y", "some"); final ArrayList friends = new ArrayList(); friends.add("x"); friends.add(5); friends.add(map); v.setProperty("friends", friends); final Iterator iterable = g.query().vertices().iterator(); final String results = ResultSerializer.JSON_RESULT_SERIALIZER.serialize(iterable, new Context(msg, null, null, null)); final JSONObject json = new JSONObject(results); assertNotNull(json); assertEquals(msg.requestId.toString(), json.getString(ResultSerializer.JsonResultSerializer.TOKEN_REQUEST)); final JSONArray converted = json.getJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_RESULT); assertNotNull(converted); assertEquals(1, converted.length()); final JSONObject vertexAsJson = converted.optJSONObject(0); assertNotNull(vertexAsJson); final JSONObject properties = vertexAsJson.optJSONObject(ResultSerializer.JsonResultSerializer.TOKEN_PROPERTIES); assertNotNull(properties); final JSONArray friendsProperty = properties.optJSONArray("friends"); assertNotNull(friendsProperty); assertEquals(3, friends.size()); final String object1 = friendsProperty.getString(0); assertEquals("x", object1); final int object2 = friendsProperty.getInt(1); assertEquals(5, object2); final JSONObject object3 = friendsProperty.getJSONObject(2); assertEquals(500, object3.getInt("x")); assertEquals("some", object3.getString("y")); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testTinkerGraph() { TinkerGraph g = new TinkerGraph(); g.createIndex("name", Vertex.class); Vertex marko = g.addVertex(TinkerProperty.make("name", "marko", "age", 33, "blah", "bloop")); Vertex stephen = g.addVertex(TinkerProperty.make("name", "stephen", "id", 12, "blah", "bloop")); Random r = new Random(); Stream.generate(()->g.addVertex(TinkerProperty.make("blah",r.nextInt()))).limit(100000).count(); assertEquals(g.vertices.size(), 100002); marko.addEdge("knows", stephen); System.out.println(g.query().has("name", Compare.EQUAL, "marko").vertices()); System.out.println(marko.query().direction(Direction.OUT).labels("knows", "workedWith").vertices()); g.createIndex("blah", Vertex.class); }
#vulnerable code public void testTinkerGraph() { TinkerGraph g = new TinkerGraph(); g.createIndex("name", Vertex.class); Vertex marko = g.addVertex(TinkerProperty.make("name", "marko", "age", 33)); Vertex stephen = g.addVertex(TinkerProperty.make("name", "stephen", "id", 12)); marko.addEdge("knows", stephen); System.out.println(g.query().has("name", Compare.EQUAL, "marko").vertices()); System.out.println(marko.query().direction(Direction.OUT).labels("knows", "workedWith").vertices()); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private FunctionThatThrows<RequestMessage, Object> select(final RequestMessage message, final GremlinServer.Graphs graphs) { final Bindings bindings = new SimpleBindings(); bindings.putAll(extractBindingsFromMessage(message)); final String language = message.<String>optionalArgs("language").orElse("gremlin-groovy"); if (message.optionalSessionId().isPresent()) { // an in session request...throw in a dummy graph instance for now.............................. final Graph g = TinkerFactory.createClassic(); bindings.put("g", g); final GremlinSession session = getGremlinSession(message.sessionId, bindings); if (logger.isDebugEnabled()) logger.debug("Using session {} ScriptEngine to process {}", message.sessionId, message); return s -> session.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings, language); } else { // a sessionless request if (logger.isDebugEnabled()) logger.debug("Using shared ScriptEngine to process {}", message); return s -> { // put all the preconfigured graphs on the bindings bindings.putAll(graphs.getGraphs()); try { // do a safety cleanup of previous transaction...if any graphs.rollbackAll(); final Object o = sharedScriptEngines.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings, language); graphs.commitAll(); return o; } catch (ScriptException ex) { // todo: gotta work on error handling for failed scripts.......... graphs.rollbackAll(); throw ex; } }; } }
#vulnerable code private FunctionThatThrows<RequestMessage, Object> select(final RequestMessage message, final GremlinServer.Graphs graphs) { final Bindings bindings = new SimpleBindings(); bindings.putAll(extractBindingsFromMessage(message)); if (message.optionalSessionId().isPresent()) { // an in session request...throw in a dummy graph instance for now.............................. final Graph g = TinkerFactory.createClassic(); bindings.put("g", g); final GremlinSession session = getGremlinSession(message.sessionId, bindings); if (logger.isDebugEnabled()) logger.debug("Using session {} ScriptEngine to process {}", message.sessionId, message); return s -> session.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings); } else { // a sessionless request if (logger.isDebugEnabled()) logger.debug("Using shared ScriptEngine to process {}", message); return s -> { // put all the preconfigured graphs on the bindings bindings.putAll(graphs.getGraphs()); try { // do a safety cleanup of previous transaction...if any graphs.rollbackAll(); final Object o = sharedScriptEngine.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings); graphs.commitAll(); return o; } catch (ScriptException ex) { // todo: gotta work on error handling for failed scripts.......... graphs.rollbackAll(); throw ex; } }; } } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public TableEvaluationRequest readFrom(Class<TableEvaluationRequest> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { String charset = getCharset(mediaType); MultivaluedMap<String, String> queryParameters = this.uriInfo.getQueryParameters(); String delimiterChar = queryParameters.getFirst("delimiterChar"); String quoteChar = queryParameters.getFirst("quoteChar"); BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, charset)){ @Override public void close(){ // The closing of the underlying java.io.InputStream is handled elsewhere } }; TableEvaluationRequest tableRequest; try { CsvPreference format; if(delimiterChar != null){ format = CsvUtil.getFormat(delimiterChar, quoteChar); } else { format = CsvUtil.getFormat(reader); } tableRequest = CsvUtil.readTable(reader, format); TableFormat tableFormat = new TableFormat() .setCharset(charset) .setDelimiterChar((char)format.getDelimiterChar()) .setQuoteChar(format.getQuoteChar()); tableRequest.setFormat(tableFormat); } catch(Exception e){ logger.error("Failed to load CSV document", e); throw new BadRequestException(e); } finally { reader.close(); } return tableRequest; }
#vulnerable code @Override public TableEvaluationRequest readFrom(Class<TableEvaluationRequest> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException { String charset = getCharset(mediaType); MultivaluedMap<String, String> queryParameters = this.uriInfo.getQueryParameters(); String delimiterChar = queryParameters.getFirst("delimiterChar"); String quoteChar = queryParameters.getFirst("quoteChar"); BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, charset)){ @Override public void close(){ // The closing of the underlying java.io.InputStream is handled elsewhere } }; TableEvaluationRequest tableRequest; try { CsvPreference format; if(delimiterChar != null){ format = CsvUtil.getFormat(delimiterChar, quoteChar); } else { format = CsvUtil.getFormat(reader); } tableRequest = CsvUtil.readTable(reader, format); } catch(Exception e){ logger.error("Failed to load CSV document", e); throw new BadRequestException(e); } finally { reader.close(); } tableRequest.setCharset(charset); return tableRequest; } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void addLink(final long srcId, final long destId, final double bandwidth, final double latency) { if (getTopologycalGraph() == null) { graph = new TopologicalGraph(); } if (entitiesMap == null) { entitiesMap = new HashMap<>(); } // maybe add the nodes addNodeMapping(srcId); addNodeMapping(destId); // generate a new link getTopologycalGraph().addLink(new TopologicalLink(entitiesMap.get(srcId), entitiesMap.get(destId), (float) latency, (float) bandwidth)); generateMatrices(); }
#vulnerable code @Override public void addLink(final long srcId, final long destId, final double bandwidth, final double latency) { if (getTopologycalGraph() == null) { graph = new TopologicalGraph(); } if (map == null) { map = new HashMap<>(); } // maybe add the nodes addNodeMapping(srcId); addNodeMapping(destId); // generate a new link getTopologycalGraph().addLink(new TopologicalLink(map.get(srcId), map.get(destId), (float) latency, (float) bandwidth)); generateMatrices(); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void updateExecutionTask(ResCloudlet rcl, double currentTime, Processor p) { NetworkCloudlet netcl = (NetworkCloudlet)rcl.getCloudlet(); if(!(netcl.getCurrentTask() instanceof CloudletExecutionTask)) throw new RuntimeException( "This method has to be called only when the current task of the NetworkCloudlet, inside the given ResCloudlet, is a CloudletExecutionTask"); /** * @todo @author manoelcampos The method updates the execution * length of the task, considering the NetworkCloudlet * has only 1 execution task. */ CloudletExecutionTask task = (CloudletExecutionTask)netcl.getCurrentTask(); task.process(netcl.getCloudletFinishedSoFar()); if (task.isFinished()) { netcl.getCurrentTask().computeExecutionTime(currentTime); startNextTask(netcl); } }
#vulnerable code protected void updateExecutionTask(ResCloudlet rcl, double currentTime, Processor p) { NetworkCloudlet netcl = (NetworkCloudlet)rcl.getCloudlet(); /** * @todo @author manoelcampos updates the execution * length of the task, considering the NetworkCloudlet * has only one execution task. */ CloudletExecutionTask task = (CloudletExecutionTask)netcl.getCurrentTask(); task.process(netcl.getCloudletFinishedSoFar()); if (task.isFinished()) { netcl.getCurrentTask().computeExecutionTime(currentTime); startNextTask(netcl); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<String> readContractList() { return ResourceLoader .newBufferedReader(SLA_CONTRACTS_LIST, getClass()) .lines() .filter(l -> !l.startsWith("#")) .filter(l -> !l.trim().isEmpty()) .collect(toList()); }
#vulnerable code private List<String> readContractList() { return ResourceLoader .getBufferedReader(getClass(), SLA_CONTRACTS_LIST) .lines() .filter(l -> !l.startsWith("#")) .filter(l -> !l.trim().isEmpty()) .collect(toList()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static GoogleTaskEventsTraceReader getInstance( final CloudSim simulation, final String filePath, final Function<TaskEvent, Cloudlet> cloudletCreationFunction) { final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleTaskEventsTraceReader.class); return new GoogleTaskEventsTraceReader(simulation, filePath, reader, cloudletCreationFunction); }
#vulnerable code public static GoogleTaskEventsTraceReader getInstance( final CloudSim simulation, final String filePath, final Function<TaskEvent, Cloudlet> cloudletCreationFunction) { final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleTaskEventsTraceReader.class); return new GoogleTaskEventsTraceReader(simulation, filePath, reader, cloudletCreationFunction); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<String> readContractList() { return ResourceLoader .newBufferedReader(SLA_CONTRACTS_LIST, getClass()) .lines() .map(String::trim) .filter(line -> !line.isEmpty()) .filter(line -> !line.startsWith("#")) .collect(toList()); }
#vulnerable code private List<String> readContractList() { return ResourceLoader .getBufferedReader(getClass(), SLA_CONTRACTS_LIST) .lines() .map(String::trim) .filter(line -> !line.isEmpty()) .filter(line -> !line.startsWith("#")) .collect(toList()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void onClockTick(final EventInfo info) { for (Host host : datacenter0.getHostList()) { System.out.printf("Host %-2d Time: %.0f%n", host.getId(), info.getTime()); for (Vm vm : host.getVmList()) { System.out.printf( "\tVm %2d: Host's CPU utilization: %5.0f%% | Host's RAM utilization: %5.0f%% | Host's BW utilization: %5.0f%%%n", vm.getId(), vm.getHostCpuUtilization()*100, vm.getHostRamUtilization()*100, vm.getHostBwUtilization()*100); } System.out.printf( "Host %-2d Total Utilization: %5.0f%% | %5.0f%% | %5.0f%%%n%n", host.getId(),host.getCpuPercentUtilization()*100, host.getRam().getPercentUtilization()*100, host.getBw().getPercentUtilization()*100); } }
#vulnerable code private void onClockTick(final EventInfo info) { for (Host host : datacenter0.getHostList()) { System.out.printf("Host %-2d Time: %.0f\n", host.getId(), info.getTime()); for (Vm vm : host.getVmList()) { System.out.printf( "\tVm %2d: Host's CPU utilization: %5.0f%% | Host's RAM utilization: %5.0f%% | Host's BW utilization: %5.0f%%\n", vm.getId(), vm.getHostCpuUtilization()*100, vm.getHostRamUtilization()*100, vm.getHostBwUtilization()*100); } System.out.printf( "Host %-2d Total Utilization: %5.0f%% | %5.0f%% | %5.0f%%\n\n", host.getId(),host.getCpuPercentUtilization()*100, host.getRam().getPercentUtilization()*100, host.getBw().getPercentUtilization()*100); } } #location 5 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static BriteNetworkTopology getInstance(final String fileName){ final InputStreamReader reader = ResourceLoader.newInputStreamReader(fileName, BriteNetworkTopology.class); return new BriteNetworkTopology(reader); }
#vulnerable code public static BriteNetworkTopology getInstance(final String fileName){ final InputStreamReader reader = new InputStreamReader(ResourceLoader.getInputStream(fileName, BriteNetworkTopology.class)); return new BriteNetworkTopology(reader); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static GoogleMachineEventsTraceReader getInstance( final String filePath, final Function<MachineEvent, Host> hostCreationFunction) { final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleMachineEventsTraceReader.class); return new GoogleMachineEventsTraceReader(filePath, reader, hostCreationFunction); }
#vulnerable code public static GoogleMachineEventsTraceReader getInstance( final String filePath, final Function<MachineEvent, Host> hostCreationFunction) { final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleMachineEventsTraceReader.class); return new GoogleMachineEventsTraceReader(filePath, reader, hostCreationFunction); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void printVmUtilizationHistory(Vm vm) { System.out.println(vm + " RAM and BW utilization history"); System.out.println("----------------------------------------------------------------------------------"); //A set containing all resource utilization collected times final Set<Double> timeSet = allVmsRamUtilizationHistory.get(vm).keySet(); final Map<Double, Double> vmRamUtilization = allVmsRamUtilizationHistory.get(vm); final Map<Double, Double> vmBwUtilization = allVmsBwUtilizationHistory.get(vm); for (final double time : timeSet) { System.out.printf( "Time: %10.1f secs | RAM Utilization: %10.2f%% | BW Utilization: %10.2f%%%n", time, vmRamUtilization.get(time) * 100, vmBwUtilization.get(time) * 100); } System.out.printf("----------------------------------------------------------------------------------%n%n"); }
#vulnerable code private void printVmUtilizationHistory(Vm vm) { System.out.println(vm + " RAM and BW utilization history"); System.out.println("----------------------------------------------------------------------------------"); //A set containing all resource utilization collected times final Set<Double> timeSet = allVmsRamUtilizationHistory.get(vm).keySet(); final Map<Double, Double> vmRamUtilization = allVmsRamUtilizationHistory.get(vm); final Map<Double, Double> vmBwUtilization = allVmsBwUtilizationHistory.get(vm); for (final double time : timeSet) { System.out.printf( "Time: %10.1f secs | RAM Utilization: %10.2f%% | BW Utilization: %10.2f%%\n", time, vmRamUtilization.get(time) * 100, vmBwUtilization.get(time) * 100); } System.out.println("----------------------------------------------------------------------------------\n"); } #location 12 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static SwfWorkloadFileReader getInstance(final String fileName, final int mips) { final InputStream reader = ResourceLoader.newInputStream(fileName, SwfWorkloadFileReader.class); return new SwfWorkloadFileReader(fileName, reader, mips); }
#vulnerable code public static SwfWorkloadFileReader getInstance(final String fileName, final int mips) { final InputStream reader = ResourceLoader.getInputStream(fileName, SwfWorkloadFileReader.class); return new SwfWorkloadFileReader(fileName, reader, mips); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void showCpuUtilizationForAllVms(final double simulationFinishTime) { System.out.printf("%nHosts CPU utilization history for the entire simulation period%n%n"); int numberOfUsageHistoryEntries = 0; for (Vm vm : vmlist) { System.out.printf("VM %d%n", vm.getId()); if (vm.getUtilizationHistory().getHistory().isEmpty()) { System.out.println("\tThere isn't any usage history"); continue; } for (Map.Entry<Double, Double> entry : vm.getUtilizationHistory().getHistory().entrySet()) { final double time = entry.getKey(); final double vmCpuUsage = entry.getValue()*100; if (vmCpuUsage > 0) { numberOfUsageHistoryEntries++; System.out.printf("\tTime: %2.0f CPU Utilization: %6.2f%%%n", time, vmCpuUsage); } } } if (numberOfUsageHistoryEntries == 0) { System.out.println("No CPU usage history was found"); } }
#vulnerable code private void showCpuUtilizationForAllVms(final double simulationFinishTime) { System.out.println("\nHosts CPU utilization history for the entire simulation period\n"); int numberOfUsageHistoryEntries = 0; for (Vm vm : vmlist) { System.out.printf("VM %d\n", vm.getId()); if (vm.getUtilizationHistory().getHistory().isEmpty()) { System.out.println("\tThere isn't any usage history"); continue; } for (Map.Entry<Double, Double> entry : vm.getUtilizationHistory().getHistory().entrySet()) { final double time = entry.getKey(); final double vmCpuUsage = entry.getValue()*100; if (vmCpuUsage > 0) { numberOfUsageHistoryEntries++; System.out.printf("\tTime: %2.0f CPU Utilization: %6.2f%%\n", time, vmCpuUsage); } } } if (numberOfUsageHistoryEntries == 0) { System.out.println("No CPU usage history was found"); } } #location 16 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static GoogleTaskUsageTraceReader getInstance( final List<DatacenterBroker> brokers, final String filePath) { final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleTaskUsageTraceReader.class); return new GoogleTaskUsageTraceReader(brokers, filePath, reader); }
#vulnerable code public static GoogleTaskUsageTraceReader getInstance( final List<DatacenterBroker> brokers, final String filePath) { final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleTaskUsageTraceReader.class); return new GoogleTaskUsageTraceReader(brokers, filePath, reader); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String downloadFromServer(RemoteUrl remoteUrl, String fileName, String localFileDir, String localFileDirTemp, String copy2TargetDirPath, boolean enableLocalDownloadDirInClassPath, int retryTimes, int retrySleepSeconds) throws Exception { // 目标地址文件 File localFile = null; // // 进行下载、mv、copy // try { // 可重试的下载 File tmpFilePathUniqueFile = retryDownload(localFileDirTemp, fileName, remoteUrl, retryTimes, retrySleepSeconds); // 将 tmp file copy localFileDir localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, localFileDir, fileName, false); // mv 到指定目录 if (copy2TargetDirPath != null) { // if (enableLocalDownloadDirInClassPath || !copy2TargetDirPath.equals(ClassLoaderUtil.getClassPath ())) { localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, copy2TargetDirPath, fileName, true); } } LOGGER.debug("Move to: " + localFile.getAbsolutePath()); } catch (Exception e) { LOGGER.warn("download file failed, using previous download file.", e); } // // 判断是否下载失败 // if (localFile == null || !localFile.exists()) { throw new Exception("target file cannot be found! " + fileName); } // // 下面为下载成功 // // 返回相对路径 String relativePathString = OsUtil.getRelativePath(localFile, new File(localFileDir)); if (relativePathString != null) { if (new File(relativePathString).isFile()) { return relativePathString; } } // 否则, 返回全路径 return localFile.getAbsolutePath(); }
#vulnerable code @Override public String downloadFromServer(RemoteUrl remoteUrl, String fileName, String localFileDir, String localFileDirTemp, String copy2TargetDirPath, boolean enableLocalDownloadDirInClassPath, int retryTimes, int retrySleepSeconds) throws Exception { // 目标地址文件 File localFile = null; // // 进行下载、mv、copy // try { // 可重试的下载 File tmpFilePathUniqueFile = retryDownload(localFileDirTemp, fileName, remoteUrl, retryTimes, retrySleepSeconds); // 将 tmp file copy localFileDir localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, localFileDir, fileName, false); // mv 到指定目录 if (copy2TargetDirPath != null) { // if (enableLocalDownloadDirInClassPath || !copy2TargetDirPath.equals(ClassLoaderUtil.getClassPath ())) { localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, copy2TargetDirPath, fileName, true); } } LOGGER.debug("Move to: " + localFile.getAbsolutePath()); } catch (Exception e) { LOGGER.warn("download file failed, using previous download file.", e); } // // 判断是否下载失败 // if (!localFile.exists()) { throw new Exception("target file cannot be found! " + fileName); } // // 下面为下载成功 // // 返回相对路径 if (localFileDir != null) { String relativePathString = OsUtil.getRelativePath(localFile, new File(localFileDir)); if (relativePathString != null) { if (new File(relativePathString).isFile()) { return relativePathString; } } } // 否则, 返回全路径 return localFile.getAbsolutePath(); } #location 44 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static Properties loadWithTomcatMode(final String propertyFilePath) throws Exception { Properties props = new Properties(); try { // 先用TOMCAT模式进行导入 // http://blog.csdn.net/minfree/article/details/1800311 // http://stackoverflow.com/questions/3263560/sysloader-getresource-problem-in-java URL url = ClassLoaderUtil.getLoader().getResource(propertyFilePath); URI uri = new URI(url.toString()); props.load(new InputStreamReader(new FileInputStream(uri.getPath()), "utf-8")); } catch (Exception e) { // http://stackoverflow.com/questions/574809/load-a-resource-contained-in-a-jar props.load(new InputStreamReader(ClassLoaderUtil.getLoader().getResourceAsStream(propertyFilePath), "utf-8")); } return props; }
#vulnerable code private static Properties loadWithTomcatMode(final String propertyFilePath) throws Exception { Properties props = new Properties(); try { // 先用TOMCAT模式进行导入 // http://blog.csdn.net/minfree/article/details/1800311 // http://stackoverflow.com/questions/3263560/sysloader-getresource-problem-in-java URL url = ClassLoaderUtil.getLoader().getResource(propertyFilePath); URI uri = new URI(url.toString()); props.load(new FileInputStream(uri.getPath())); } catch (Exception e) { // http://stackoverflow.com/questions/574809/load-a-resource-contained-in-a-jar props.load(ClassLoaderUtil.getLoader().getResourceAsStream(propertyFilePath)); } return props; } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @ManagedMetric(description = "Total RAM assigned") public long getTotalRAMAssigned() { return convertPotentialLong(parseStorageTotals().get("ram").get("total")); }
#vulnerable code @ManagedMetric(description = "Total RAM assigned") public long getTotalRAMAssigned() { return (Long) parseStorageTotals().get("ram").get("total"); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @ManagedMetric(description = "Total Disk Space used") public long getTotalDiskUsed() { return convertPotentialLong(parseStorageTotals().get("hdd").get("used")); }
#vulnerable code @ManagedMetric(description = "Total Disk Space used") public long getTotalDiskUsed() { return (Long) parseStorageTotals().get("hdd").get("used"); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { // comment out references to 'protected' and 'mybucket' - they are only to show how multi-bucket would work // CouchbaseTemplate personTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("protected"),new // MappingCouchbaseConverter()); // baseMapping.mapEntity(Person.class, personTemplate); // Person goes in "protected" bucket // CouchbaseTemplate userTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("mybucket"),new // MappingCouchbaseConverter()); // baseMapping.mapEntity(User.class, userTemplate); // User goes in "mybucket" // everything else goes in getBucketName() ( which is travel-sample ) } catch (Exception e) { throw e; } }
#vulnerable code @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { CouchbaseTemplate personTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("protected"),new MappingCouchbaseConverter()); baseMapping.mapEntity(Person.class, personTemplate); // Person goes in "protected" bucket CouchbaseTemplate userTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("mybucket"),new MappingCouchbaseConverter()); baseMapping.mapEntity(User.class, userTemplate); // User goes in "mybucket" // everything else goes in getBucketName() ( which is travel-sample ) } catch (Exception e) { throw e; } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { // comment out references to 'protected' and 'mybucket' - they are only to show how multi-bucket would work // CouchbaseTemplate personTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("protected"),new // MappingCouchbaseConverter()); // baseMapping.mapEntity(Person.class, personTemplate); // Person goes in "protected" bucket // CouchbaseTemplate userTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("mybucket"),new // MappingCouchbaseConverter()); // baseMapping.mapEntity(User.class, userTemplate); // User goes in "mybucket" // everything else goes in getBucketName() ( which is travel-sample ) } catch (Exception e) { throw e; } }
#vulnerable code @Override public void configureRepositoryOperationsMapping(RepositoryOperationsMapping baseMapping) { try { CouchbaseTemplate personTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("protected"),new MappingCouchbaseConverter()); baseMapping.mapEntity(Person.class, personTemplate); // Person goes in "protected" bucket CouchbaseTemplate userTemplate = myCouchbaseTemplate(myCouchbaseClientFactory("mybucket"),new MappingCouchbaseConverter()); baseMapping.mapEntity(User.class, userTemplate); // User goes in "mybucket" // everything else goes in getBucketName() ( which is travel-sample ) } catch (Exception e) { throw e; } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testUnicodeEscape() throws Exception { String code = "abc,\\u0070\\u0075\\u0062\\u006C\\u0069\\u0063"; CSVParser parser = new CSVParser(code, CSVFormat.DEFAULT.withUnicodeEscapesInterpreted(true)); final Iterator<String[]> iterator = parser.iterator(); String[] data = iterator.next(); assertEquals(2, data.length); assertEquals("abc", data[0]); assertEquals("public", data[1]); assertFalse("Should not have any more records", iterator.hasNext()); }
#vulnerable code public void testUnicodeEscape() throws Exception { String code = "abc,\\u0070\\u0075\\u0062\\u006C\\u0069\\u0063"; CSVParser parser = new CSVParser(code, CSVFormat.DEFAULT.withUnicodeEscapesInterpreted(true)); String[] data = parser.iterator().next(); assertEquals(2, data.length); assertEquals("abc", data[0]); assertEquals("public", data[1]); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br.close(); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); br.close(); }
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMutators() { final CSVFormat format = new CSVFormat('!', '!', null, '!', '!', true, true, CRLF, null); assertEquals('?', format.withDelimiter('?').getDelimiter()); assertEquals('?', format.withQuoteChar('?').getQuoteChar().charValue()); assertEquals('?', format.withCommentStart('?').getCommentStart().charValue()); assertEquals("?", format.withLineSeparator("?").getLineSeparator()); assertEquals('?', format.withEscape('?').getEscape().charValue()); assertFalse(format.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); assertFalse(format.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); assertEquals(Quote.ALL, format.withQuotePolicy(Quote.ALL).getQuotePolicy()); }
#vulnerable code @Test public void testMutators() { final CSVFormat format = new CSVFormat('!', '!', null, '!', '!', true, true, CRLF, null); assertEquals('?', format.withDelimiter('?').getDelimiter()); assertEquals('?', format.withEncapsulator('?').getQuoteChar().charValue()); assertEquals('?', format.withCommentStart('?').getCommentStart().charValue()); assertEquals("?", format.withLineSeparator("?").getLineSeparator()); assertEquals('?', format.withEscape('?').getEscape().charValue()); assertFalse(format.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); assertFalse(format.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); assertEquals(Quote.ALL, format.withQuotePolicy(Quote.ALL).getQuotePolicy()); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReadLine() throws Exception { ExtendedBufferedReader br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); }
#vulnerable code public void testReadLine() throws Exception { br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReadLine() throws Exception { ExtendedBufferedReader br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); }
#vulnerable code public void testReadLine() throws Exception { br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testGetLine() throws IOException { CSVParser parser = new CSVParser(new StringReader(code)); for (String[] re : res) { assertTrue(Arrays.equals(re, parser.getLine())); } assertTrue(parser.getLine() == null); }
#vulnerable code public void testGetLine() throws IOException { CSVParser parser = new CSVParser(new StringReader(code)); String[] tmp = null; for (int i = 0; i < res.length; i++) { tmp = parser.getLine(); assertTrue(Arrays.equals(res[i], tmp)); } tmp = parser.getLine(); assertTrue(tmp == null); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetRecords() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } parser.close(); }
#vulnerable code @Test public void testGetRecords() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCSVUrl() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName + " require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for (int i = 1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=", 2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName + " unexpected option: " + option); } } line = readTestData(); // get string version of format assertEquals(testName + " Expected format ", line, format.toString()); // Now parse the file and compare against the expected results final URL resource = ClassLoader.getSystemResource("CSVFileParser/" + split[0]); final CSVParser parser = CSVParser.parse(resource, Charset.forName("UTF-8"), format); for (final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count + ":" + parsed); } parser.close(); }
#vulnerable code @Test public void testCSVUrl() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName + " require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for (int i = 1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=", 2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName + " unexpected option: " + option); } } line = readTestData(); // get string version of format assertEquals(testName + " Expected format ", line, format.toString()); // Now parse the file and compare against the expected results final URL resource = ClassLoader.getSystemResource("CSVFileParser/" + split[0]); final CSVParser parser = CSVParser.parse(resource, Charset.forName("UTF-8"), format); for (final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count + ":" + parsed); } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; final String[][] res = { {"one", "two", "three"}, // 0 {"", ""}, // 1 {"'", "'"}, // 2 {"'", "'"}, // 3 {"'", "'"}, // 4 {",", ","}, // 5 {"/", "/"}, // 6 {"/", "/"}, // 7 {" 8 ", " \"quoted \"\" /\" / string\" "}, {"9", " \n "}, }; final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); final CSVParser parser = CSVParser.parse(code, format); final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Records do not match expected result", res, records); }
#vulnerable code @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; final String[][] res = { {"one", "two", "three"}, // 0 {"", ""}, // 1 {"'", "'"}, // 2 {"'", "'"}, // 3 {"'", "'"}, // 4 {",", ","}, // 5 {"/", "/"}, // 6 {"/", "/"}, // 7 {" 8 ", " \"quoted \"\" /\" / string\" "}, {"9", " \n "}, }; final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); final CSVParser parser = CSVParser.parseString(code, format); final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Records do not match expected result", res, records); } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
#vulnerable code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; String[][] res = { {"one", "two", "three"}, // 0 {"", ""}, // 1 {"'", "'"}, // 2 {"'", "'"}, // 3 {"'", "'"}, // 4 {",", ","}, // 5 {"/", "/"}, // 6 {"/", "/"}, // 7 {" 8 ", " \"quoted \"\" \" / string\" "}, {"9", " \n "}, }; CSVFormat format = new CSVFormat(',', '\'', CSVFormat.DISABLED, '/', false, false, true, true, "\r\n", null); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } }
#vulnerable code @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; String[][] res = { {"one", "two", "three"}, // 0 {"", ""}, // 1 {"'", "'"}, // 2 {"'", "'"}, // 3 {"'", "'"}, // 4 {",", ","}, // 5 {"/", "/"}, // 6 {"/", "/"}, // 7 {" 8 ", " \"quoted \"\" \" / string\" "}, {"9", " \n "}, }; CSVFormat format = new CSVFormat(',', '\'', CSVFormat.DISABLED, '/', false, false, true, true, "\r\n"); CSVParser parser = new CSVParser(code, format); String[][] tmp = parser.getRecords(); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } #location 38 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); parser.close(); }
#vulnerable code @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = CSVParser.parse(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); }
#vulnerable code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = CSVParser.parseString(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); printer.close(); }
#vulnerable code @Test public void testExcelPrintAllIterableOfArrays() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
#vulnerable code @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (final String code : codes) { final CSVParser parser = new CSVParser(new StringReader(code)); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testDefaultFormat() throws IOException { final String code = "" + "a,b#\n" // 1) + "\"\n\",\" \",#\n" // 2) + "#,\"\"\n" // 3) + "# Final comment\n"// 4) ; final String[][] res = { {"a", "b#"}, {"\n", " ", "#"}, {"#", ""}, {"# Final comment"} }; CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isCommentingEnabled()); CSVParser parser = CSVParser.parse(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Failed to parse without comments", res, records); final String[][] res_comments = { {"a", "b#"}, {"\n", " ", "#"}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = CSVParser.parse(code, format); records = parser.getRecords(); Utils.compare("Failed to parse with comments", res_comments, records); }
#vulnerable code @Test public void testDefaultFormat() throws IOException { final String code = "" + "a,b#\n" // 1) + "\"\n\",\" \",#\n" // 2) + "#,\"\"\n" // 3) + "# Final comment\n"// 4) ; final String[][] res = { {"a", "b#"}, {"\n", " ", "#"}, {"#", ""}, {"# Final comment"} }; CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isCommentingEnabled()); CSVParser parser = CSVParser.parseString(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Failed to parse without comments", res, records); final String[][] res_comments = { {"a", "b#"}, {"\n", " ", "#"}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = CSVParser.parseString(code, format); records = parser.getRecords(); Utils.compare("Failed to parse with comments", res_comments, records); } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); printer.close(); }
#vulnerable code @Test public void testExcelPrinter2() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReadLine() throws Exception { ExtendedBufferedReader br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); }
#vulnerable code public void testReadLine() throws Exception { br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() throws UnsupportedEncodingException, IOException { InputStream pointsOfReference = getClass().getResourceAsStream("/CSV-198/optd_por_public.csv"); Assert.assertNotNull(pointsOfReference); try (@SuppressWarnings("resource") CSVParser parser = CSV_FORMAT.parse(new InputStreamReader(pointsOfReference, "UTF-8"))) { for (CSVRecord record : parser) { String locationType = record.get("location_type"); Assert.assertNotNull(locationType); } } }
#vulnerable code @Test public void test() throws UnsupportedEncodingException, IOException { InputStream pointsOfReference = getClass().getResourceAsStream("/CSV-198/optd_por_public.csv"); Assert.assertNotNull(pointsOfReference); CSVParser parser = CSV_FORMAT.parse(new InputStreamReader(pointsOfReference, "UTF-8")); for (CSVRecord record : parser) { String locationType = record.get("location_type"); Assert.assertNotNull(locationType); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReadUntil() throws Exception { ExtendedBufferedReader br = getEBR(""); assertTrue(br.readUntil(';').equals("")); br = getEBR("ABCDEF;GHL;;MN"); assertTrue(br.readUntil(';').equals("ABCDEF")); assertTrue(br.readUntil(';').length() == 0); br.skip(1); assertTrue(br.readUntil(';').equals("GHL")); br.skip(1); assertTrue(br.readUntil(';').equals("")); br.skip(1); assertTrue(br.readUntil(',').equals("MN")); }
#vulnerable code public void testReadUntil() throws Exception { br = getEBR(""); assertTrue(br.readUntil(';').equals("")); br = getEBR("ABCDEF;GHL;;MN"); assertTrue(br.readUntil(';').equals("ABCDEF")); assertTrue(br.readUntil(';').length() == 0); br.skip(1); assertTrue(br.readUntil(';').equals("GHL")); br.skip(1); assertTrue(br.readUntil(';').equals("")); br.skip(1); assertTrue(br.readUntil(',').equals("MN")); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; final String[][] res = { {"one", "two", "three"}, // 0 {"", ""}, // 1 {"'", "'"}, // 2 {"'", "'"}, // 3 {"'", "'"}, // 4 {",", ","}, // 5 {"/", "/"}, // 6 {"/", "/"}, // 7 {" 8 ", " \"quoted \"\" /\" / string\" "}, {"9", " \n "}, }; final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); final CSVParser parser = CSVParser.parse(code, format); final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Records do not match expected result", res, records); parser.close(); }
#vulnerable code @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; final String[][] res = { {"one", "two", "three"}, // 0 {"", ""}, // 1 {"'", "'"}, // 2 {"'", "'"}, // 3 {"'", "'"}, // 4 {",", ","}, // 5 {"/", "/"}, // 6 {"/", "/"}, // 7 {" 8 ", " \"quoted \"\" /\" / string\" "}, {"9", " \n "}, }; final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); final CSVParser parser = CSVParser.parse(code, format); final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Records do not match expected result", res, records); } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testEndOfFileBehaviourExcel() throws Exception { String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.EXCEL); String[][] tmp = parser.getAllValues(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } }
#vulnerable code public void testEndOfFileBehaviourExcel() throws Exception { String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; String code; for (int codeIndex = 0; codeIndex < codes.length; codeIndex++) { code = codes[codeIndex]; CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.EXCEL); String[][] tmp = parser.getAllValues(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } } #location 21 #vulnerability type RESOURCE_LEAK