output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void onServiceContextReceived(ServiceContext serviceContext) throws Throwable {
FlowMessage flowMessage = serviceContext.getFlowMessage();
if (serviceContext.isSync()) {
CacheManager.get(serviceActorCachePrefix + serviceContext.getFlowName()).add(serviceContext.getId(), getSender(),
defaultTimeToLive);
}
Serializer serializer = ExtensionLoader.load(Serializer.class).load(serviceContext.getCodec());
Object result = null;
Object param = null;
try {
ServiceContextUtil.fillServiceContext(serviceContext);
param = getAndDecodeParam(serviceContext);
if (getFilter(serviceContext) != null) {
getFilter(serviceContext).filter(param, serviceContext);
}
// logger.info("服务参数类型 {} : {}", pType, getService(serviceContext));
result = ((Service) getService(serviceContext)).process(param, serviceContext);
} catch (Throwable e) {
handleException(serviceContext, e, param, serializer);
}
if (result != null && result instanceof CompletableFuture) {
final Object tempParam = param;
((CompletableFuture<Object>) result).whenComplete((r, e) -> {
if (e != null) {
handleException(serviceContext, e, tempParam, serializer);
return;
}
handleNextServices(serviceContext, r, flowMessage.getTransactionId(), serializer);
});
} else {
handleNextServices(serviceContext, result, flowMessage.getTransactionId(), serializer);
}
}
|
#vulnerable code
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void onServiceContextReceived(ServiceContext serviceContext) throws Throwable {
FlowMessage flowMessage = serviceContext.getFlowMessage();
if (serviceContext.isSync()) {
CacheManager.get(serviceActorCachePrefix + serviceContext.getFlowName()).add(serviceContext.getId(), getSender(),
defaultTimeToLive);
}
Serializer serializer = ExtensionLoader.load(Serializer.class).load(serviceContext.getCodec());
Object result = null;
Object param = null;
try {
ServiceContextUtil.fillServiceContext(serviceContext);
String pType = getParamType(serviceContext);
if (flowMessage.getMessage() != null && ClassUtil.exists(flowMessage.getMessageType())) {
pType = flowMessage.getMessageType();
}
param = serializer.decode(flowMessage.getMessage(), pType);
if (getFilter(serviceContext) != null) {
getFilter(serviceContext).filter(param, serviceContext);
}
// logger.info("服务参数类型 {} : {}", pType, getService(serviceContext));
result = ((Service) getService(serviceContext)).process(param, serviceContext);
} catch (Throwable e) {
handleException(serviceContext, e, param, serializer);
}
if (result != null && result instanceof CompletableFuture) {
final Object tempParam = param;
((CompletableFuture<Object>) result).whenComplete((r, e) -> {
if (e != null) {
handleException(serviceContext, e, tempParam, serializer);
return;
}
handleNextServices(serviceContext, r, flowMessage.getTransactionId(), serializer);
});
} else {
handleNextServices(serviceContext, result, flowMessage.getTransactionId(), serializer);
}
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void doStartup(String configLocation) throws Throwable {
Class<?> applicationContextClazz =
Class.forName("org.springframework.context.support.ClassPathXmlApplicationContext", true, getClassLoader());
Object flowerFactory = applicationContextClazz.getConstructor(String.class).newInstance(configLocation);
Method startMethod = applicationContextClazz.getMethod("start");
startMethod.invoke(flowerFactory);
logger.info("spring初始化完成");
}
|
#vulnerable code
@Override
public void doStartup(String configLocation) {
ClassPathXmlApplicationContext applicationContext = null;
try {
applicationContext = new ClassPathXmlApplicationContext(configLocation);
applicationContext.start();
} catch (Exception e) {
if (applicationContext != null) {
applicationContext.close();
}
logger.error("", e);
}
logger.info("spring初始化完成");
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static List<Pair<String, String>> readFlow(String path) throws IOException {
InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path),Constant.ENCODING_UTF_8);
BufferedReader br = new BufferedReader(fr);
String line;
List<Pair<String, String>> flow = new ArrayList<>();
while ((line = br.readLine()) != null) {
String sl = line.trim();
if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) {
continue;
}
String[] connection = sl.split("->");
if (connection == null || connection.length != 2) {
close(br, fr);
throw new RuntimeException("Illegal flow config:" + path);
} else {
flow.add(new Pair<String, String>(connection[0].trim(), connection[1].trim()));
}
}
close(br, fr);
return flow;
}
|
#vulnerable code
public static List<Pair<String, String>> readFlow(String path) throws IOException {
InputStreamReader fr = new InputStreamReader(FileUtil.class.getResourceAsStream(path));
BufferedReader br = new BufferedReader(fr);
String line = "";
List<Pair<String, String>> flow = new ArrayList<>();
while ((line = br.readLine()) != null) {
String sl = line.trim();
if ((sl.startsWith("//")) || sl.startsWith("#") || sl.equals("")) {
continue;
}
String[] connection = sl.split("->");
if (connection == null || connection.length != 2) {
close(br, fr);
throw new RuntimeException("Illegal flow config:" + path);
} else {
flow.add(new Pair<String, String>(connection[0].trim(), connection[1].trim()));
}
}
close(br, fr);
return flow;
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
FunctionTypeBuilder(String fnName, AbstractCompiler compiler,
Node errorRoot, String sourceName, Scope scope) {
Preconditions.checkNotNull(errorRoot);
this.fnName = fnName == null ? "" : fnName;
this.codingConvention = compiler.getCodingConvention();
this.typeRegistry = compiler.getTypeRegistry();
this.errorRoot = errorRoot;
this.sourceName = sourceName;
this.compiler = compiler;
this.scope = scope;
}
|
#vulnerable code
FunctionTypeBuilder inferThisType(JSDocInfo info,
@Nullable Node owner) {
ObjectType maybeThisType = null;
if (info != null && info.hasThisType()) {
maybeThisType = ObjectType.cast(
info.getThisType().evaluate(scope, typeRegistry));
}
if (maybeThisType != null) {
thisType = maybeThisType;
thisType.setValidator(new ThisTypeValidator());
} else if (owner != null &&
(info == null || !info.hasType())) {
// If the function is of the form:
// x.prototype.y = function() {}
// then we can assume "x" is the @this type. On the other hand,
// if it's of the form:
// /** @type {Function} */ x.prototype.y;
// then we should not give it a @this type.
String ownerTypeName = owner.getQualifiedName();
ObjectType ownerType = ObjectType.cast(
typeRegistry.getForgivingType(
scope, ownerTypeName, sourceName,
owner.getLineno(), owner.getCharno()));
if (ownerType != null) {
thisType = ownerType;
}
}
return this;
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private EnvTypePair analyzeLooseCallNodeBwd(
Node callNode, TypeEnv outEnv, JSType retType) {
Preconditions.checkArgument(callNode.isCall());
Preconditions.checkNotNull(retType);
Node callee = callNode.getFirstChild();
TypeEnv tmpEnv = outEnv;
FunctionTypeBuilder builder = new FunctionTypeBuilder();
for (int i = callNode.getChildCount() - 2; i >= 0; i--) {
Node arg = callNode.getChildAtIndex(i + 1);
tmpEnv = analyzeExprBwd(arg, tmpEnv).env;
// Wait until FWD to get more precise argument types.
builder.addReqFormal(JSType.BOTTOM);
}
JSType looseRetType = retType.isUnknown() ? JSType.BOTTOM : retType;
JSType looseFunctionType =
builder.addRetType(looseRetType).addLoose().buildType();
println("loose function type is ", looseFunctionType);
EnvTypePair calleePair = analyzeExprBwd(callee, tmpEnv, looseFunctionType);
return new EnvTypePair(calleePair.env, retType);
}
|
#vulnerable code
private EnvTypePair analyzeLooseCallNodeBwd(
Node callNode, TypeEnv outEnv, JSType retType) {
Preconditions.checkArgument(callNode.isCall());
Preconditions.checkNotNull(retType);
Node callee = callNode.getFirstChild();
TypeEnv tmpEnv = outEnv;
FunctionTypeBuilder builder = new FunctionTypeBuilder();
for (int i = callNode.getChildCount() - 2; i >= 0; i--) {
Node arg = callNode.getChildAtIndex(i + 1);
tmpEnv = analyzeExprBwd(arg, tmpEnv).env;
// Wait until FWD to get more precise argument types.
builder.addReqFormal(JSType.BOTTOM);
}
JSType looseRetType = retType.isUnknown() ? JSType.BOTTOM : retType;
JSType looseFunctionType =
builder.addRetType(looseRetType).addLoose().buildType();
looseFunctionType.getFunType().checkValid();
println("loose function type is ", looseFunctionType);
EnvTypePair calleePair = analyzeExprBwd(callee, tmpEnv, looseFunctionType);
return new EnvTypePair(calleePair.env, retType);
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<JSSourceFile> getDefaultExterns() {
try {
return CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
}
|
#vulnerable code
private List<JSSourceFile> getDefaultExterns() {
try {
InputStream input = Compiler.class.getResourceAsStream(
"/externs.zip");
ZipInputStream zip = new ZipInputStream(input);
List<JSSourceFile> externs = Lists.newLinkedList();
for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) {
LimitInputStream entryStream =
new LimitInputStream(zip, entry.getSize());
externs.add(
JSSourceFile.fromInputStream(entry.getName(), entryStream));
}
return externs;
} catch (IOException e) {
throw new BuildException(e);
}
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node tryOptimizeSwitch(Node n) {
Preconditions.checkState(n.getType() == Token.SWITCH);
Node defaultCase = tryOptimizeDefaultCase(n);
// Removing cases when there exists a default case is not safe.
if (defaultCase == null) {
Node next = null;
Node prev = null;
// The first child is the switch conditions skip it.
for (Node c = n.getFirstChild().getNext(); c != null; c = next) {
next = c.getNext();
if (!mayHaveSideEffects(c.getFirstChild()) && isUselessCase(c, prev)) {
removeCase(n, c);
} else {
prev = c;
}
}
}
// Remove the switch if there are no remaining cases.
if (n.hasOneChild()) {
Node condition = n.removeFirstChild();
Node parent = n.getParent();
Node replacement = new Node(Token.EXPR_RESULT, condition)
.copyInformationFrom(n);
parent.replaceChild(n, replacement);
reportCodeChange();
return replacement;
}
return null;
}
|
#vulnerable code
private Node tryOptimizeSwitch(Node n) {
Preconditions.checkState(n.getType() == Token.SWITCH);
Node defaultCase = findDefaultCase(n);
if (defaultCase != null && isUselessCase(defaultCase)) {
NodeUtil.redeclareVarsInsideBranch(defaultCase);
n.removeChild(defaultCase);
reportCodeChange();
defaultCase = null;
}
// Removing cases when there exists a default case is not safe.
// TODO(johnlenz): Allow this if the same code is executed.
if (defaultCase == null) {
Node next = null;
// The first child is the switch conditions skip it.
for (Node c = n.getFirstChild().getNext(); c != null; c = next) {
next = c.getNext();
if (!mayHaveSideEffects(c.getFirstChild()) && isUselessCase(c)) {
NodeUtil.redeclareVarsInsideBranch(c);
n.removeChild(c);
reportCodeChange();
}
}
}
if (n.hasOneChild()) {
Node condition = n.removeFirstChild();
Node parent = n.getParent();
Node replacement = new Node(Token.EXPR_RESULT, condition)
.copyInformationFrom(n);
parent.replaceChild(n, replacement);
reportCodeChange();
return replacement;
}
return null;
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void writeResult(String source) {
if (this.outputFile.getParentFile().mkdirs()) {
log("Created missing parent directory " +
this.outputFile.getParentFile(), Project.MSG_DEBUG);
}
try {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(this.outputFile), outputEncoding);
out.append(source);
out.flush();
out.close();
} catch (IOException e) {
throw new BuildException(e);
}
log("Compiled javascript written to " + this.outputFile.getAbsolutePath(),
Project.MSG_DEBUG);
}
|
#vulnerable code
private void writeResult(String source) {
if (this.outputFile.getParentFile().mkdirs()) {
log("Created missing parent directory " +
this.outputFile.getParentFile(), Project.MSG_DEBUG);
}
try {
FileWriter out = new FileWriter(this.outputFile);
out.append(source);
out.close();
} catch (IOException e) {
throw new BuildException(e);
}
log("Compiled javascript written to " + this.outputFile.getAbsolutePath(),
Project.MSG_DEBUG);
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Writer fileNameToOutputWriter(String fileName) throws IOException {
if (fileName == null) {
return null;
}
if (testMode) {
return new StringWriter();
}
return streamToOutputWriter(filenameToOutputStream(fileName));
}
|
#vulnerable code
private Writer fileNameToOutputWriter(String fileName) throws IOException {
if (fileName == null) {
return null;
}
if (testMode) {
return new StringWriter();
}
return streamToOutputWriter(new FileOutputStream(fileName));
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) {
return getDependenciesOf(roots, true);
}
|
#vulnerable code
public List<INPUT> getSortedDependenciesOf(List<INPUT> roots) {
Preconditions.checkArgument(inputs.containsAll(roots));
Set<INPUT> included = Sets.newHashSet();
Deque<INPUT> worklist = new ArrayDeque<INPUT>(roots);
while (!worklist.isEmpty()) {
INPUT current = worklist.pop();
if (included.add(current)) {
for (String req : current.getRequires()) {
INPUT dep = provideMap.get(req);
if (dep != null) {
worklist.add(dep);
}
}
}
}
ImmutableList.Builder<INPUT> builder = ImmutableList.builder();
for (INPUT current : sortedList) {
if (included.contains(current)) {
builder.add(current);
}
}
return builder.build();
}
#location 1
#vulnerability type CHECKERS_IMMUTABLE_CAST
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
return true;
}
|
#vulnerable code
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (n.isScript()) {
this.inExterns = n.getStaticSourceFile().isExtern();
}
return true;
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Set<String> getOwnPropertyNames() {
return getPropertyMap().getOwnPropertyNames();
}
|
#vulnerable code
public Set<String> getOwnPropertyNames() {
return ImmutableSet.of();
}
#location 1
#vulnerability type CHECKERS_IMMUTABLE_CAST
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void enterScope(NodeTraversal t) {
scopeNeedsInit = true;
}
|
#vulnerable code
@Override
public void enterScope(NodeTraversal t) {
new GraphReachability<Node, ControlFlowGraph.Branch>(
t.getControlFlowGraph(), new ReachablePredicate()).compute(
t.getControlFlowGraph().getEntry().getValue());
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void initEdgeEnvsFwd() {
// TODO(user): Revisit what we throw away after the bwd analysis
DiGraphNode<Node, ControlFlowGraph.Branch> entry = cfg.getEntry();
DiGraphEdge<Node, ControlFlowGraph.Branch> entryOutEdge =
cfg.getOutEdges(entry.getValue()).get(0);
TypeEnv entryEnv = envs.get(entryOutEdge);
initEdgeEnvs(new TypeEnv());
// For function scopes, add the formal parameters and the free variables
// from outer scopes to the environment.
if (currentScope.isFunction()) {
Set<String> formalsAndOuters = currentScope.getOuterVars();
formalsAndOuters.addAll(currentScope.getFormals());
if (currentScope.hasThis()) {
formalsAndOuters.add("this");
}
for (String name : formalsAndOuters) {
JSType declType = currentScope.getDeclaredTypeOf(name);
JSType initType;
if (declType == null) {
initType = envGetType(entryEnv, name);
} else if (declType.getFunTypeIfSingletonObj() != null &&
declType.getFunTypeIfSingletonObj().isConstructor()) {
initType =
declType.getFunTypeIfSingletonObj().createConstructorObject();
} else {
initType = declType;
}
entryEnv = envPutType(entryEnv, name, initType.withLocation(name));
}
entryEnv = envPutType(entryEnv, RETVAL_ID, JSType.UNDEFINED);
}
// For all scopes, add local variables and (local) function definitions
// to the environment.
for (String local : currentScope.getLocals()) {
entryEnv = envPutType(entryEnv, local, JSType.UNDEFINED);
}
for (String fnName : currentScope.getLocalFunDefs()) {
JSType summaryType = summaries.get(currentScope.getScope(fnName));
FunctionType fnType = summaryType.getFunType();
if (fnType.isConstructor()) {
summaryType = fnType.createConstructorObject();
} else {
summaryType = summaryType.withProperty(
new QualifiedName("prototype"), JSType.TOP_OBJECT);
}
entryEnv = envPutType(entryEnv, fnName, summaryType);
}
println("Keeping env: ", entryEnv);
envs.put(entryOutEdge, entryEnv);
}
|
#vulnerable code
private void initEdgeEnvsFwd() {
// TODO(user): Revisit what we throw away after the bwd analysis
DiGraphNode<Node, ControlFlowGraph.Branch> entry = cfg.getEntry();
DiGraphEdge<Node, ControlFlowGraph.Branch> entryOutEdge =
cfg.getOutEdges(entry.getValue()).get(0);
TypeEnv entryEnv = envs.get(entryOutEdge);
initEdgeEnvs(new TypeEnv());
// For function scopes, add the formal parameters and the free variables
// from outer scopes to the environment.
if (currentScope.isFunction()) {
Set<String> formalsAndOuters = currentScope.getOuterVars();
formalsAndOuters.addAll(currentScope.getFormals());
if (currentScope.hasThis()) {
formalsAndOuters.add("this");
}
for (String name : formalsAndOuters) {
JSType declType = currentScope.getDeclaredTypeOf(name);
JSType initType;
if (declType == null) {
initType = envGetType(entryEnv, name);
} else if (declType.getFunTypeIfSingletonObj() != null &&
declType.getFunTypeIfSingletonObj().isConstructor()) {
initType =
declType.getFunTypeIfSingletonObj().createConstructorObject();
} else {
initType = declType;
}
entryEnv = envPutType(entryEnv, name, initType.withLocation(name));
}
entryEnv = envPutType(entryEnv, RETVAL_ID, JSType.UNDEFINED);
}
// For all scopes, add local variables and (local) function definitions
// to the environment.
for (String local : currentScope.getLocals()) {
entryEnv = envPutType(entryEnv, local, JSType.UNDEFINED);
}
for (String fnName : currentScope.getLocalFunDefs()) {
JSType summaryType = summaries.get(currentScope.getScope(fnName));
FunctionType fnType = summaryType.getFunType();
if (fnType.isConstructor()) {
summaryType = fnType.createConstructorObject();
} else {
summaryType = summaryType.withProperty("prototype", JSType.TOP_OBJECT);
}
entryEnv = envPutType(entryEnv, fnName, summaryType);
}
println("Keeping env: ", entryEnv);
envs.put(entryOutEdge, entryEnv);
}
#location 29
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void removeUnreferencedVars() {
CodingConvention convention = codingConvention;
for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
Var var = it.next();
// Remove calls to inheritance-defining functions where the unreferenced
// class is the subclass.
for (Node exprCallNode : inheritsCalls.get(var)) {
NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
compiler.reportCodeChange();
}
// Regardless of what happens to the original declaration,
// we need to remove all assigns, because they may contain references
// to other unreferenced variables.
removeAllAssigns(var);
compiler.addToDebugLog("Unreferenced var: " + var.name);
Node nameNode = var.nameNode;
Node toRemove = nameNode.getParent();
Node parent = toRemove.getParent();
Preconditions.checkState(
toRemove.getType() == Token.VAR ||
toRemove.getType() == Token.FUNCTION ||
toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION,
"We should only declare vars and functions and function args");
if (toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION) {
// Don't remove function arguments here. That's a special case
// that's taken care of in removeUnreferencedFunctionArgs.
} else if (NodeUtil.isFunctionExpression(toRemove)) {
if (!preserveFunctionExpressionNames) {
toRemove.getFirstChild().setString("");
compiler.reportCodeChange();
}
// Don't remove bleeding functions.
} else if (parent != null &&
parent.getType() == Token.FOR &&
parent.getChildCount() < 4) {
// foreach iterations have 3 children. Leave them alone.
} else if (toRemove.getType() == Token.VAR &&
nameNode.hasChildren() &&
NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
// If this is a single var declaration, we can at least remove the
// declaration itself and just leave the value, e.g.,
// var a = foo(); => foo();
if (toRemove.getChildCount() == 1) {
parent.replaceChild(toRemove,
new Node(Token.EXPR_RESULT, nameNode.removeFirstChild()));
compiler.reportCodeChange();
}
} else if (toRemove.getType() == Token.VAR &&
toRemove.getChildCount() > 1) {
// For var declarations with multiple names (i.e. var a, b, c),
// only remove the unreferenced name
toRemove.removeChild(nameNode);
compiler.reportCodeChange();
} else if (parent != null) {
NodeUtil.removeChild(parent, toRemove);
compiler.reportCodeChange();
}
}
}
|
#vulnerable code
private void removeUnreferencedVars() {
CodingConvention convention = compiler.getCodingConvention();
for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
Var var = it.next();
// Regardless of what happens to the original declaration,
// we need to remove all assigns, because they may contain references
// to other unreferenced variables.
removeAllAssigns(var);
compiler.addToDebugLog("Unreferenced var: " + var.name);
Node nameNode = var.nameNode;
Node toRemove = nameNode.getParent();
Node parent = toRemove.getParent();
Preconditions.checkState(
toRemove.getType() == Token.VAR ||
toRemove.getType() == Token.FUNCTION ||
toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION,
"We should only declare vars and functions and function args");
if (toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION) {
// Don't remove function arguments here. That's a special case
// that's taken care of in removeUnreferencedFunctionArgs.
} else if (NodeUtil.isFunctionExpression(toRemove)) {
if (!preserveFunctionExpressionNames) {
toRemove.getFirstChild().setString("");
compiler.reportCodeChange();
}
// Don't remove bleeding functions.
} else if (parent != null &&
parent.getType() == Token.FOR &&
parent.getChildCount() < 4) {
// foreach iterations have 3 children. Leave them alone.
} else if (toRemove.getType() == Token.VAR &&
nameNode.hasChildren() &&
NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
// If this is a single var declaration, we can at least remove the
// declaration itself and just leave the value, e.g.,
// var a = foo(); => foo();
if (toRemove.getChildCount() == 1) {
parent.replaceChild(toRemove,
new Node(Token.EXPR_RESULT, nameNode.removeFirstChild()));
compiler.reportCodeChange();
}
} else if (toRemove.getType() == Token.VAR &&
toRemove.getChildCount() > 1) {
// For var declarations with multiple names (i.e. var a, b, c),
// only remove the unreferenced name
toRemove.removeChild(nameNode);
compiler.reportCodeChange();
} else if (parent != null) {
NodeUtil.removeChild(parent, toRemove);
compiler.reportCodeChange();
}
}
}
#location 45
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node aliasAndInlineArguments(
Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
Set<String> namesToAlias) {
if (namesToAlias == null || namesToAlias.isEmpty()) {
// There are no names to alias, just inline the arguments directly.
Node result = FunctionArgumentInjector.inject(
fnTemplateRoot, null, argMap);
Preconditions.checkState(result == fnTemplateRoot);
return result;
} else {
// Create local alias of names that can not be safely
// used directly.
// An arg map that will be updated to contain the
// safe aliases.
Map<String, Node> newArgMap = Maps.newHashMap(argMap);
// Declare the alias in the same order as they
// are declared.
List<Node> newVars = Lists.newLinkedList();
// NOTE: argMap is a linked map so we get the parameters in the
// order that they were declared.
for (Entry<String, Node> entry : argMap.entrySet()) {
String name = entry.getKey();
if (namesToAlias.contains(name)) {
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(name, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.remove(name);
}
}
// Inline the arguments.
Node result = FunctionArgumentInjector.inject(
fnTemplateRoot, null, newArgMap);
Preconditions.checkState(result == fnTemplateRoot);
// Now that the names have been replaced, add the new aliases for
// the old names.
for (Node n : newVars) {
fnTemplateRoot.addChildToFront(n);
}
return result;
}
}
|
#vulnerable code
private Node aliasAndInlineArguments(
Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
Set<String> namesToAlias) {
if (namesToAlias == null || namesToAlias.isEmpty()) {
// There are no names to alias, just inline the arguments directly.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, argMap);
Preconditions.checkState(result == fnTemplateRoot);
return result;
} else {
// Create local alias of names that can not be safely
// used directly.
// An arg map that will be updated to contain the
// safe aliases.
Map<String, Node> newArgMap = Maps.newHashMap(argMap);
// Declare the alias in the same order as they
// are declared.
List<Node> newVars = Lists.newLinkedList();
// NOTE: argMap is a linked map so we get the parameters in the
// order that they were declared.
for (Entry<String, Node> entry : argMap.entrySet()) {
String name = entry.getKey();
if (namesToAlias.contains(name)) {
if (name.equals(THIS_MARKER)) {
boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot);
// Update "this", this is only necessary if "this" is referenced
// and the value of "this" is not Token.THIS, or the value of "this"
// has side effects.
Node value = entry.getValue();
if (value.getType() != Token.THIS
&& (referencesThis
|| NodeUtil.mayHaveSideEffects(value, compiler))) {
String newName = getUniqueThisName();
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(newName, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.put(THIS_MARKER,
Node.newString(Token.NAME, newName)
.copyInformationFromForTree(newValue));
}
} else {
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(name, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.remove(name);
}
}
}
// Inline the arguments.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, newArgMap);
Preconditions.checkState(result == fnTemplateRoot);
// Now that the names have been replaced, add the new aliases for
// the old names.
for (Node n : newVars) {
fnTemplateRoot.addChildToFront(n);
}
return result;
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void outputTracerReport() {
JvmMetrics.maybeWriteJvmMetrics(this.err, "verbose:pretty:all");
OutputStreamWriter output = new OutputStreamWriter(this.err);
try {
int runtime = 0;
int runs = 0;
int changes = 0;
int diff = 0;
int gzDiff = 0;
// header
output.write("Summary:\n");
output.write("pass,runtime,runs,chancingRuns,reduction,gzReduction\n");
Map<String, Stats> runtimeMap = compiler.tracker.getStats();
for (Entry<String, Stats> entry : runtimeMap.entrySet()) {
String key = entry.getKey();
Stats stats = entry.getValue();
output.write(key);
output.write(",");
output.write(String.valueOf(stats.runtime));
runtime += stats.runtime;
output.write(",");
output.write(String.valueOf(stats.runs));
runs += stats.runs;
output.write(",");
output.write(String.valueOf(stats.changes));
changes += stats.changes;
output.write(",");
output.write(String.valueOf(stats.diff));
diff += stats.diff;
output.write(",");
output.write(String.valueOf(stats.gzDiff));
gzDiff += stats.gzDiff;
output.write("\n");
}
output.write("TOTAL");
output.write(",");
output.write(String.valueOf(runtime));
output.write(",");
output.write(String.valueOf(runs));
output.write(",");
output.write(String.valueOf(changes));
output.write(",");
output.write(String.valueOf(diff));
output.write(",");
output.write(String.valueOf(gzDiff));
output.write("\n");
output.write("\n");
output.write("Log:\n");
output.write(
"pass,runtime,runs,chancingRuns,reduction,gzReduction,size,gzSize\n");
List<Stats> runtimeLog = compiler.tracker.getLog();
for (Stats stats : runtimeLog) {
output.write(stats.pass);
output.write(",");
output.write(String.valueOf(stats.runtime));
output.write(",");
output.write(String.valueOf(stats.runs));
output.write(",");
output.write(String.valueOf(stats.changes));
output.write(",");
output.write(String.valueOf(stats.diff));
output.write(",");
output.write(String.valueOf(stats.gzDiff));
output.write(",");
output.write(String.valueOf(stats.size));
output.write(",");
output.write(String.valueOf(stats.gzSize));
output.write("\n");
}
output.write("\n");
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
|
#vulnerable code
private void outputTracerReport() {
OutputStreamWriter output = new OutputStreamWriter(this.err);
try {
int runtime = 0;
int runs = 0;
int changes = 0;
int diff = 0;
int gzDiff = 0;
// header
output.write("Summary:\n");
output.write("pass,runtime,runs,chancingRuns,reduction,gzReduction\n");
Map<String, Stats> runtimeMap = compiler.tracker.getStats();
for (Entry<String, Stats> entry : runtimeMap.entrySet()) {
String key = entry.getKey();
Stats stats = entry.getValue();
output.write(key);
output.write(",");
output.write(String.valueOf(stats.runtime));
runtime += stats.runtime;
output.write(",");
output.write(String.valueOf(stats.runs));
runs += stats.runs;
output.write(",");
output.write(String.valueOf(stats.changes));
changes += stats.changes;
output.write(",");
output.write(String.valueOf(stats.diff));
diff += stats.diff;
output.write(",");
output.write(String.valueOf(stats.gzDiff));
gzDiff += stats.gzDiff;
output.write("\n");
}
output.write("TOTAL");
output.write(",");
output.write(String.valueOf(runtime));
output.write(",");
output.write(String.valueOf(runs));
output.write(",");
output.write(String.valueOf(changes));
output.write(",");
output.write(String.valueOf(diff));
output.write(",");
output.write(String.valueOf(gzDiff));
output.write("\n");
output.write("\n");
output.write("Log:\n");
output.write(
"pass,runtime,runs,chancingRuns,reduction,gzReduction,size,gzSize\n");
List<Stats> runtimeLog = compiler.tracker.getLog();
for (Stats stats : runtimeLog) {
output.write(stats.pass);
output.write(",");
output.write(String.valueOf(stats.runtime));
output.write(",");
output.write(String.valueOf(stats.runs));
output.write(",");
output.write(String.valueOf(stats.changes));
output.write(",");
output.write(String.valueOf(stats.diff));
output.write(",");
output.write(String.valueOf(stats.gzDiff));
output.write(",");
output.write(String.valueOf(stats.size));
output.write(",");
output.write(String.valueOf(stats.gzSize));
output.write("\n");
}
output.write("\n");
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 74
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void escapeParameters(MustDef output) {
for (Iterator<Var> i = jsScope.getVars(); i.hasNext();) {
Var v = i.next();
if (isParameter(v)) {
// Assume we no longer know where the parameter comes from
// anymore.
output.reachingDef.put(v, null);
}
}
// Also, assume we no longer know anything that depends on a parameter.
for (Entry<Var, Definition> pair: output.reachingDef.entrySet()) {
Definition value = pair.getValue();
if (value == null) {
continue;
}
for (Var dep : value.depends) {
if (isParameter(dep)) {
output.reachingDef.put(pair.getKey(), null);
}
}
}
}
|
#vulnerable code
private void escapeParameters(MustDef output) {
for (Iterator<Var> i = jsScope.getVars(); i.hasNext();) {
Var v = i.next();
if (v.getParentNode().getType() == Token.LP) {
// Assume we no longer know where the parameter comes from
// anymore.
output.reachingDef.put(v, null);
}
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void enterScope(NodeTraversal t) {}
|
#vulnerable code
@Override
public void enterScope(NodeTraversal t) {
Scope scope = t.getScope();
// Computes the control flow graph.
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, scope.getRootNode());
cfgStack.push(curCfg);
curCfg = cfa.getCfg();
new GraphReachability<Node, ControlFlowGraph.Branch>(curCfg)
.compute(curCfg.getEntry().getValue());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private String getFunctionAnnotation(Node fnNode) {
Preconditions.checkState(fnNode.getType() == Token.FUNCTION);
StringBuilder sb = new StringBuilder("/**\n");
JSType type = fnNode.getJSType();
if (type == null || type.isUnknownType()) {
return "";
}
FunctionType funType = (FunctionType) fnNode.getJSType();
// We need to use the child nodes of the function as the nodes for the
// parameters of the function type do not have the real parameter names.
// FUNCTION
// NAME
// LP
// NAME param1
// NAME param2
if (fnNode != null) {
Node paramNode = NodeUtil.getFunctionParameters(fnNode).getFirstChild();
// Param types
for (Node n : funType.getParameters()) {
// Bail out if the paramNode is not there.
if (paramNode == null) {
break;
}
sb.append(" * @param {" + getParameterNodeJSDocType(n) + "} ");
sb.append(paramNode.getString());
sb.append("\n");
paramNode = paramNode.getNext();
}
}
// Return type
JSType retType = funType.getReturnType();
if (retType != null && !retType.isUnknownType() && !retType.isEmptyType()) {
sb.append(" * @return {" + retType + "}\n");
}
// Constructor/interface
if (funType.isConstructor() || funType.isInterface()) {
FunctionType superConstructor = funType.getSuperClassConstructor();
if (superConstructor != null) {
ObjectType superInstance =
funType.getSuperClassConstructor().getInstanceType();
if (!superInstance.toString().equals("Object")) {
sb.append(" * @extends {" + superInstance + "}\n");
}
}
if (funType.isInterface()) {
for (ObjectType interfaceType : funType.getExtendedInterfaces()) {
sb.append(" * @extends {" + interfaceType + "}\n");
}
}
// Avoid duplicates, add implemented type to a set first
Set<String> interfaces = Sets.newTreeSet();
for (ObjectType interfaze : funType.getImplementedInterfaces()) {
interfaces.add(interfaze.toString());
}
for (String interfaze : interfaces) {
sb.append(" * @implements {" + interfaze + "}\n");
}
if (funType.isConstructor()) {
sb.append(" * @constructor\n");
} else if (funType.isInterface()) {
sb.append(" * @interface\n");
}
}
if (fnNode != null && fnNode.getBooleanProp(Node.IS_DISPATCHER)) {
sb.append(" * @javadispatch\n");
}
sb.append(" */\n");
return sb.toString();
}
|
#vulnerable code
private String getFunctionAnnotation(Node fnNode) {
Preconditions.checkState(fnNode.getType() == Token.FUNCTION);
StringBuilder sb = new StringBuilder("/**\n");
JSType type = fnNode.getJSType();
if (type == null || type.isUnknownType()) {
return "";
}
FunctionType funType = type.toMaybeFunctionType();
// We need to use the child nodes of the function as the nodes for the
// parameters of the function type do not have the real parameter names.
// FUNCTION
// NAME
// LP
// NAME param1
// NAME param2
if (fnNode != null) {
Node paramNode = NodeUtil.getFunctionParameters(fnNode).getFirstChild();
// Param types
for (Node n : funType.getParameters()) {
// Bail out if the paramNode is not there.
if (paramNode == null) {
break;
}
sb.append(" * @param {" + getParameterNodeJSDocType(n) + "} ");
sb.append(paramNode.getString());
sb.append("\n");
paramNode = paramNode.getNext();
}
}
// Return type
JSType retType = funType.getReturnType();
if (retType != null && !retType.isUnknownType() && !retType.isEmptyType()) {
sb.append(" * @return {" + retType + "}\n");
}
// Constructor/interface
if (funType.isConstructor() || funType.isInterface()) {
FunctionType superConstructor = funType.getSuperClassConstructor();
if (superConstructor != null) {
ObjectType superInstance =
funType.getSuperClassConstructor().getInstanceType();
if (!superInstance.toString().equals("Object")) {
sb.append(" * @extends {" + superInstance + "}\n");
}
}
if (funType.isInterface()) {
for (ObjectType interfaceType : funType.getExtendedInterfaces()) {
sb.append(" * @extends {" + interfaceType + "}\n");
}
}
// Avoid duplicates, add implemented type to a set first
Set<String> interfaces = Sets.newTreeSet();
for (ObjectType interfaze : funType.getImplementedInterfaces()) {
interfaces.add(interfaze.toString());
}
for (String interfaze : interfaces) {
sb.append(" * @implements {" + interfaze + "}\n");
}
if (funType.isConstructor()) {
sb.append(" * @constructor\n");
} else if (funType.isInterface()) {
sb.append(" * @interface\n");
}
}
if (fnNode != null && fnNode.getBooleanProp(Node.IS_DISPATCHER)) {
sb.append(" * @javadispatch\n");
}
sb.append(" */\n");
return sb.toString();
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
|
#vulnerable code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
null, safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
FunctionTypeBuilder(String fnName, AbstractCompiler compiler,
Node errorRoot, String sourceName, Scope scope) {
Preconditions.checkNotNull(errorRoot);
this.fnName = fnName == null ? "" : fnName;
this.codingConvention = compiler.getCodingConvention();
this.typeRegistry = compiler.getTypeRegistry();
this.errorRoot = errorRoot;
this.sourceName = sourceName;
this.compiler = compiler;
this.scope = scope;
}
|
#vulnerable code
FunctionTypeBuilder inferThisType(JSDocInfo info,
@Nullable Node owner) {
ObjectType maybeThisType = null;
if (info != null && info.hasThisType()) {
maybeThisType = ObjectType.cast(
info.getThisType().evaluate(scope, typeRegistry));
}
if (maybeThisType != null) {
// TODO(user): Doing an instanceof check here is too
// restrictive as (Date,Error) is, for instance, an object type
// even though its implementation is a UnionType. Would need to
// create interfaces JSType, ObjectType, FunctionType etc and have
// separate implementation instead of the class hierarchy, so that
// union types can also be object types, etc.
thisType = maybeThisType;
} else if (owner != null &&
(info == null || !info.hasType())) {
// If the function is of the form:
// x.prototype.y = function() {}
// then we can assume "x" is the @this type. On the other hand,
// if it's of the form:
// /** @type {Function} */ x.prototype.y;
// then we should not give it a @this type.
String ownerTypeName = owner.getQualifiedName();
ObjectType ownerType = ObjectType.cast(
typeRegistry.getType(
scope, ownerTypeName, sourceName,
owner.getLineno(), owner.getCharno()));
if (ownerType != null) {
thisType = ownerType;
}
}
return this;
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getType()) {
case Token.ASSIGN:
scope = traverseAssign(n, scope);
break;
case Token.NAME:
scope = traverseName(n, scope);
break;
case Token.GETPROP:
scope = traverseGetProp(n, scope);
break;
case Token.AND:
scope = traverseAnd(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.OR:
scope = traverseOr(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.HOOK:
scope = traverseHook(n, scope);
break;
case Token.OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case Token.CALL:
scope = traverseCall(n, scope);
break;
case Token.NEW:
scope = traverseNew(n, scope);
break;
case Token.ASSIGN_ADD:
case Token.ADD:
scope = traverseAdd(n, scope);
break;
case Token.POS:
case Token.NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case Token.THIS:
n.setJSType(scope.getTypeOfThis());
break;
case Token.ASSIGN_LSH:
case Token.ASSIGN_RSH:
case Token.LSH:
case Token.RSH:
case Token.ASSIGN_URSH:
case Token.URSH:
case Token.ASSIGN_DIV:
case Token.ASSIGN_MOD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_MUL:
case Token.ASSIGN_SUB:
case Token.DIV:
case Token.MOD:
case Token.BITAND:
case Token.BITXOR:
case Token.BITOR:
case Token.MUL:
case Token.SUB:
case Token.DEC:
case Token.INC:
case Token.BITNOT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.PARAM_LIST:
scope = traverse(n.getFirstChild(), scope);
n.setJSType(getJSType(n.getFirstChild()));
break;
case Token.COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case Token.TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case Token.DELPROP:
case Token.LT:
case Token.LE:
case Token.GT:
case Token.GE:
case Token.NOT:
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.INSTANCEOF:
case Token.IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case Token.GETELEM:
scope = traverseGetElem(n, scope);
break;
case Token.EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
ensurePropertyDeclared(n.getFirstChild());
}
break;
case Token.SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case Token.RETURN:
scope = traverseReturn(n, scope);
break;
case Token.VAR:
case Token.THROW:
scope = traverseChildren(n, scope);
break;
case Token.CATCH:
scope = traverseCatch(n, scope);
break;
case Token.CAST:
scope = traverseChildren(n, scope);
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasType()) {
n.setJSType(info.getType().evaluate(syntacticScope, registry));
}
break;
}
return scope;
}
|
#vulnerable code
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getType()) {
case Token.ASSIGN:
scope = traverseAssign(n, scope);
break;
case Token.NAME:
scope = traverseName(n, scope);
break;
case Token.GETPROP:
scope = traverseGetProp(n, scope);
break;
case Token.AND:
scope = traverseAnd(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.OR:
scope = traverseOr(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.HOOK:
scope = traverseHook(n, scope);
break;
case Token.OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case Token.CALL:
scope = traverseCall(n, scope);
break;
case Token.NEW:
scope = traverseNew(n, scope);
break;
case Token.ASSIGN_ADD:
case Token.ADD:
scope = traverseAdd(n, scope);
break;
case Token.POS:
case Token.NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case Token.THIS:
n.setJSType(scope.getTypeOfThis());
break;
case Token.ASSIGN_LSH:
case Token.ASSIGN_RSH:
case Token.LSH:
case Token.RSH:
case Token.ASSIGN_URSH:
case Token.URSH:
case Token.ASSIGN_DIV:
case Token.ASSIGN_MOD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_MUL:
case Token.ASSIGN_SUB:
case Token.DIV:
case Token.MOD:
case Token.BITAND:
case Token.BITXOR:
case Token.BITOR:
case Token.MUL:
case Token.SUB:
case Token.DEC:
case Token.INC:
case Token.BITNOT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.PARAM_LIST:
scope = traverse(n.getFirstChild(), scope);
n.setJSType(getJSType(n.getFirstChild()));
break;
case Token.COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case Token.TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case Token.DELPROP:
case Token.LT:
case Token.LE:
case Token.GT:
case Token.GE:
case Token.NOT:
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.INSTANCEOF:
case Token.IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case Token.GETELEM:
scope = traverseGetElem(n, scope);
break;
case Token.EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
ensurePropertyDeclared(n.getFirstChild());
}
break;
case Token.SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case Token.RETURN:
scope = traverseReturn(n, scope);
break;
case Token.VAR:
case Token.THROW:
scope = traverseChildren(n, scope);
break;
case Token.CATCH:
scope = traverseCatch(n, scope);
break;
case Token.CAST:
scope = traverseChildren(n, scope);
break;
}
// TODO(johnlenz): remove this after the CAST node change has shaken out.
if (!n.isFunction()) {
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasType()) {
JSType castType = info.getType().evaluate(syntacticScope, registry);
// A stubbed type declaration on a qualified name should take
// effect for all subsequent accesses of that name,
// so treat it the same as an assign to that name.
if (n.isQualifiedName() &&
n.getParent().isExprResult()) {
updateScopeForTypeChange(scope, n, n.getJSType(), castType);
}
n.setJSType(castType);
}
}
return scope;
}
#location 155
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
null, safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
|
#vulnerable code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph(
NodeTraversal t, ControlFlowGraph<Node> cfg, Set<Var> escaped) {
UndiGraph<Var, Void> interferenceGraph =
LinkedUndirectedGraph.create();
// For all variables V not in unsafeCrossRange,
// LiveRangeChecker(V, X) and LiveRangeChecker(Y, V) will never add a edge
// to the interferenceGraph. In other words, we don't need to use
// LiveRangeChecker on variable pair (A, B) if both A and B are not
// in the unsafeCrossRangeSet. See PrescreenCrossLiveRange for details.
Set<Var> unsafeCrossRangeSet = Sets.newHashSet();
Scope scope = t.getScope();
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue;
}
for (Iterator<Var> i = scope.getVars(); i.hasNext();) {
final Var v = i.next();
if (!unsafeCrossRangeSet.contains(v)) {
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
PrescreenCrossLiveRange check =
new PrescreenCrossLiveRange(v, state.getOut());
NodeTraversal.traverse(compiler, cfgNode.getValue(), check);
if (!check.isSafe()) {
unsafeCrossRangeSet.add(v);
}
}
}
}
// First create a node for each non-escaped variable.
for (Iterator<Var> i = scope.getVars(); i.hasNext();) {
Var v = i.next();
if (!escaped.contains(v)) {
// TODO(user): In theory, we CAN coalesce function names just like
// any variables. Our Liveness analysis captures this just like it as
// described in the specification. However, we saw some zipped and
// and unzipped size increase after this. We are not totally sure why
// that is but, for now, we will respect the dead functions and not play
// around with it.
if (!NodeUtil.isFunction(v.getParentNode())) {
interferenceGraph.createNode(v);
}
}
}
// Go through each variable and try to connect them.
for (Iterator<Var> i1 = scope.getVars(); i1.hasNext();) {
Var v1 = i1.next();
NEXT_VAR_PAIR:
for (Iterator<Var> i2 = scope.getVars(); i2.hasNext();) {
Var v2 = i2.next();
// Skip duplicate pairs.
if (v1.index >= v2.index) {
continue;
}
if (!interferenceGraph.hasNode(v1) ||
!interferenceGraph.hasNode(v2)) {
// Skip nodes that were not added. They are globals and escaped
// locals. Also avoid merging a variable with itself.
continue NEXT_VAR_PAIR;
}
if (v1.getParentNode().getType() == Token.LP &&
v2.getParentNode().getType() == Token.LP) {
interferenceGraph.connectIfNotFound(v1, null, v2);
continue NEXT_VAR_PAIR;
}
// Go through every CFG node in the program and look at
// this variable pair. If they are both live at the same
// time, add an edge between them and continue to the next pair.
NEXT_CROSS_CFG_NODE:
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue NEXT_CROSS_CFG_NODE;
}
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
// Check the live states and add edge when possible.
if ((state.getIn().isLive(v1) && state.getIn().isLive(v2)) ||
(state.getOut().isLive(v1) && state.getOut().isLive(v2))) {
interferenceGraph.connectIfNotFound(v1, null, v2);
continue NEXT_VAR_PAIR;
}
}
// v1 and v2 might not have an edge between them! woohoo. there's
// one last sanity check that we have to do: we have to check
// if there's a collision *within* the cfg node.
if (!unsafeCrossRangeSet.contains(v1) &&
!unsafeCrossRangeSet.contains(v2)) {
continue NEXT_VAR_PAIR;
}
NEXT_INTRA_CFG_NODE:
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue NEXT_INTRA_CFG_NODE;
}
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
boolean v1OutLive = state.getOut().isLive(v1);
boolean v2OutLive = state.getOut().isLive(v2);
CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker(
new LiveRangeChecker(v1, v2OutLive ? null : v2),
new LiveRangeChecker(v2, v1OutLive ? null : v1));
NodeTraversal.traverse(
compiler,
cfgNode.getValue(),
checker);
if (checker.connectIfCrossed(interferenceGraph)) {
continue NEXT_VAR_PAIR;
}
}
}
}
return interferenceGraph;
}
|
#vulnerable code
private UndiGraph<Var, Void> computeVariableNamesInterferenceGraph(
NodeTraversal t, ControlFlowGraph<Node> cfg, Set<Var> escaped) {
UndiGraph<Var, Void> interferenceGraph =
LinkedUndirectedGraph.create();
Scope scope = t.getScope();
// First create a node for each non-escaped variable.
for (Iterator<Var> i = scope.getVars(); i.hasNext();) {
Var v = i.next();
if (!escaped.contains(v)) {
// TODO(user): In theory, we CAN coalesce function names just like
// any variables. Our Liveness analysis captures this just like it as
// described in the specification. However, we saw some zipped and
// and unzipped size increase after this. We are not totally sure why
// that is but, for now, we will respect the dead functions and not play
// around with it.
if (!NodeUtil.isFunction(v.getParentNode())) {
interferenceGraph.createNode(v);
}
}
}
// Go through each variable and try to connect them.
for (Iterator<Var> i1 = scope.getVars(); i1.hasNext();) {
Var v1 = i1.next();
NEXT_VAR_PAIR:
for (Iterator<Var> i2 = scope.getVars(); i2.hasNext();) {
Var v2 = i2.next();
// Skip duplicate pairs.
if (v1.index >= v2.index) {
continue;
}
if (!interferenceGraph.hasNode(v1) ||
!interferenceGraph.hasNode(v2)) {
// Skip nodes that were not added. They are globals and escaped
// locals. Also avoid merging a variable with itself.
continue NEXT_VAR_PAIR;
}
if (v1.getParentNode().getType() == Token.LP &&
v2.getParentNode().getType() == Token.LP) {
interferenceGraph.connectIfNotFound(v1, null, v2);
continue NEXT_VAR_PAIR;
}
// Go through every CFG node in the program and look at
// this variable pair. If they are both live at the same
// time, add an edge between them and continue to the next pair.
NEXT_CROSS_CFG_NODE:
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue NEXT_CROSS_CFG_NODE;
}
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
// Check the live states and add edge when possible.
if ((state.getIn().isLive(v1) && state.getIn().isLive(v2)) ||
(state.getOut().isLive(v1) && state.getOut().isLive(v2))) {
interferenceGraph.connectIfNotFound(v1, null, v2);
continue NEXT_VAR_PAIR;
}
}
// v1 and v2 might not have an edge between them! woohoo. there's
// one last sanity check that we have to do: we have to check
// if there's a collision *within* the cfg node.
NEXT_INTRA_CFG_NODE:
for (DiGraphNode<Node, Branch> cfgNode : cfg.getDirectedGraphNodes()) {
if (cfg.isImplicitReturn(cfgNode)) {
continue NEXT_INTRA_CFG_NODE;
}
FlowState<LiveVariableLattice> state = cfgNode.getAnnotation();
boolean v1OutLive = state.getOut().isLive(v1);
boolean v2OutLive = state.getOut().isLive(v2);
CombinedLiveRangeChecker checker = new CombinedLiveRangeChecker(
new LiveRangeChecker(v1, v2OutLive ? null : v2),
new LiveRangeChecker(v2, v1OutLive ? null : v1));
NodeTraversal.traverse(
compiler,
cfgNode.getValue(),
checker);
if (checker.connectIfCrossed(interferenceGraph)) {
continue NEXT_VAR_PAIR;
}
}
}
}
return interferenceGraph;
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Symbol getSymbolForInstancesOf(FunctionType fn) {
Preconditions.checkState(fn.isConstructor() || fn.isInterface());
ObjectType pType = fn.getPrototype();
return getSymbolForName(fn.getSource(), pType.getReferenceName());
}
|
#vulnerable code
public Symbol getSymbolForInstancesOf(FunctionType fn) {
Preconditions.checkState(fn.isConstructor() || fn.isInterface());
ObjectType pType = fn.getPrototype();
String name = pType.getReferenceName();
if (name == null || globalScope == null) {
return null;
}
Node source = fn.getSource();
return (source == null ?
globalScope : getEnclosingScope(source)).getSlot(name);
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void enterScope(NodeTraversal t) {}
|
#vulnerable code
@Override
public void enterScope(NodeTraversal t) {
Scope scope = t.getScope();
// Computes the control flow graph.
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, scope.getRootNode());
cfgStack.push(curCfg);
curCfg = cfa.getCfg();
new GraphReachability<Node, ControlFlowGraph.Branch>(curCfg)
.compute(curCfg.getEntry().getValue());
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node aliasAndInlineArguments(
Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
Set<String> namesToAlias) {
if (namesToAlias == null || namesToAlias.isEmpty()) {
// There are no names to alias, just inline the arguments directly.
Node result = FunctionArgumentInjector.inject(
fnTemplateRoot, null, argMap);
Preconditions.checkState(result == fnTemplateRoot);
return result;
} else {
// Create local alias of names that can not be safely
// used directly.
// An arg map that will be updated to contain the
// safe aliases.
Map<String, Node> newArgMap = Maps.newHashMap(argMap);
// Declare the alias in the same order as they
// are declared.
List<Node> newVars = Lists.newLinkedList();
// NOTE: argMap is a linked map so we get the parameters in the
// order that they were declared.
for (Entry<String, Node> entry : argMap.entrySet()) {
String name = entry.getKey();
if (namesToAlias.contains(name)) {
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(name, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.remove(name);
}
}
// Inline the arguments.
Node result = FunctionArgumentInjector.inject(
fnTemplateRoot, null, newArgMap);
Preconditions.checkState(result == fnTemplateRoot);
// Now that the names have been replaced, add the new aliases for
// the old names.
for (Node n : newVars) {
fnTemplateRoot.addChildToFront(n);
}
return result;
}
}
|
#vulnerable code
private Node aliasAndInlineArguments(
Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
Set<String> namesToAlias) {
if (namesToAlias == null || namesToAlias.isEmpty()) {
// There are no names to alias, just inline the arguments directly.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, argMap);
Preconditions.checkState(result == fnTemplateRoot);
return result;
} else {
// Create local alias of names that can not be safely
// used directly.
// An arg map that will be updated to contain the
// safe aliases.
Map<String, Node> newArgMap = Maps.newHashMap(argMap);
// Declare the alias in the same order as they
// are declared.
List<Node> newVars = Lists.newLinkedList();
// NOTE: argMap is a linked map so we get the parameters in the
// order that they were declared.
for (Entry<String, Node> entry : argMap.entrySet()) {
String name = entry.getKey();
if (namesToAlias.contains(name)) {
if (name.equals(THIS_MARKER)) {
boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot);
// Update "this", this is only necessary if "this" is referenced
// and the value of "this" is not Token.THIS, or the value of "this"
// has side effects.
Node value = entry.getValue();
if (value.getType() != Token.THIS
&& (referencesThis
|| NodeUtil.mayHaveSideEffects(value, compiler))) {
String newName = getUniqueThisName();
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(newName, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.put(THIS_MARKER,
Node.newString(Token.NAME, newName)
.copyInformationFromForTree(newValue));
}
} else {
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(name, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.remove(name);
}
}
}
// Inline the arguments.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, newArgMap);
Preconditions.checkState(result == fnTemplateRoot);
// Now that the names have been replaced, add the new aliases for
// the old names.
for (Node n : newVars) {
fnTemplateRoot.addChildToFront(n);
}
return result;
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void removeUnreferencedVars() {
CodingConvention convention = codingConvention;
for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
Var var = it.next();
// Remove calls to inheritance-defining functions where the unreferenced
// class is the subclass.
for (Node exprCallNode : inheritsCalls.get(var)) {
NodeUtil.removeChild(exprCallNode.getParent(), exprCallNode);
compiler.reportCodeChange();
}
// Regardless of what happens to the original declaration,
// we need to remove all assigns, because they may contain references
// to other unreferenced variables.
removeAllAssigns(var);
compiler.addToDebugLog("Unreferenced var: " + var.name);
Node nameNode = var.nameNode;
Node toRemove = nameNode.getParent();
Node parent = toRemove.getParent();
Preconditions.checkState(
toRemove.getType() == Token.VAR ||
toRemove.getType() == Token.FUNCTION ||
toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION,
"We should only declare vars and functions and function args");
if (toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION) {
// Don't remove function arguments here. That's a special case
// that's taken care of in removeUnreferencedFunctionArgs.
} else if (NodeUtil.isFunctionExpression(toRemove)) {
if (!preserveFunctionExpressionNames) {
toRemove.getFirstChild().setString("");
compiler.reportCodeChange();
}
// Don't remove bleeding functions.
} else if (parent != null &&
parent.getType() == Token.FOR &&
parent.getChildCount() < 4) {
// foreach iterations have 3 children. Leave them alone.
} else if (toRemove.getType() == Token.VAR &&
nameNode.hasChildren() &&
NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
// If this is a single var declaration, we can at least remove the
// declaration itself and just leave the value, e.g.,
// var a = foo(); => foo();
if (toRemove.getChildCount() == 1) {
parent.replaceChild(toRemove,
new Node(Token.EXPR_RESULT, nameNode.removeFirstChild()));
compiler.reportCodeChange();
}
} else if (toRemove.getType() == Token.VAR &&
toRemove.getChildCount() > 1) {
// For var declarations with multiple names (i.e. var a, b, c),
// only remove the unreferenced name
toRemove.removeChild(nameNode);
compiler.reportCodeChange();
} else if (parent != null) {
NodeUtil.removeChild(parent, toRemove);
compiler.reportCodeChange();
}
}
}
|
#vulnerable code
private void removeUnreferencedVars() {
CodingConvention convention = compiler.getCodingConvention();
for (Iterator<Var> it = maybeUnreferenced.iterator(); it.hasNext(); ) {
Var var = it.next();
// Regardless of what happens to the original declaration,
// we need to remove all assigns, because they may contain references
// to other unreferenced variables.
removeAllAssigns(var);
compiler.addToDebugLog("Unreferenced var: " + var.name);
Node nameNode = var.nameNode;
Node toRemove = nameNode.getParent();
Node parent = toRemove.getParent();
Preconditions.checkState(
toRemove.getType() == Token.VAR ||
toRemove.getType() == Token.FUNCTION ||
toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION,
"We should only declare vars and functions and function args");
if (toRemove.getType() == Token.LP &&
parent.getType() == Token.FUNCTION) {
// Don't remove function arguments here. That's a special case
// that's taken care of in removeUnreferencedFunctionArgs.
} else if (NodeUtil.isFunctionExpression(toRemove)) {
if (!preserveFunctionExpressionNames) {
toRemove.getFirstChild().setString("");
compiler.reportCodeChange();
}
// Don't remove bleeding functions.
} else if (parent != null &&
parent.getType() == Token.FOR &&
parent.getChildCount() < 4) {
// foreach iterations have 3 children. Leave them alone.
} else if (toRemove.getType() == Token.VAR &&
nameNode.hasChildren() &&
NodeUtil.mayHaveSideEffects(nameNode.getFirstChild())) {
// If this is a single var declaration, we can at least remove the
// declaration itself and just leave the value, e.g.,
// var a = foo(); => foo();
if (toRemove.getChildCount() == 1) {
parent.replaceChild(toRemove,
new Node(Token.EXPR_RESULT, nameNode.removeFirstChild()));
compiler.reportCodeChange();
}
} else if (toRemove.getType() == Token.VAR &&
toRemove.getChildCount() > 1) {
// For var declarations with multiple names (i.e. var a, b, c),
// only remove the unreferenced name
toRemove.removeChild(nameNode);
compiler.reportCodeChange();
} else if (parent != null) {
NodeUtil.removeChild(parent, toRemove);
compiler.reportCodeChange();
}
}
}
#location 45
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node aliasAndInlineArguments(
Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
Set<String> namesToAlias) {
if (namesToAlias == null || namesToAlias.isEmpty()) {
// There are no names to alias, just inline the arguments directly.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, argMap);
Preconditions.checkState(result == fnTemplateRoot);
return result;
} else {
// Create local alias of names that can not be safely
// used directly.
// An arg map that will be updated to contain the
// safe aliases.
Map<String, Node> newArgMap = Maps.newHashMap(argMap);
// Declare the alias in the same order as they
// are declared.
List<Node> newVars = Lists.newLinkedList();
// NOTE: argMap is a linked map so we get the parameters in the
// order that they were declared.
for (Entry<String, Node> entry : argMap.entrySet()) {
String name = entry.getKey();
if (namesToAlias.contains(name)) {
if (name.equals(THIS_MARKER)) {
boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot);
// Update "this", this is only necessary if "this" is referenced
// and the value of "this" is not Token.THIS, or the value of "this"
// has side effects.
Node value = entry.getValue();
if (!value.isThis()
&& (referencesThis
|| NodeUtil.mayHaveSideEffects(value, compiler))) {
String newName = getUniqueThisName();
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(newName, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.put(THIS_MARKER,
Node.newString(Token.NAME, newName)
.copyInformationFromForTree(newValue));
}
} else {
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(name, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.remove(name);
}
}
}
// Inline the arguments.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, newArgMap);
Preconditions.checkState(result == fnTemplateRoot);
// Now that the names have been replaced, add the new aliases for
// the old names.
for (Node n : newVars) {
fnTemplateRoot.addChildToFront(n);
}
return result;
}
}
|
#vulnerable code
private Node aliasAndInlineArguments(
Node fnTemplateRoot, LinkedHashMap<String, Node> argMap,
Set<String> namesToAlias) {
if (namesToAlias == null || namesToAlias.isEmpty()) {
// There are no names to alias, just inline the arguments directly.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, argMap);
Preconditions.checkState(result == fnTemplateRoot);
return result;
} else {
// Create local alias of names that can not be safely
// used directly.
// An arg map that will be updated to contain the
// safe aliases.
Map<String, Node> newArgMap = Maps.newHashMap(argMap);
// Declare the alias in the same order as they
// are declared.
List<Node> newVars = Lists.newLinkedList();
// NOTE: argMap is a linked map so we get the parameters in the
// order that they were declared.
for (Entry<String, Node> entry : argMap.entrySet()) {
String name = entry.getKey();
if (namesToAlias.contains(name)) {
if (name.equals(THIS_MARKER)) {
boolean referencesThis = NodeUtil.referencesThis(fnTemplateRoot);
// Update "this", this is only necessary if "this" is referenced
// and the value of "this" is not Token.THIS, or the value of "this"
// has side effects.
Node value = entry.getValue();
if (value.getType() != Token.THIS
&& (referencesThis
|| NodeUtil.mayHaveSideEffects(value, compiler))) {
String newName = getUniqueThisName();
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(newName, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.put(THIS_MARKER,
Node.newString(Token.NAME, newName)
.copyInformationFromForTree(newValue));
}
} else {
Node newValue = entry.getValue().cloneTree();
Node newNode = NodeUtil.newVarNode(name, newValue)
.copyInformationFromForTree(newValue);
newVars.add(0, newNode);
// Remove the parameter from the list to replace.
newArgMap.remove(name);
}
}
}
// Inline the arguments.
Node result = FunctionArgumentInjector.inject(
compiler, fnTemplateRoot, null, newArgMap);
Preconditions.checkState(result == fnTemplateRoot);
// Now that the names have been replaced, add the new aliases for
// the old names.
for (Node n : newVars) {
fnTemplateRoot.addChildToFront(n);
}
return result;
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static List<JSSourceFile> getDefaultExterns() throws IOException {
InputStream input = CommandLineRunner.class.getResourceAsStream(
"/externs.zip");
ZipInputStream zip = new ZipInputStream(input);
Map<String, JSSourceFile> externsMap = Maps.newHashMap();
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
BufferedInputStream entryStream = new BufferedInputStream(
new LimitInputStream(zip, entry.getSize()));
externsMap.put(entry.getName(),
JSSourceFile.fromInputStream(
// Give the files an odd prefix, so that they do not conflict
// with the user's files.
"externs.zip//" + entry.getName(),
entryStream));
}
Preconditions.checkState(
externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
"Externs zip must match our hard-coded list of externs.");
// Order matters, so the resources must be added to the result list
// in the expected order.
List<JSSourceFile> externs = Lists.newArrayList();
for (String key : DEFAULT_EXTERNS_NAMES) {
externs.add(externsMap.get(key));
}
return externs;
}
|
#vulnerable code
public static List<JSSourceFile> getDefaultExterns() throws IOException {
InputStream input = CommandLineRunner.class.getResourceAsStream(
"/externs.zip");
ZipInputStream zip = new ZipInputStream(input);
Map<String, JSSourceFile> externsMap = Maps.newHashMap();
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize());
externsMap.put(entry.getName(),
JSSourceFile.fromInputStream(
// Give the files an odd prefix, so that they do not conflict
// with the user's files.
"externs.zip//" + entry.getName(),
entryStream));
}
Preconditions.checkState(
externsMap.keySet().equals(Sets.newHashSet(DEFAULT_EXTERNS_NAMES)),
"Externs zip must match our hard-coded list of externs.");
// Order matters, so the resources must be added to the result list
// in the expected order.
List<JSSourceFile> externs = Lists.newArrayList();
for (String key : DEFAULT_EXTERNS_NAMES) {
externs.add(externsMap.get(key));
}
return externs;
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
AbstractCommandLineRunner() {
this(System.out, System.err);
}
|
#vulnerable code
int processResults(Result result, List<JSModule> modules, B options)
throws FlagUsageException, IOException {
if (config.computePhaseOrdering) {
return 0;
}
if (config.printPassGraph) {
if (compiler.getRoot() == null) {
return 1;
} else {
jsOutput.append(
DotFormatter.toDot(compiler.getPassConfig().getPassGraph()));
jsOutput.append('\n');
return 0;
}
}
if (config.printAst) {
if (compiler.getRoot() == null) {
return 1;
} else {
ControlFlowGraph<Node> cfg = compiler.computeCFG();
DotFormatter.appendDot(
compiler.getRoot().getLastChild(), cfg, jsOutput);
jsOutput.append('\n');
return 0;
}
}
if (config.printTree) {
if (compiler.getRoot() == null) {
jsOutput.append("Code contains errors; no tree was generated.\n");
return 1;
} else {
compiler.getRoot().appendStringTree(jsOutput);
jsOutput.append("\n");
return 0;
}
}
rootRelativePathsMap = constructRootRelativePathsMap();
if (config.skipNormalOutputs) {
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
return 0;
} else if (result.success) {
if (modules == null) {
writeOutput(
jsOutput, compiler, compiler.toSource(), config.outputWrapper,
OUTPUT_WRAPPER_MARKER);
// Output the source map if requested.
outputSourceMap(options, config.jsOutputFile);
} else {
parsedModuleWrappers = parseModuleWrappers(
config.moduleWrapper, modules);
maybeCreateDirsForPath(config.moduleOutputPathPrefix);
// If the source map path is in fact a pattern for each
// module, create a stream per-module. Otherwise, create
// a single source map.
Writer mapOut = null;
if (!shouldGenerateMapPerModule(options)) {
mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, null));
}
for (JSModule m : modules) {
if (shouldGenerateMapPerModule(options)) {
mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, m));
}
Writer writer =
fileNameToLegacyOutputWriter(getModuleOutputFileName(m));
if (options.sourceMapOutputPath != null) {
compiler.getSourceMap().reset();
}
writeModuleOutput(writer, m);
if (options.sourceMapOutputPath != null) {
compiler.getSourceMap().appendTo(mapOut, m.getName());
}
writer.close();
if (shouldGenerateMapPerModule(options) && mapOut != null) {
mapOut.close();
mapOut = null;
}
}
if (mapOut != null) {
mapOut.close();
}
}
// Output the externs if required.
if (options.externExportsPath != null) {
Writer eeOut =
openExternExportsStream(options, config.jsOutputFile);
eeOut.append(result.externExport);
eeOut.close();
}
// Output the variable and property name maps if requested.
outputNameMaps(options);
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
if (options.tracer.isOn()) {
outputTracerReport();
}
}
// return 0 if no errors, the error count otherwise
return Math.min(result.errors.length, 0x7f);
}
#location 105
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
Node tryOptimizeBlock(Node n) {
// Remove any useless children
for (Node c = n.getFirstChild(); c != null; ) {
Node next = c.getNext(); // save c.next, since 'c' may be removed
if (!mayHaveSideEffects(c)) {
// TODO(johnlenz): determine what this is actually removing. Candidates
// include: EMPTY nodes, control structures without children
// (removing infinite loops), empty try blocks. What else?
n.removeChild(c); // lazy kids
reportCodeChange();
} else {
tryOptimizeConditionalAfterAssign(c);
}
c = next;
}
if (n.isSyntheticBlock() || n.getParent() == null) {
return n;
}
// Try to remove the block.
if (NodeUtil.tryMergeBlock(n)) {
reportCodeChange();
return null;
}
return n;
}
|
#vulnerable code
Node tryFoldFor(Node n) {
Preconditions.checkArgument(n.getType() == Token.FOR);
// This is not a FOR-IN loop
if (n.getChildCount() != 4) {
return n;
}
// There isn't an initializer
if (n.getFirstChild().getType() != Token.EMPTY) {
return n;
}
Node cond = NodeUtil.getConditionExpression(n);
if (NodeUtil.getBooleanValue(cond) != TernaryValue.FALSE) {
return n;
}
NodeUtil.redeclareVarsInsideBranch(n);
NodeUtil.removeChild(n.getParent(), n);
reportCodeChange();
return null;
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void outputManifest() throws IOException {
List<String> outputManifests = config.outputManifests;
if (outputManifests.isEmpty()) {
return;
}
for (String outputManifest : outputManifests) {
if (outputManifest.isEmpty()) {
continue;
}
JSModuleGraph graph = compiler.getModuleGraph();
if (shouldGenerateManifestPerModule(outputManifest)) {
// Generate per-module manifests.
Iterable<JSModule> modules = graph.getAllModules();
for (JSModule module : modules) {
Writer out = fileNameToOutputWriter(
expandManifest(module, outputManifest));
printManifestTo(module.getInputs(), out);
out.close();
}
} else {
// Generate a single file manifest.
Writer out = fileNameToOutputWriter(
expandManifest(null, outputManifest));
if (graph == null) {
printManifestTo(compiler.getInputsInOrder(), out);
} else {
printModuleGraphManifestTo(graph, out);
}
out.close();
}
}
}
|
#vulnerable code
private void outputManifest() throws IOException {
String outputManifest = config.outputManifest;
if (Strings.isEmpty(outputManifest)) {
return;
}
JSModuleGraph graph = compiler.getModuleGraph();
if (shouldGenerateManifestPerModule()) {
// Generate per-module manifests.
Iterable<JSModule> modules = graph.getAllModules();
for (JSModule module : modules) {
Writer out = fileNameToOutputWriter(expandManifest(module));
printManifestTo(module.getInputs(), out);
out.close();
}
} else {
// Generate a single file manifest.
Writer out = fileNameToOutputWriter(expandManifest(null));
if (graph == null) {
printManifestTo(compiler.getInputsInOrder(), out);
} else {
printModuleGraphManifestTo(graph, out);
}
out.close();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
null, safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
|
#vulnerable code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(Node externs, Node root) {
CollectTweaksResult result = collectTweaks(root);
applyCompilerDefaultValueOverrides(result.tweakInfos);
boolean changed = false;
if (stripTweaks) {
changed = stripAllCalls(result.tweakInfos);
} else if (!compilerDefaultValueOverrides.isEmpty()) {
changed = replaceGetCompilerOverridesCalls(result.getOverridesCalls);
}
if (changed) {
compiler.reportCodeChange();
}
}
|
#vulnerable code
@Override
public void process(Node externs, Node root) {
Map<String, TweakInfo> tweakInfos = collectTweaks(root);
applyCompilerDefaultValueOverrides(tweakInfos);
boolean changed = false;
if (stripTweaks) {
changed = stripAllCalls(tweakInfos);
} else if (!compilerDefaultValueOverrides.isEmpty()) {
// Pass the compiler default value overrides to the JS through a specially
// named variable.
Node varNode = createCompilerDefaultValueOverridesVarNode(
root.getFirstChild());
root.getFirstChild().addChildToFront(varNode);
changed = true;
}
if (changed) {
compiler.reportCodeChange();
}
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Node fuseIntoOneStatement(Node parent, Node first, Node last) {
// Nothing to fuse if there is only one statement.
if (first.getNext() == last) {
return first;
}
// Step one: Create a comma tree that contains all the statements.
Node commaTree = first.removeFirstChild();
Node next = null;
for (Node cur = first.getNext(); cur != last; cur = next) {
commaTree = fuseExpressionIntoExpression(
commaTree, cur.removeFirstChild());
next = cur.getNext();
parent.removeChild(cur);
}
// Step two: The last EXPR_RESULT will now hold the comma tree with all
// the fused statements.
first.addChildToBack(commaTree);
return first;
}
|
#vulnerable code
private Node fuseIntoOneStatement(Node parent, Node first, Node last) {
// Nothing to fuse if there is only one statement.
if (first == last) {
return first;
}
// Step one: Create a comma tree that contains all the statements.
Node commaTree = first.removeFirstChild();
Node onePastLast = last.getNext();
Node next = null;
for (Node cur = first.getNext(); cur != onePastLast; cur = next) {
commaTree = fuseExpressionIntoExpression(
commaTree, cur.removeFirstChild());
next = cur.getNext();
parent.removeChild(cur);
}
// Step two: The last EXPR_RESULT will now hold the comma tree with all
// the fused statements.
first.addChildToBack(commaTree);
return first;
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
FunctionTypeBuilder(String fnName, AbstractCompiler compiler,
Node errorRoot, String sourceName, Scope scope) {
Preconditions.checkNotNull(errorRoot);
this.fnName = fnName == null ? "" : fnName;
this.codingConvention = compiler.getCodingConvention();
this.typeRegistry = compiler.getTypeRegistry();
this.errorRoot = errorRoot;
this.sourceName = sourceName;
this.compiler = compiler;
this.scope = scope;
}
|
#vulnerable code
FunctionTypeBuilder inferReturnType(@Nullable JSDocInfo info) {
if (info != null && info.hasReturnType()) {
returnType = info.getReturnType().evaluate(scope, typeRegistry);
returnTypeInferred = false;
}
return this;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
AbstractCommandLineRunner() {
this(System.out, System.err);
}
|
#vulnerable code
int processResults(Result result, List<JSModule> modules, B options)
throws FlagUsageException, IOException {
if (config.computePhaseOrdering) {
return 0;
}
if (config.printPassGraph) {
if (compiler.getRoot() == null) {
return 1;
} else {
jsOutput.append(
DotFormatter.toDot(compiler.getPassConfig().getPassGraph()));
jsOutput.append('\n');
return 0;
}
}
if (config.printAst) {
if (compiler.getRoot() == null) {
return 1;
} else {
ControlFlowGraph<Node> cfg = compiler.computeCFG();
DotFormatter.appendDot(
compiler.getRoot().getLastChild(), cfg, jsOutput);
jsOutput.append('\n');
return 0;
}
}
if (config.printTree) {
if (compiler.getRoot() == null) {
jsOutput.append("Code contains errors; no tree was generated.\n");
return 1;
} else {
compiler.getRoot().appendStringTree(jsOutput);
jsOutput.append("\n");
return 0;
}
}
rootRelativePathsMap = constructRootRelativePathsMap();
if (config.skipNormalOutputs) {
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
return 0;
} else if (result.success) {
if (modules == null) {
writeOutput(
jsOutput, compiler, compiler.toSource(), config.outputWrapper,
OUTPUT_WRAPPER_MARKER);
// Output the source map if requested.
outputSourceMap(options, config.jsOutputFile);
} else {
parsedModuleWrappers = parseModuleWrappers(
config.moduleWrapper, modules);
maybeCreateDirsForPath(config.moduleOutputPathPrefix);
// If the source map path is in fact a pattern for each
// module, create a stream per-module. Otherwise, create
// a single source map.
Writer mapOut = null;
if (!shouldGenerateMapPerModule(options)) {
mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, null));
}
for (JSModule m : modules) {
if (shouldGenerateMapPerModule(options)) {
mapOut = fileNameToOutputWriter2(expandSourceMapPath(options, m));
}
Writer writer =
fileNameToLegacyOutputWriter(getModuleOutputFileName(m));
if (options.sourceMapOutputPath != null) {
compiler.getSourceMap().reset();
}
writeModuleOutput(writer, m);
if (options.sourceMapOutputPath != null) {
compiler.getSourceMap().appendTo(mapOut, m.getName());
}
writer.close();
if (shouldGenerateMapPerModule(options) && mapOut != null) {
mapOut.close();
mapOut = null;
}
}
if (mapOut != null) {
mapOut.close();
}
}
// Output the externs if required.
if (options.externExportsPath != null) {
Writer eeOut =
openExternExportsStream(options, config.jsOutputFile);
eeOut.append(result.externExport);
eeOut.close();
}
// Output the variable and property name maps if requested.
outputNameMaps(options);
// Output the manifest and bundle files if requested.
outputManifest();
outputBundle();
if (options.tracer.isOn()) {
outputTracerReport();
}
}
// return 0 if no errors, the error count otherwise
return Math.min(result.errors.length, 0x7f);
}
#location 105
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void ensureTyped(NodeTraversal t, Node n, JSType type) {
// Make sure FUNCTION nodes always get function type.
Preconditions.checkState(!n.isFunction() ||
type.isFunctionType() ||
type.isUnknownType());
// TODO(johnlenz): this seems like a strange place to check "@implicitCast"
JSDocInfo info = n.getJSDocInfo();
if (info != null) {
if (info.isImplicitCast() && !inExterns) {
String propName = n.isGetProp() ?
n.getLastChild().getString() : "(missing)";
compiler.report(
t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName));
}
}
if (n.getJSType() == null) {
n.setJSType(type);
}
}
|
#vulnerable code
private void ensureTyped(NodeTraversal t, Node n, JSType type) {
// Make sure FUNCTION nodes always get function type.
Preconditions.checkState(!n.isFunction() ||
type.isFunctionType() ||
type.isUnknownType());
JSDocInfo info = n.getJSDocInfo();
if (info != null) {
if (info.hasType()) {
// TODO(johnlenz): Change this so that we only look for casts on CAST
// nodes one the misplaced type annotation warning is on by default and
// people have been given a chance to fix them. As is, this is here
// simply for legacy casts.
JSType infoType = info.getType().evaluate(t.getScope(), typeRegistry);
validator.expectCanCast(t, n, infoType, type);
type = infoType;
}
if (info.isImplicitCast() && !inExterns) {
String propName = n.isGetProp() ?
n.getLastChild().getString() : "(missing)";
compiler.report(
t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName));
}
}
if (n.getJSType() == null) {
n.setJSType(type);
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void outputManifest() throws IOException {
List<String> outputManifests = config.outputManifests;
if (outputManifests.isEmpty()) {
return;
}
for (String outputManifest : outputManifests) {
if (outputManifest.isEmpty()) {
continue;
}
JSModuleGraph graph = compiler.getModuleGraph();
if (shouldGenerateManifestPerModule(outputManifest)) {
// Generate per-module manifests.
Iterable<JSModule> modules = graph.getAllModules();
for (JSModule module : modules) {
Writer out = fileNameToOutputWriter(
expandManifest(module, outputManifest));
printManifestTo(module.getInputs(), out);
out.close();
}
} else {
// Generate a single file manifest.
Writer out = fileNameToOutputWriter(
expandManifest(null, outputManifest));
if (graph == null) {
printManifestTo(compiler.getInputsInOrder(), out);
} else {
printModuleGraphManifestTo(graph, out);
}
out.close();
}
}
}
|
#vulnerable code
private void outputManifest() throws IOException {
String outputManifest = config.outputManifest;
if (Strings.isEmpty(outputManifest)) {
return;
}
JSModuleGraph graph = compiler.getModuleGraph();
if (shouldGenerateManifestPerModule()) {
// Generate per-module manifests.
Iterable<JSModule> modules = graph.getAllModules();
for (JSModule module : modules) {
Writer out = fileNameToOutputWriter(expandManifest(module));
printManifestTo(module.getInputs(), out);
out.close();
}
} else {
// Generate a single file manifest.
Writer out = fileNameToOutputWriter(expandManifest(null));
if (graph == null) {
printManifestTo(compiler.getInputsInOrder(), out);
} else {
printModuleGraphManifestTo(graph, out);
}
out.close();
}
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean isEquivalentTo(JSType otherType) {
FunctionType that =
JSType.toMaybeFunctionType(otherType.toMaybeFunctionType());
if (that == null) {
return false;
}
if (this.isConstructor()) {
if (that.isConstructor()) {
return this == that;
}
return false;
}
if (this.isInterface()) {
if (that.isInterface()) {
return this.getReferenceName().equals(that.getReferenceName());
}
return false;
}
if (that.isInterface()) {
return false;
}
return this.typeOfThis.isEquivalentTo(that.typeOfThis) &&
this.call.isEquivalentTo(that.call);
}
|
#vulnerable code
@Override
public boolean isEquivalentTo(JSType otherType) {
if (!(otherType instanceof FunctionType)) {
return false;
}
FunctionType that = (FunctionType) otherType;
if (!that.isFunctionType()) {
return false;
}
if (this.isConstructor()) {
if (that.isConstructor()) {
return this == that;
}
return false;
}
if (this.isInterface()) {
if (that.isInterface()) {
return this.getReferenceName().equals(that.getReferenceName());
}
return false;
}
if (that.isInterface()) {
return false;
}
return this.typeOfThis.isEquivalentTo(that.typeOfThis) &&
this.call.isEquivalentTo(that.call);
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<JSSourceFile> getDefaultExterns() {
try {
return CommandLineRunner.getDefaultExterns();
} catch (IOException e) {
throw new BuildException(e);
}
}
|
#vulnerable code
private List<JSSourceFile> getDefaultExterns() {
try {
InputStream input = Compiler.class.getResourceAsStream(
"/externs.zip");
ZipInputStream zip = new ZipInputStream(input);
List<JSSourceFile> externs = Lists.newLinkedList();
for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) {
LimitInputStream entryStream =
new LimitInputStream(zip, entry.getSize());
externs.add(
JSSourceFile.fromInputStream(entry.getName(), entryStream));
}
return externs;
} catch (IOException e) {
throw new BuildException(e);
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Symbol getSymbolDeclaredBy(FunctionType fn) {
Preconditions.checkState(fn.isConstructor() || fn.isInterface());
ObjectType instanceType = fn.getInstanceType();
return getSymbolForName(fn.getSource(), instanceType.getReferenceName());
}
|
#vulnerable code
public Symbol getSymbolDeclaredBy(FunctionType fn) {
Preconditions.checkState(fn.isConstructor() || fn.isInterface());
ObjectType instanceType = fn.getInstanceType();
String name = instanceType.getReferenceName();
if (name == null || globalScope == null) {
return null;
}
Node source = fn.getSource();
return (source == null ?
globalScope : getEnclosingScope(source)).getSlot(name);
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void toDebugString(StringBuilder builder, Symbol symbol) {
SymbolScope scope = symbol.scope;
if (scope.isGlobalScope()) {
builder.append(
String.format("'%s' : in global scope:\n", symbol.getName()));
} else if (scope.getRootNode() != null) {
builder.append(
String.format("'%s' : in scope %s:%d\n",
symbol.getName(),
scope.getRootNode().getSourceFileName(),
scope.getRootNode().getLineno()));
} else if (scope.getSymbolForScope() != null) {
builder.append(
String.format("'%s' : in scope %s\n", symbol.getName(),
scope.getSymbolForScope().getName()));
} else {
builder.append(
String.format("'%s' : in unknown scope\n", symbol.getName()));
}
int refCount = 0;
for (Reference ref : getReferences(symbol)) {
builder.append(
String.format(" Ref %d: %s:%d\n",
refCount,
ref.getNode().getSourceFileName(),
ref.getNode().getLineno()));
refCount++;
}
}
|
#vulnerable code
private void toDebugString(StringBuilder builder, Symbol symbol) {
SymbolScope scope = symbol.scope;
if (scope.isGlobalScope()) {
builder.append(
String.format("'%s' : in global scope:\n", symbol.getName()));
} else {
builder.append(
String.format("'%s' : in scope %s:%d\n",
symbol.getName(),
scope.getRootNode().getSourceFileName(),
scope.getRootNode().getLineno()));
}
int refCount = 0;
for (Reference ref : getReferences(symbol)) {
builder.append(
String.format(" Ref %d: %s:%d\n",
refCount,
ref.getNode().getSourceFileName(),
ref.getNode().getLineno()));
refCount++;
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void setSqlSource(MappedStatement ms) {
MapperTemplate mapperTemplate = getMapperTemplate(ms.getId());
try {
if (mapperTemplate != null) {
mapperTemplate.setSqlSource(ms);
}
} catch (Exception e) {
throw new RuntimeException("调用方法异常:" + e.getMessage());
}
}
|
#vulnerable code
public void setSqlSource(MappedStatement ms) {
MapperTemplate mapperTemplate = getMapperTemplate(ms.getId());
try {
mapperTemplate.setSqlSource(ms);
} catch (Exception e) {
throw new RuntimeException("调用方法异常:" + e.getMessage());
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected String read(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, encoding));
StringBuffer stringBuffer = new StringBuffer();
String line = reader.readLine();
while (line != null) {
stringBuffer.append(line).append("\n");
line = reader.readLine();
}
return stringBuffer.toString();
}
|
#vulnerable code
protected String read(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = reader.readLine();
while (line != null) {
stringBuffer.append(line).append("\n");
line = reader.readLine();
}
return stringBuffer.toString();
}
#location 9
#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) {
example();
}
|
#vulnerable code
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("exampleContext.xml");
SpringCacheExample example = context.getBean(SpringCacheExample.class);
example.getBook(0);
example.getBook(0);
}
#location 4
#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) {
example();
}
|
#vulnerable code
public static void main(String[] args) {
Cache<Integer, Integer> cache = CacheBuilder.transactionalHeapCache()
.transactionCommitter(new TransactionCommitter<Integer, Integer>() {
int counter = 0;
public void doPut(Integer key, Integer value) {
if (counter < 3) {
System.out.println("key[" + key + "]," + "value[" + value + "]");
counter++;
} else {
throw new RuntimeException();
}
}
}).build();
Transaction transaction1 = CacheTransaction.get();
transaction1.begin();
try {
cache.put(3, 5);
cache.put(10, 14);
transaction1.commit();
} catch (TransactionException exception) {
transaction1.rollback();
} finally {
transaction1.close();
}
System.out.println("Value for the key 3 is " + cache.get(3));
System.out.println("Value for the key 10 is " + cache.get(10));
Transaction transaction2 = CacheTransaction.get();
transaction2.begin();
try {
cache.put(1, 10);
cache.put(10, 13);
transaction2.commit();
} catch (TransactionException exception) {
transaction2.rollback();
} finally {
transaction2.close();
}
System.out.println("Value for the key 1 is " + cache.get(1));
System.out.println("Value for the key 10 is " + cache.get(10));
}
#location 16
#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) {
example();
}
|
#vulnerable code
public static void main(String[] args) {
@SuppressWarnings({ "resource", "unused" })
ApplicationContext context = new ClassPathXmlApplicationContext("exampleContext.xml");
}
#location 3
#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) {
example();
}
|
#vulnerable code
public static void main(String[] args) {
Cache<Integer, Integer> cache = CacheBuilder.transactionalHeapCache()
.transactionCommitter(new TransactionCommitter<Integer, Integer>() {
int counter = 0;
public void doPut(Integer key, Integer value) {
if (counter < 3) {
System.out.println("key[" + key + "]," + "value[" + value + "]");
counter++;
} else {
throw new RuntimeException();
}
}
}).build();
Transaction transaction1 = CacheTransaction.get();
transaction1.begin();
try {
cache.put(3, 5);
cache.put(10, 14);
transaction1.commit();
} catch (TransactionException exception) {
transaction1.rollback();
} finally {
transaction1.close();
}
System.out.println("Value for the key 3 is " + cache.get(3));
System.out.println("Value for the key 10 is " + cache.get(10));
Transaction transaction2 = CacheTransaction.get();
transaction2.begin();
try {
cache.put(1, 10);
cache.put(10, 13);
transaction2.commit();
} catch (TransactionException exception) {
transaction2.rollback();
} finally {
transaction2.close();
}
System.out.println("Value for the key 1 is " + cache.get(1));
System.out.println("Value for the key 10 is " + cache.get(10));
}
#location 29
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static void installDependencies(PrintStream logger, Launcher launcher,
AndroidSdk sdk, EmulatorConfig emuConfig) throws IOException, InterruptedException {
// Get AVD platform from emulator config
String platform = getPlatformForEmulator(launcher, emuConfig);
// Install platform and any dependencies it may have
final boolean skipSystemImageInstall = emuConfig.isNamedEmulator()
|| !emuConfig.getOsVersion().requiresAbi();
installPlatform(logger, launcher, sdk, platform, emuConfig.getTargetAbi(), skipSystemImageInstall);
}
|
#vulnerable code
static void installDependencies(PrintStream logger, Launcher launcher,
AndroidSdk sdk, EmulatorConfig emuConfig) throws IOException, InterruptedException {
// Get AVD platform from emulator config
String platform = getPlatformForEmulator(launcher, emuConfig);
// Install platform and any dependencies it may have
final boolean requiresAbi = emuConfig.getOsVersion().requiresAbi();
String abi = requiresAbi ? emuConfig.getTargetAbi() : null;
installPlatform(logger, launcher, sdk, platform, abi, emuConfig.isNamedEmulator());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void writeAvdConfigFile(File homeDir, Map<String,String> values) throws IOException {
final File configFile = getAvdConfigFile(homeDir);
ConfigFileUtils.writeConfigFile(configFile, values);
}
|
#vulnerable code
private void writeAvdConfigFile(File homeDir, Map<String,String> values) throws FileNotFoundException {
StringBuilder sb = new StringBuilder();
for (String key : values.keySet()) {
sb.append(key);
sb.append("=");
sb.append(values.get(key));
sb.append("\r\n");
}
File configFile = new File(getAvdDirectory(homeDir), "config.ini");
PrintWriter out = new PrintWriter(configFile);
out.print(sb.toString());
out.flush();
out.close();
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testTargetName() {
assertEquals("Some:Addon:11", AndroidPlatform.valueOf("Some:Addon:11").getTargetName());
assertEquals("Google Inc.:Google APIs:23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getTargetName());
assertEquals("Google Inc.:Google APIs:24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getTargetName());
assertEquals("Apple Inc.:Apple APIs:24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getTargetName());
assertEquals("android-23", AndroidPlatform.valueOf("android-23").getTargetName());
assertEquals("android-24", AndroidPlatform.valueOf("android-24").getTargetName());
assertEquals("android-26", AndroidPlatform.valueOf("android-26").getTargetName());
assertEquals("android-10", AndroidPlatform.valueOf("2.3.3").getTargetName());
assertEquals("android-26", AndroidPlatform.valueOf("8.0").getTargetName());
assertEquals("android-26", AndroidPlatform.valueOf("26").getTargetName());
}
|
#vulnerable code
@Test
public void testTargetName() {
assertEquals("Google Inc.:Google APIs:23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getTargetName());
assertEquals("Google Inc.:Google APIs:24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getTargetName());
assertEquals("Apple Inc.:Apple APIs:24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getTargetName());
assertEquals("android-23", AndroidPlatform.valueOf("android-23").getTargetName());
assertEquals("android-24", AndroidPlatform.valueOf("android-24").getTargetName());
assertEquals("android-26", AndroidPlatform.valueOf("android-26").getTargetName());
assertEquals("android-10", AndroidPlatform.valueOf("2.3.3").getTargetName());
assertEquals("android-26", AndroidPlatform.valueOf("8.0").getTargetName());
assertEquals("android-26", AndroidPlatform.valueOf("26").getTargetName());
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testSystemImageName() {
assertEquals("sys-img-x86-android-23", AndroidPlatform.valueOf("android-23").getSystemImageName("x86"));
assertEquals("sys-img-x86-google_apis-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("x86"));
assertEquals("sys-img-x86-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86"));
assertEquals("sys-img-x86_64-apple_apis-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("x86_64"));
assertEquals("sys-img-x86_64-ms_apis-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("x86_64"));
assertEquals("sys-img-armabi-v7a-android-23", AndroidPlatform.valueOf("android-23").getSystemImageName("armabi-v7a"));
assertEquals("sys-img-armabi-v7a-android-24", AndroidPlatform.valueOf("android-24").getSystemImageName("armabi-v7a"));
assertEquals("sys-img-arm64-v8a-android-26", AndroidPlatform.valueOf("android-26").getSystemImageName("arm64-v8a"));
assertEquals("sys-img-x86-test-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("test/x86"));
assertEquals("sys-img-x86-test-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("test/x86"));
assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("test/x86_64"));
assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("test/x86_64"));
assertEquals("sys-img-armabi-v7a-test-23", AndroidPlatform.valueOf("android-23").getSystemImageName("test/armabi-v7a"));
assertEquals("sys-img-armabi-v7a-test-24", AndroidPlatform.valueOf("android-24").getSystemImageName("test/armabi-v7a"));
assertEquals("sys-img-arm64-v8a-test-26", AndroidPlatform.valueOf("android-26").getSystemImageName("test/arm64-v8a"));
assertEquals("sys-img-x86-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("/x86"));
assertEquals("sys-img-x86-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("///////x86"));
assertEquals("sys-img-x86_64-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64/"));
assertEquals("sys-img-x86_64-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64////"));
}
|
#vulnerable code
@Test
public void testSystemImageName() {
assertEquals("sys-img-x86-android-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("x86"));
assertEquals("sys-img-x86-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86"));
assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("x86_64"));
assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("x86_64"));
assertEquals("sys-img-armabi-v7a-android-23", AndroidPlatform.valueOf("android-23").getSystemImageName("armabi-v7a"));
assertEquals("sys-img-armabi-v7a-android-24", AndroidPlatform.valueOf("android-24").getSystemImageName("armabi-v7a"));
assertEquals("sys-img-arm64-v8a-android-26", AndroidPlatform.valueOf("android-26").getSystemImageName("arm64-v8a"));
assertEquals("sys-img-x86-test-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("test/x86"));
assertEquals("sys-img-x86-test-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("test/x86"));
assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("test/x86_64"));
assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("test/x86_64"));
assertEquals("sys-img-armabi-v7a-test-23", AndroidPlatform.valueOf("android-23").getSystemImageName("test/armabi-v7a"));
assertEquals("sys-img-armabi-v7a-test-24", AndroidPlatform.valueOf("android-24").getSystemImageName("test/armabi-v7a"));
assertEquals("sys-img-arm64-v8a-test-26", AndroidPlatform.valueOf("android-26").getSystemImageName("test/arm64-v8a"));
assertEquals("sys-img-x86-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("/x86"));
assertEquals("sys-img-x86-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("///////x86"));
assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64/"));
assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64////"));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void determinesItemBSourceSetter() {
Target target = new Target();
target.setKeyOfAllBeings( new KeyOfAllBeings() );
Child source = new Child();
GenericsHierarchyMapper.INSTANCE.updateSourceWithKeyOfAllBeings( target, source );
assertThat( source.getKey().typeParameterIsResolvedToKeyOfAllBeings() ).isTrue();
}
|
#vulnerable code
@Test
public void determinesItemBSourceSetter() {
Target target = new Target();
target.setItemB( new ItemB() );
SourceWithItemB source = new SourceWithItemB();
GenericsHierarchyMapper.INSTANCE.intoSourceWithItemB( target, source );
assertThat( source.getItem().typeParameterIsResolvedToItemB() ).isTrue();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean isIterableMapping() {
return getSingleSourceParameter().getType().isIterableType() && getResultType().isIterableType();
}
|
#vulnerable code
public boolean isIterableMapping() {
return getSingleSourceType().isIterableType() && resultType.isIterableType();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Mapping getMapping(MappingPrism mapping) {
return new Mapping( mapping.source(), mapping.target() );
}
|
#vulnerable code
private Mapping getMapping(MappingPrism mapping) {
Type converterType = typeUtil.retrieveType( mapping.converter() );
return new Mapping(
mapping.source(),
mapping.target(),
converterType.getName().equals( "NoOpConverter" ) ? null : converterType
);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
List<ExecutableElement> sourceSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters )
.getSimpleName()
.toString(),
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters )
.getSimpleName()
.toString(),
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
|
#vulnerable code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
Element returnTypeElement = typeUtils.asElement( method.getReturnType() );
Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( parameterElement.getEnclosedElements() );
List<ExecutableElement> targetSetters = Filters.setterMethodsIn( returnTypeElement.getEnclosedElements() );
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
Executables.getCorrespondingSetterMethod( parameterElement, getterMethod )
.getSimpleName()
.toString(),
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
Executables.getCorrespondingGetterMethod( returnTypeElement, setterMethod )
.getSimpleName()
.toString(),
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean process(
final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnvironment) {
for ( TypeElement oneAnnotation : annotations ) {
//Indicates that the annotation's type isn't on the class path of the compiled
//project. Let the compiler deal with that and print an appropriate error.
if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) {
continue;
}
for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) {
oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv ), null );
}
}
return ANNOTATIONS_CLAIMED_EXCLUSIVELY;
}
|
#vulnerable code
@Override
public boolean process(
final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnvironment) {
for ( TypeElement oneAnnotation : annotations ) {
//Indicates that the annotation's type isn't on the class path of the compiled
//project. Let the compiler deal with that and print an appropriate error.
if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) {
continue;
}
for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) {
oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv, configuration ), null );
}
}
return ANNOTATIONS_CLAIMED_EXCLUSIVELY;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Mapper process(ProcessorContext context, TypeElement mapperTypeElement, Mapper mapper) {
String componentModel = MapperPrism.getInstanceOn( mapperTypeElement ).componentModel();
String effectiveComponentModel = OptionsHelper.getEffectiveComponentModel(
context.getOptions(),
componentModel
);
if ( !"cdi".equalsIgnoreCase( effectiveComponentModel ) ) {
return mapper;
}
mapper.addAnnotation( new Annotation( new Type( "javax.enterprise.context", "ApplicationScoped" ) ) );
ListIterator<MapperReference> iterator = mapper.getReferencedMappers().listIterator();
while ( iterator.hasNext() ) {
MapperReference reference = iterator.next();
iterator.remove();
iterator.add( new CdiMapperReference( reference.getMapperType() ) );
}
return mapper;
}
|
#vulnerable code
@Override
public Mapper process(ProcessorContext context, TypeElement mapperTypeElement, Mapper mapper) {
String componentModel = MapperPrism.getInstanceOn( mapperTypeElement ).componentModel();
if ( !componentModel.equals( "cdi" ) ) {
return mapper;
}
mapper.addAnnotation( new Annotation( new Type( "javax.enterprise.context", "ApplicationScoped" ) ) );
ListIterator<MapperReference> iterator = mapper.getReferencedMappers().listIterator();
while ( iterator.hasNext() ) {
MapperReference reference = iterator.next();
iterator.remove();
iterator.add( new CdiMapperReference( reference.getMapperType() ) );
}
return mapper;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
List<ExecutableElement> sourceSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters )
.getSimpleName()
.toString(),
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters )
.getSimpleName()
.toString(),
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
|
#vulnerable code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
Element returnTypeElement = typeUtils.asElement( method.getReturnType() );
Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( parameterElement.getEnclosedElements() );
List<ExecutableElement> targetSetters = Filters.setterMethodsIn( returnTypeElement.getEnclosedElements() );
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
Executables.getCorrespondingSetterMethod( parameterElement, getterMethod )
.getSimpleName()
.toString(),
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
Executables.getCorrespondingGetterMethod( returnTypeElement, setterMethod )
.getSimpleName()
.toString(),
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) {
List<Method> methods = new ArrayList<Method>();
MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null;
for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) {
Method method = getMethod( element, executable, implementationRequired );
if ( method != null ) {
methods.add( method );
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( implementationRequired ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
(TypeElement) ( (DeclaredType) usedMapper ).asElement(),
false
)
);
}
}
return methods;
}
|
#vulnerable code
private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) {
List<Method> methods = new ArrayList<Method>();
MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null;
//TODO Extract to separate method
for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) {
Parameter parameter = executables.retrieveParameter( method );
Type returnType = executables.retrieveReturnType( method );
boolean mappingErroneous = false;
if ( implementationRequired ) {
if ( parameter.getType().isIterableType() && !returnType.isIterableType() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method from iterable type to non-iterable type.",
method
);
mappingErroneous = true;
}
if ( !parameter.getType().isIterableType() && returnType.isIterableType() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method from non-iterable type to iterable type.",
method
);
mappingErroneous = true;
}
if ( parameter.getType().isPrimitive() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method with primitive parameter type.",
method
);
mappingErroneous = true;
}
if ( returnType.isPrimitive() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method with primitive return type.",
method
);
mappingErroneous = true;
}
if ( mappingErroneous ) {
continue;
}
}
//add method with property mappings if an implementation needs to be generated
if ( implementationRequired ) {
methods.add(
Method.forMethodRequiringImplementation(
method,
parameter.getName(),
parameter.getType(),
returnType,
getMappings( method )
)
);
}
//otherwise add reference to existing mapper method
else {
methods.add(
Method.forReferencedMethod(
typeUtil.getType( typeUtils.getDeclaredType( element ) ),
method,
parameter.getName(),
parameter.getType(),
returnType
)
);
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( implementationRequired ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
(TypeElement) ( (DeclaredType) usedMapper ).asElement(),
false
)
);
}
}
return methods;
}
#location 57
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences, List<Method> methods,
Method method, Parameter parameter, ExecutableElement sourceAccessor,
ExecutableElement targetAcessor, String dateFormat) {
Type sourceType = typeFactory.getReturnType( sourceAccessor );
Type targetType = null;
String conversionString = null;
conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()";
if ( Executables.isSetterMethod( targetAcessor ) ) {
targetType = typeFactory.getSingleParameter( targetAcessor ).getType();
}
else if ( Executables.isGetterMethod( targetAcessor ) ) {
targetType = typeFactory.getReturnType( targetAcessor );
}
MethodReference propertyMappingMethod = getMappingMethodReference(
method,
"property '" + Executables.getPropertyName( sourceAccessor ) + "'",
mapperReferences,
methods,
sourceType,
targetType
);
TypeConversion conversion = getConversion(
sourceType,
targetType,
dateFormat,
conversionString
);
PropertyMapping property = new PropertyMapping(
parameter.getName(),
Executables.getPropertyName( sourceAccessor ),
sourceAccessor.getSimpleName().toString(),
sourceType,
Executables.getPropertyName( targetAcessor ),
targetAcessor.getSimpleName().toString(),
targetType,
propertyMappingMethod,
conversion
);
reportErrorIfPropertyCanNotBeMapped(
method,
property
);
return property;
}
|
#vulnerable code
private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences, List<Method> methods,
Method method, Parameter parameter, ExecutableElement sourceAccessor,
ExecutableElement targetAcessor, String dateFormat) {
Type sourceType = typeFactory.getReturnType( sourceAccessor );
Type targetType = null;
String conversionString = null;
conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()";
if ( Executables.isSetterMethod( targetAcessor ) ) {
targetType = typeFactory.getSingleParameter( targetAcessor ).getType();
}
else if ( Executables.isGetterMethod( targetAcessor ) ) {
targetType = typeFactory.getReturnType( targetAcessor );
}
MethodReference propertyMappingMethod = getMappingMethodReference(
mapperReferences,
methods,
sourceType,
targetType
);
TypeConversion conversion = getConversion(
sourceType,
targetType,
dateFormat,
conversionString
);
PropertyMapping property = new PropertyMapping(
parameter.getName(),
Executables.getPropertyName( sourceAccessor ),
sourceAccessor.getSimpleName().toString(),
sourceType,
Executables.getPropertyName( targetAcessor ),
targetAcessor.getSimpleName().toString(),
targetType,
propertyMappingMethod,
conversion
);
reportErrorIfPropertyCanNotBeMapped(
method,
property
);
return property;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean isMapMapping() {
return getSingleSourceParameter().getType().isMapType() && getResultType().isMapType();
}
|
#vulnerable code
public boolean isMapMapping() {
return getSingleSourceType().isMapType() && resultType.isMapType();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void deleteDirectory(File path) {
if ( path.exists() ) {
File[] files = path.listFiles();
for ( File file : files ) {
if ( file.isDirectory() ) {
deleteDirectory( file );
}
else {
file.delete();
}
}
}
path.delete();
}
|
#vulnerable code
private void deleteDirectory(File path) {
if ( path.exists() ) {
File[] files = path.listFiles();
for ( int i = 0; i < files.length; i++ ) {
if ( files[i].isDirectory() ) {
deleteDirectory( files[i] );
}
else {
files[i].delete();
}
}
}
path.delete();
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<Method> retrieveMethods(TypeElement element, boolean mapperRequiresImplementation) {
List<Method> methods = new ArrayList<Method>();
for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) {
Method method = getMethod( element, executable, mapperRequiresImplementation );
if ( method != null ) {
methods.add( method );
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( mapperRequiresImplementation ) {
MapperPrism mapperPrism = MapperPrism.getInstanceOn( element );
if ( !mapperPrism.isValid ) {
throw new AnnotationProcessingException(
"Couldn't retrieve @Mapper annotation", element, mapperPrism.mirror
);
}
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
(TypeElement) ( (DeclaredType) usedMapper ).asElement(),
false
)
);
}
}
return methods;
}
|
#vulnerable code
private List<Method> retrieveMethods(TypeElement element, boolean mapperRequiresImplementation) {
List<Method> methods = new ArrayList<Method>();
MapperPrism mapperPrism = mapperRequiresImplementation ? MapperPrism.getInstanceOn( element ) : null;
for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) {
Method method = getMethod( element, executable, mapperRequiresImplementation );
if ( method != null ) {
methods.add( method );
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( mapperRequiresImplementation ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
(TypeElement) ( (DeclaredType) usedMapper ).asElement(),
false
)
);
}
}
return methods;
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
List<ExecutableElement> sourceSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor(
getterMethod,
sourceSetters
);
ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor(
setterMethod,
targetGetters
);
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null,
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null,
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
|
#vulnerable code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
List<ExecutableElement> sourceSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters )
.getSimpleName()
.toString(),
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters )
.getSimpleName()
.toString(),
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
#location 35
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void determinesItemCSourceSetter() {
Target target = new Target();
target.setAnimalKey( new AnimalKey() );
Elephant source = new Elephant();
GenericsHierarchyMapper.INSTANCE.updateSourceWithAnimalKey( target, source );
assertThat( source.getKey().typeParameterIsResolvedToAnimalKey() ).isTrue();
}
|
#vulnerable code
@Test
public void determinesItemCSourceSetter() {
Target target = new Target();
target.setItemC( new ItemC() );
SourceWithItemC source = new SourceWithItemC();
GenericsHierarchyMapper.INSTANCE.intoSourceWithItemC( target, source );
assertThat( source.getItem().typeParameterIsResolvedToItemC() ).isTrue();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private MappingMethod getBeanMappingMethod(List<Method> methods, Method method,
ReportingPolicy unmappedTargetPolicy) {
List<PropertyMapping> propertyMappings = new ArrayList<PropertyMapping>();
Set<String> mappedTargetProperties = new HashSet<String>();
Map<String, Mapping> mappings = method.getMappings();
TypeElement resultTypeElement = elementUtils.getTypeElement( method.getResultType().getCanonicalName() );
TypeElement parameterElement = elementUtils.getTypeElement(
method.getSingleSourceParameter()
.getType()
.getCanonicalName()
);
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( resultTypeElement )
);
Set<String> sourceProperties = executables.getPropertyNames(
Filters.getterMethodsIn( sourceGetters )
);
Set<String> targetProperties = executables.getPropertyNames(
Filters.setterMethodsIn( targetSetters )
);
reportErrorIfMappedPropertiesDontExist( method, sourceProperties, targetProperties );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
String dateFormat = mapping != null ? mapping.getDateFormat() : null;
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
PropertyMapping property = getPropertyMapping(
methods,
method,
getterMethod,
setterMethod,
dateFormat
);
propertyMappings.add( property );
mappedTargetProperties.add( targetPropertyName );
}
}
}
reportErrorForUnmappedTargetPropertiesIfRequired(
method,
unmappedTargetPolicy,
targetProperties,
mappedTargetProperties
);
return new BeanMappingMethod( method, propertyMappings );
}
|
#vulnerable code
private MappingMethod getBeanMappingMethod(List<Method> methods, Method method,
ReportingPolicy unmappedTargetPolicy) {
List<PropertyMapping> propertyMappings = new ArrayList<PropertyMapping>();
Set<String> mappedTargetProperties = new HashSet<String>();
Map<String, Mapping> mappings = method.getMappings();
TypeElement resultTypeElement = elementUtils.getTypeElement( method.getResultType().getCanonicalName() );
TypeElement parameterElement = elementUtils.getTypeElement( method.getSingleSourceType().getCanonicalName() );
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( resultTypeElement )
);
Set<String> sourceProperties = executables.getPropertyNames(
Filters.getterMethodsIn( sourceGetters )
);
Set<String> targetProperties = executables.getPropertyNames(
Filters.setterMethodsIn( targetSetters )
);
reportErrorIfMappedPropertiesDontExist( method, sourceProperties, targetProperties );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
String dateFormat = mapping != null ? mapping.getDateFormat() : null;
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
PropertyMapping property = getPropertyMapping(
methods,
method,
getterMethod,
setterMethod,
dateFormat
);
propertyMappings.add( property );
mappedTargetProperties.add( targetPropertyName );
}
}
}
reportErrorForUnmappedTargetPropertiesIfRequired(
method,
unmappedTargetPolicy,
targetProperties,
mappedTargetProperties
);
return new BeanMappingMethod(
method.getName(),
method.getParameters(),
method.getSourceParameters(),
method.getResultType(),
method.getResultName(),
method.getReturnType(),
propertyMappings
);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean matches() {
// check & collect generic types.
List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters();
if ( candidateParameters.size() != 1 ) {
typesMatch = false;
}
else {
TypeMatcher parameterMatcher = new TypeMatcher();
typesMatch = parameterMatcher.visit(
candidateParameters.iterator().next().asType(),
parameter.getTypeMirror()
);
}
// check return type
if ( typesMatch ) {
TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType();
TypeMatcher returnTypeMatcher = new TypeMatcher();
typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() );
}
// check if all type parameters are indeed mapped
if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) {
typesMatch = false;
}
else {
// check if all entries are in the bounds
for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) {
if (!isWithinBounds( entry.getValue(), getTypeParamFromCandidate( entry.getKey() ) ) ) {
// checks if the found Type is in bounds of the TypeParameters bounds.
typesMatch = false;
}
}
}
return typesMatch;
}
|
#vulnerable code
public boolean matches() {
// check & collect generic types.
List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters();
if ( candidateParameters.size() == parameters.length ) {
for ( int i = 0; i < parameters.length; i++ ) {
TypeMatcher parameterMatcher = new TypeMatcher();
typesMatch = parameterMatcher.visit( candidateParameters.get( i ).asType(),
parameters[i].getTypeMirror() );
if ( !typesMatch ) {
break;
}
}
}
else {
typesMatch = false;
}
// check return type
if ( typesMatch ) {
TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType();
TypeMatcher returnTypeMatcher = new TypeMatcher();
typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() );
}
// check if all type parameters are indeed mapped
if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) {
typesMatch = false;
}
else {
// check if all entries are in the bounds
for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) {
if (!isWithinBounds( entry.getValue(), getTypeParamFromCandite( entry.getKey() ) ) ) {
// checks if the found Type is in bounds of the TypeParameters bounds.
typesMatch = false;
}
}
}
return typesMatch;
}
#location 33
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private PropertyMapping getConstantMapping(List<MapperReference> mapperReferences,
List<SourceMethod> methods,
SourceMethod method,
String constantExpression,
ExecutableElement targetAccessor,
String dateFormat,
List<TypeMirror> qualifiers) {
// source
String mappedElement = "constant '" + constantExpression + "'";
Type sourceType = typeFactory.getType( String.class );
// target
Type targetType;
if ( Executables.isSetterMethod( targetAccessor ) ) {
targetType = typeFactory.getSingleParameter( targetAccessor ).getType();
}
else {
targetType = typeFactory.getReturnType( targetAccessor );
}
String targetPropertyName = Executables.getPropertyName( targetAccessor );
Assignment assignment = mappingResolver.getTargetAssignment(
method,
mappedElement,
mapperReferences,
methods,
sourceType,
targetType,
targetPropertyName,
dateFormat,
qualifiers,
constantExpression
);
if ( assignment != null ) {
// target accessor is setter, so decorate assignment as setter
assignment = new SetterWrapper( assignment, method.getThrownTypes() );
// wrap when dealing with getter only on target
if ( Executables.isGetterMethod( targetAccessor ) ) {
assignment = new GetterCollectionOrMapWrapper( assignment );
}
}
else {
messager.printMessage(
Kind.ERROR,
String.format(
"Can't map \"%s %s\" to \"%s %s\".",
sourceType,
constantExpression,
targetType,
targetPropertyName
),
method.getExecutable()
);
}
return new PropertyMapping( targetAccessor.getSimpleName().toString(), targetType, assignment );
}
|
#vulnerable code
private PropertyMapping getConstantMapping(List<MapperReference> mapperReferences,
List<SourceMethod> methods,
SourceMethod method,
String constantExpression,
ExecutableElement targetAccessor,
String dateFormat,
List<TypeMirror> qualifiers) {
// source
String mappedElement = "constant '" + constantExpression + "'";
Type sourceType = typeFactory.getType( String.class );
// target
Type targetType = typeFactory.getSingleParameter( targetAccessor ).getType();
String targetPropertyName = Executables.getPropertyName( targetAccessor );
Assignment assignment = mappingResolver.getTargetAssignment(
method,
mappedElement,
mapperReferences,
methods,
sourceType,
targetType,
targetPropertyName,
dateFormat,
qualifiers,
constantExpression
);
if ( assignment != null ) {
// target accessor is setter, so decorate assignment as setter
assignment = new SetterWrapper( assignment, method.getThrownTypes() );
}
else {
messager.printMessage(
Kind.ERROR,
String.format(
"Can't map \"%s %s\" to \"%s %s\".",
sourceType,
constantExpression,
targetType,
targetPropertyName
),
method.getExecutable()
);
}
return new PropertyMapping( targetAccessor.getSimpleName().toString(), targetType, assignment );
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void reportErrorIfPropertyCanNotBeMapped(Method method, PropertyMapping property) {
if ( property.getSourceType().isAssignableTo( property.getTargetType() ) ||
property.getMappingMethod() != null ||
property.getConversion() != null ||
property.getTargetType().getImplementationType() != null ) {
return;
}
messager.printMessage(
Kind.ERROR,
String.format(
"Can't map property \"%s %s\" to \"%s %s\".",
property.getSourceType(),
property.getSourceName(),
property.getTargetType(),
property.getTargetName()
),
method.getExecutable()
);
}
|
#vulnerable code
private void reportErrorIfPropertyCanNotBeMapped(Method method, PropertyMapping property) {
if ( property.getSourceType().equals( property.getTargetType() ) ||
property.getMappingMethod() != null ||
property.getConversion() != null ||
property.getTargetType().getImplementationType() != null ) {
return;
}
messager.printMessage(
Kind.ERROR,
String.format(
"Can't map property \"%s %s\" to \"%s %s\".",
property.getSourceType().getName(),
property.getSourceName(),
property.getTargetType().getName(),
property.getTargetName()
),
method.getExecutable()
);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
List<ExecutableElement> sourceSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor(
getterMethod,
sourceSetters
);
ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor(
setterMethod,
targetGetters
);
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null,
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null,
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
|
#vulnerable code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
List<ExecutableElement> sourceSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
);
reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters );
for ( ExecutableElement getterMethod : sourceGetters ) {
String sourcePropertyName = Executables.getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : targetSetters ) {
String targetPropertyName = Executables.getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
getterMethod.getSimpleName().toString(),
Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters )
.getSimpleName()
.toString(),
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters )
.getSimpleName()
.toString(),
setterMethod.getSimpleName().toString(),
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
#location 43
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences,
List<SourceMethod> methods,
SourceMethod method,
Parameter parameter,
ExecutableElement sourceAccessor,
ExecutableElement targetAcessor,
String dateFormat) {
Type sourceType = typeFactory.getReturnType( sourceAccessor );
Type targetType = null;
String conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()";
if ( Executables.isSetterMethod( targetAcessor ) ) {
targetType = typeFactory.getSingleParameter( targetAcessor ).getType();
}
else if ( Executables.isGetterMethod( targetAcessor ) ) {
targetType = typeFactory.getReturnType( targetAcessor );
}
String targetPropertyName = Executables.getPropertyName( targetAcessor );
String mappedElement = "property '" + Executables.getPropertyName( sourceAccessor ) + "'";
ParameterAssignment parameterAssignment = mappingResolver.getParameterAssignment(
method,
mappedElement,
mapperReferences,
methods,
sourceType,
targetType,
targetPropertyName,
dateFormat,
conversionString
);
PropertyMapping property = new PropertyMapping(
parameter.getName(),
Executables.getPropertyName( sourceAccessor ),
sourceAccessor.getSimpleName().toString(),
sourceType,
Executables.getPropertyName( targetAcessor ),
targetAcessor.getSimpleName().toString(),
targetType,
parameterAssignment != null ? parameterAssignment.getMethodReference() : null,
parameterAssignment != null ? parameterAssignment.getTypeConversion() : null
);
if ( !isPropertyMappable( property ) ) {
messager.printMessage(
Kind.ERROR,
String.format(
"Can't map property \"%s %s\" to \"%s %s\".",
property.getSourceType(),
property.getSourceName(),
property.getTargetType(),
property.getTargetName()
),
method.getExecutable()
);
}
return property;
}
|
#vulnerable code
private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences,
List<SourceMethod> methods,
SourceMethod method,
Parameter parameter,
ExecutableElement sourceAccessor,
ExecutableElement targetAcessor,
String dateFormat) {
Type sourceType = typeFactory.getReturnType( sourceAccessor );
Type targetType = null;
String conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()";
if ( Executables.isSetterMethod( targetAcessor ) ) {
targetType = typeFactory.getSingleParameter( targetAcessor ).getType();
}
else if ( Executables.isGetterMethod( targetAcessor ) ) {
targetType = typeFactory.getReturnType( targetAcessor );
}
String targetPropertyName = Executables.getPropertyName( targetAcessor );
String mappedElement = "property '" + Executables.getPropertyName( sourceAccessor ) + "'";
MethodReference mappingMethodReference = mappingMethodResolver.getMappingMethodReferenceBasedOnMethod(
method,
mappedElement,
mapperReferences,
methods,
sourceType,
targetType,
targetPropertyName,
dateFormat
);
TypeConversion conversion = mappingMethodResolver.getConversion(
sourceType,
targetType,
dateFormat,
conversionString
);
PropertyMapping property = new PropertyMapping(
parameter.getName(),
Executables.getPropertyName( sourceAccessor ),
sourceAccessor.getSimpleName().toString(),
sourceType,
Executables.getPropertyName( targetAcessor ),
targetAcessor.getSimpleName().toString(),
targetType,
mappingMethodReference,
conversion
);
if ( !isPropertyMappable( property ) ) {
// when not mappable, try again with another property mapping method based on parameter only.
mappingMethodReference = mappingMethodResolver.getMappingMethodReferenceBasedOnParameter(
method,
"property '" + Executables.getPropertyName( sourceAccessor ) + "'",
mapperReferences,
methods,
sourceType,
targetType,
targetPropertyName,
dateFormat
);
property = new PropertyMapping(
parameter.getName(),
Executables.getPropertyName( sourceAccessor ),
sourceAccessor.getSimpleName().toString(),
sourceType,
Executables.getPropertyName( targetAcessor ),
targetAcessor.getSimpleName().toString(),
targetType,
mappingMethodReference,
conversion
);
}
if ( !isPropertyMappable( property ) ) {
messager.printMessage(
Kind.ERROR,
String.format(
"Can't map property \"%s %s\" to \"%s %s\".",
property.getSourceType(),
property.getSourceName(),
property.getTargetType(),
property.getTargetName()
),
method.getExecutable()
);
}
return property;
}
#location 32
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Type getType(TypeMirror mirror, boolean isLiteral) {
if ( !canBeProcessed( mirror ) ) {
throw new TypeHierarchyErroneousException( mirror );
}
ImplementationType implementationType = getImplementationType( mirror );
boolean isIterableType = typeUtils.isSubtype( mirror, iterableType );
boolean isCollectionType = typeUtils.isSubtype( mirror, collectionType );
boolean isMapType = typeUtils.isSubtype( mirror, mapType );
boolean isStreamType = streamType != null && typeUtils.isSubtype( mirror, streamType );
boolean isEnumType;
boolean isInterface;
String name;
String packageName;
String qualifiedName;
TypeElement typeElement;
Type componentType;
Boolean toBeImported = null;
if ( mirror.getKind() == TypeKind.DECLARED ) {
DeclaredType declaredType = (DeclaredType) mirror;
isEnumType = declaredType.asElement().getKind() == ElementKind.ENUM;
isInterface = declaredType.asElement().getKind() == ElementKind.INTERFACE;
name = declaredType.asElement().getSimpleName().toString();
typeElement = (TypeElement) declaredType.asElement();
if ( typeElement != null ) {
packageName = elementUtils.getPackageOf( typeElement ).getQualifiedName().toString();
qualifiedName = typeElement.getQualifiedName().toString();
}
else {
packageName = null;
qualifiedName = name;
}
componentType = null;
}
else if ( mirror.getKind() == TypeKind.ARRAY ) {
TypeMirror componentTypeMirror = getComponentType( mirror );
StringBuilder builder = new StringBuilder("[]");
while ( componentTypeMirror.getKind() == TypeKind.ARRAY ) {
componentTypeMirror = getComponentType( componentTypeMirror );
builder.append( "[]" );
}
if ( componentTypeMirror.getKind() == TypeKind.DECLARED ) {
DeclaredType declaredType = (DeclaredType) componentTypeMirror;
TypeElement componentTypeElement = (TypeElement) declaredType.asElement();
String arraySuffix = builder.toString();
name = componentTypeElement.getSimpleName().toString() + arraySuffix;
packageName = elementUtils.getPackageOf( componentTypeElement ).getQualifiedName().toString();
qualifiedName = componentTypeElement.getQualifiedName().toString() + arraySuffix;
}
else if (componentTypeMirror.getKind().isPrimitive()) {
// When the component type is primitive and is annotated with ElementType.TYPE_USE then
// the typeMirror#toString returns (@CustomAnnotation :: byte) for the javac compiler
name = NativeTypes.getName( componentTypeMirror.getKind() ) + builder.toString();
packageName = null;
// for primitive types only name (e.g. byte, short..) required as qualified name
qualifiedName = name;
toBeImported = false;
}
else {
name = mirror.toString();
packageName = null;
qualifiedName = name;
toBeImported = false;
}
isEnumType = false;
isInterface = false;
typeElement = null;
componentType = getType( getComponentType( mirror ) );
}
else {
isEnumType = false;
isInterface = false;
// When the component type is primitive and is annotated with ElementType.TYPE_USE then
// the typeMirror#toString returns (@CustomAnnotation :: byte) for the javac compiler
name = mirror.getKind().isPrimitive() ? NativeTypes.getName( mirror.getKind() ) : mirror.toString();
packageName = null;
qualifiedName = name;
typeElement = null;
componentType = null;
toBeImported = false;
}
return new Type(
typeUtils, elementUtils, this,
roundContext.getAnnotationProcessorContext().getAccessorNaming(),
mirror,
typeElement,
getTypeParameters( mirror, false ),
implementationType,
componentType,
packageName,
name,
qualifiedName,
isInterface,
isEnumType,
isIterableType,
isCollectionType,
isMapType,
isStreamType,
toBeImportedTypes,
notToBeImportedTypes,
toBeImported,
isLiteral,
loggingVerbose
);
}
|
#vulnerable code
private Type getType(TypeMirror mirror, boolean isLiteral) {
if ( !canBeProcessed( mirror ) ) {
throw new TypeHierarchyErroneousException( mirror );
}
ImplementationType implementationType = getImplementationType( mirror );
boolean isIterableType = typeUtils.isSubtype( mirror, iterableType );
boolean isCollectionType = typeUtils.isSubtype( mirror, collectionType );
boolean isMapType = typeUtils.isSubtype( mirror, mapType );
boolean isStreamType = streamType != null && typeUtils.isSubtype( mirror, streamType );
boolean isEnumType;
boolean isInterface;
String name;
String packageName;
String qualifiedName;
TypeElement typeElement;
Type componentType;
Boolean toBeImported = null;
if ( mirror.getKind() == TypeKind.DECLARED ) {
DeclaredType declaredType = (DeclaredType) mirror;
isEnumType = declaredType.asElement().getKind() == ElementKind.ENUM;
isInterface = declaredType.asElement().getKind() == ElementKind.INTERFACE;
name = declaredType.asElement().getSimpleName().toString();
typeElement = (TypeElement) declaredType.asElement();
if ( typeElement != null ) {
packageName = elementUtils.getPackageOf( typeElement ).getQualifiedName().toString();
qualifiedName = typeElement.getQualifiedName().toString();
}
else {
packageName = null;
qualifiedName = name;
}
componentType = null;
}
else if ( mirror.getKind() == TypeKind.ARRAY ) {
TypeMirror componentTypeMirror = getComponentType( mirror );
StringBuilder builder = new StringBuilder("[]");
while ( componentTypeMirror.getKind() == TypeKind.ARRAY ) {
componentTypeMirror = getComponentType( componentTypeMirror );
builder.append( "[]" );
}
if ( componentTypeMirror.getKind() == TypeKind.DECLARED ) {
DeclaredType declaredType = (DeclaredType) componentTypeMirror;
TypeElement componentTypeElement = (TypeElement) declaredType.asElement();
String arraySuffix = builder.toString();
name = componentTypeElement.getSimpleName().toString() + arraySuffix;
packageName = elementUtils.getPackageOf( componentTypeElement ).getQualifiedName().toString();
qualifiedName = componentTypeElement.getQualifiedName().toString() + arraySuffix;
}
else if (componentTypeMirror.getKind().isPrimitive()) {
// When the component type is primitive and is annotated with ElementType.TYPE_USE then
// the typeMirror#toString returns (@CustomAnnotation :: byte) for the javac compiler
name = NativeTypes.getName( componentTypeMirror.getKind() ) + builder.toString();
packageName = null;
// for primitive types only name (e.g. byte, short..) required as qualified name
qualifiedName = name;
toBeImported = false;
}
else {
name = mirror.toString();
packageName = null;
qualifiedName = name;
toBeImported = false;
}
isEnumType = false;
isInterface = false;
typeElement = null;
componentType = getType( getComponentType( mirror ) );
}
else {
isEnumType = false;
isInterface = false;
name = mirror.toString();
packageName = null;
qualifiedName = name;
typeElement = null;
componentType = null;
toBeImported = false;
}
return new Type(
typeUtils, elementUtils, this,
roundContext.getAnnotationProcessorContext().getAccessorNaming(),
mirror,
typeElement,
getTypeParameters( mirror, false ),
implementationType,
componentType,
packageName,
name,
qualifiedName,
isInterface,
isEnumType,
isIterableType,
isCollectionType,
isMapType,
isStreamType,
toBeImportedTypes,
notToBeImportedTypes,
toBeImported,
isLiteral,
loggingVerbose
);
}
#location 46
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
Element returnTypeElement = typeUtils.asElement( method.getReturnType() );
Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
for ( ExecutableElement getterMethod : getterMethodsIn( parameterElement.getEnclosedElements() ) ) {
String sourcePropertyName = getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : setterMethodsIn( returnTypeElement.getEnclosedElements() ) ) {
String targetPropertyName = getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
retrieveParameter( setterMethod ).getType(),
mapping != null ? mapping.getConverterType() : null
)
);
}
}
}
return properties;
}
|
#vulnerable code
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
Element returnTypeElement = typeUtils.asElement( method.getReturnType() );
Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
for ( ExecutableElement getterMethod : getterMethodsIn( parameterElement.getEnclosedElements() ) ) {
String sourcePropertyName = Introspector.decapitalize(
getterMethod.getSimpleName()
.toString()
.substring( 3 )
);
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : setterMethodsIn( returnTypeElement.getEnclosedElements() ) ) {
String targetPropertyName = Introspector.decapitalize(
setterMethod.getSimpleName()
.toString()
.substring( 3 )
);
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
retrieveParameter( setterMethod ).getType(),
mapping != null ? mapping.getConverterType() : null
)
);
}
}
}
return properties;
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index);
try {
return new ArrayBuffer(buffer.getBackingStore());
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toTypedArray(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
|
#vulnerable code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toTypedArray(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
#location 33
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) {
if (!nativeLibraryLoaded) {
synchronized (lock) {
if (!nativeLibraryLoaded) {
load(tempDirectory);
}
}
}
checkNativeLibraryLoaded();
if (!initialized) {
_setFlags(v8Flags);
initialized = true;
}
V8 runtime = new V8(globalAlias);
synchronized (lock) {
runtimeCounter++;
}
return runtime;
}
|
#vulnerable code
public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) {
if (!nativeLibraryLoaded) {
synchronized (lock) {
if (!nativeLibraryLoaded) {
load(tempDirectory);
}
}
}
checkNativeLibraryLoaded();
if (!initialized) {
_setFlags(v8Flags);
initialized = true;
}
if (debugThread == null) {
debugThread = Thread.currentThread();
}
V8 runtime = new V8(globalAlias);
synchronized (lock) {
runtimeCounter++;
}
return runtime;
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
|
#vulnerable code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
if (debugEnabled) {
disableDebugSupport();
}
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void release(final boolean reportMemoryLeaks) {
checkThread();
if (isReleased()) {
return;
}
if (debugEnabled) {
disableDebugSupport();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
|
#vulnerable code
public void release(final boolean reportMemoryLeaks) {
checkThread();
if (isReleased()) {
return;
}
if (debugEnabled) {
disableDebugSupport();
}
runtimeCounter--;
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) {
int valueType = object.getType(key);
switch (valueType) {
case V8Value.INTEGER:
return object.getInteger(key);
case V8Value.DOUBLE:
return object.getDouble(key);
case V8Value.BOOLEAN:
return object.getBoolean(key);
case V8Value.STRING:
return object.getString(key);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) object.get(key);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = object.getArray(key);
try {
return toTypedArray(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array array = object.getArray(key);
try {
return toList(array, cache);
} finally {
if (array instanceof V8Array) {
array.release();
}
}
case V8Value.V8_OBJECT:
V8Object child = object.getObject(key);
try {
return toMap(child, cache);
} finally {
if (child instanceof V8Object) {
child.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for key: " + key);
}
}
|
#vulnerable code
private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) {
int valueType = object.getType(key);
switch (valueType) {
case V8Value.INTEGER:
return object.getInteger(key);
case V8Value.DOUBLE:
return object.getDouble(key);
case V8Value.BOOLEAN:
return object.getBoolean(key);
case V8Value.STRING:
return object.getString(key);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) object.get(key);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = object.getArray(key);
try {
return toByteBuffer(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array array = object.getArray(key);
try {
return toList(array, cache);
} finally {
if (array instanceof V8Array) {
array.release();
}
}
case V8Value.V8_OBJECT:
V8Object child = object.getObject(key);
try {
return toMap(child, cache);
} finally {
if (child instanceof V8Object) {
child.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for key: " + key);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) {
if (!nativeLibraryLoaded) {
synchronized (lock) {
if (!nativeLibraryLoaded) {
load(tempDirectory);
}
}
}
checkNativeLibraryLoaded();
if (!initialized) {
_setFlags(v8Flags);
initialized = true;
}
V8 runtime = new V8(globalAlias);
synchronized (lock) {
runtimeCounter++;
}
return runtime;
}
|
#vulnerable code
public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) {
if (!nativeLibraryLoaded) {
synchronized (lock) {
if (!nativeLibraryLoaded) {
load(tempDirectory);
}
}
}
checkNativeLibraryLoaded();
if (!initialized) {
_setFlags(v8Flags);
initialized = true;
}
if (debugThread == null) {
debugThread = Thread.currentThread();
}
V8 runtime = new V8(globalAlias);
synchronized (lock) {
runtimeCounter++;
}
return runtime;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toTypedArray(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
|
#vulnerable code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toByteBuffer(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
try {
notifyReleaseHandlers(this);
} finally {
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
releaseNativeMethodDescriptors();
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (getObjectReferenceCount() > 0)) {
throw new IllegalStateException(getObjectReferenceCount() + " Object(s) still exist in runtime");
}
}
}
|
#vulnerable code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
try {
notifyReleaseHandlers(this);
} finally {
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
releaseNativeMethodDescriptors();
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (getObjectReferenceCount() > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toByteBuffer(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
|
#vulnerable code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return ((V8TypedArray) typedArray).getByteBuffer();
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testTypedArrayGetValue_Float32Array() {
V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(100);\n"
+ "var floatsArray = new Float32Array(buf);\n"
+ "floatsArray[0] = 16.2;\n"
+ "floatsArray;\n");
V8TypedArray result = ((TypedArray) V8ObjectUtils.getValue(floatsArray)).getV8TypedArray();
assertEquals(25, result.length());
assertEquals(16.2, (Float) result.get(0), 0.00001);
floatsArray.close();
result.close();
}
|
#vulnerable code
@Test
public void testTypedArrayGetValue_Float32Array() {
V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(100);\n"
+ "var floatsArray = new Float32Array(buf);\n"
+ "floatsArray[0] = 16.2;\n"
+ "floatsArray;\n");
V8TypedArray result = (V8TypedArray) V8ObjectUtils.getValue(floatsArray);
assertEquals(25, result.length());
assertEquals(16.2, (Float) result.get(0), 0.00001);
floatsArray.close();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) {
int valueType = object.getType(key);
switch (valueType) {
case V8Value.INTEGER:
return object.getInteger(key);
case V8Value.DOUBLE:
return object.getDouble(key);
case V8Value.BOOLEAN:
return object.getBoolean(key);
case V8Value.STRING:
return object.getString(key);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) object.get(key);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = object.getArray(key);
try {
return toByteBuffer(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array array = object.getArray(key);
try {
return toList(array, cache);
} finally {
if (array instanceof V8Array) {
array.release();
}
}
case V8Value.V8_OBJECT:
V8Object child = object.getObject(key);
try {
return toMap(child, cache);
} finally {
if (child instanceof V8Object) {
child.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for key: " + key);
}
}
|
#vulnerable code
private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) {
int valueType = object.getType(key);
switch (valueType) {
case V8Value.INTEGER:
return object.getInteger(key);
case V8Value.DOUBLE:
return object.getDouble(key);
case V8Value.BOOLEAN:
return object.getBoolean(key);
case V8Value.STRING:
return object.getString(key);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = object.getArray(key);
try {
return toByteBuffer(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array array = object.getArray(key);
try {
return toList(array, cache);
} finally {
if (array instanceof V8Array) {
array.release();
}
}
case V8Value.V8_OBJECT:
V8Object child = object.getObject(key);
try {
return toMap(child, cache);
} finally {
if (child instanceof V8Object) {
child.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for key: " + key);
}
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
|
#vulnerable code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
if (debugEnabled) {
disableDebugSupport();
}
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testTypedArrayGetValue_Float64Array() {
V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n"
+ "var floatsArray = new Float64Array(buf);\n"
+ "floatsArray[0] = 16.2;\n"
+ "floatsArray;\n");
V8TypedArray result = ((TypedArray) V8ObjectUtils.getValue(floatsArray)).getV8TypedArray();
assertEquals(10, result.length());
assertEquals(16.2, (Double) result.get(0), 0.0001);
floatsArray.close();
result.close();
}
|
#vulnerable code
@Test
public void testTypedArrayGetValue_Float64Array() {
V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n"
+ "var floatsArray = new Float64Array(buf);\n"
+ "floatsArray[0] = 16.2;\n"
+ "floatsArray;\n");
V8TypedArray result = (V8TypedArray) V8ObjectUtils.getValue(floatsArray);
assertEquals(10, result.length());
assertEquals(16.2, (Double) result.get(0), 0.0001);
floatsArray.close();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) {
int valueType = object.getType(key);
switch (valueType) {
case V8Value.INTEGER:
return object.getInteger(key);
case V8Value.DOUBLE:
return object.getDouble(key);
case V8Value.BOOLEAN:
return object.getBoolean(key);
case V8Value.STRING:
return object.getString(key);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = object.getArray(key);
try {
return toByteBuffer(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array array = object.getArray(key);
try {
return toList(array, cache);
} finally {
if (array instanceof V8Array) {
array.release();
}
}
case V8Value.V8_OBJECT:
V8Object child = object.getObject(key);
try {
return toMap(child, cache);
} finally {
if (child instanceof V8Object) {
child.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for key: " + key);
}
}
|
#vulnerable code
private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) {
int valueType = object.getType(key);
switch (valueType) {
case V8Value.INTEGER:
return object.getInteger(key);
case V8Value.DOUBLE:
return object.getDouble(key);
case V8Value.BOOLEAN:
return object.getBoolean(key);
case V8Value.STRING:
return object.getString(key);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = object.getArray(key);
try {
return ((V8TypedArray) typedArray).getByteBuffer();
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array array = object.getArray(key);
try {
return toList(array, cache);
} finally {
if (array instanceof V8Array) {
array.release();
}
}
case V8Value.V8_OBJECT:
V8Object child = object.getObject(key);
try {
return toMap(child, cache);
} finally {
if (child instanceof V8Object) {
child.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for key: " + key);
}
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean enableDebugSupport(final int port, final boolean waitForConnection) {
V8.checkDebugThread();
debugEnabled = enableDebugSupport(getV8RuntimePtr(), port, waitForConnection);
return debugEnabled;
}
|
#vulnerable code
public boolean enableDebugSupport(final int port, final boolean waitForConnection) {
V8.checkDebugThread();
debugEnabled = enableDebugSupport(getHandle(), port, waitForConnection);
return debugEnabled;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public CommandLine parse(final String[] args) throws ParseException, IllegalArgumentException {
final CommandLine cmd = super.parse(args);
final String[] files = cmd.getArgs();
if (files.length > 1) {
throw new IllegalArgumentException("Only one dump file path may be passed at a time.");
}
final Report report = ReportFactory.createReport(cmd, ReportType.REDIS);
final OutputStream output;
// Write to stdout if no path is specified.
if (0 == files.length) {
logger.info("No path given. Writing to standard output.");
output = System.out;
} else {
try {
output = new FileOutputStream(files[0]);
} catch (FileNotFoundException e) {
throw new RuntimeException("Unable to open dump file for writing.", e);
}
}
ExtractionResult match = null;
if (cmd.hasOption("reporter-status")) {
match = ExtractionResult.get(((Number) cmd.getParsedOptionValue("reporter-status")));
if (null == match) {
throw new IllegalArgumentException(String.format("%s is not a valid report status.",
cmd.getOptionValue("reporter-status")));
}
}
final ProgressBar progressBar = ConsoleProgressBar.on(System.err)
.withFormat("[:bar] :percent% :elapsed/:total ETA: :eta")
.withTotalSteps(report.size());
final ObjectMapper mapper = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addSerializer(Report.class, new ReportSerializer(progressBar, match));
mapper.registerModule(module);
try (
final JsonGenerator jsonGenerator = new JsonFactory()
.setCodec(mapper)
.createGenerator(output, JsonEncoding.UTF8)
) {
jsonGenerator.useDefaultPrettyPrinter();
jsonGenerator.writeObject(report);
jsonGenerator.writeRaw('\n');
} catch (IOException e) {
throw new RuntimeException("Unable to output JSON.", e);
}
try {
report.close();
} catch (IOException e) {
throw new RuntimeException("Exception while closing report.", e);
}
return cmd;
}
|
#vulnerable code
public CommandLine parse(final String[] args) throws ParseException, IllegalArgumentException {
final CommandLine cmd = super.parse(args);
final Report report = ReportFactory.createReport(cmd, ReportType.REDIS);
ExtractionResult match = null;
if (cmd.hasOption("reporter-status")) {
match = ExtractionResult.get(((Number) cmd.getParsedOptionValue("reporter-status")));
if (null == match) {
throw new IllegalArgumentException(String.format("%s is not a valid report status.",
cmd.getOptionValue("reporter-status")));
}
}
final ProgressBar progressBar = ConsoleProgressBar.on(System.err)
.withFormat("[:bar] :percent% :elapsed/:total ETA: :eta")
.withTotalSteps(report.size());
final ObjectMapper mapper = new ObjectMapper();
final SimpleModule module = new SimpleModule();
module.addSerializer(Report.class, new ReportSerializer(progressBar, match));
mapper.registerModule(module);
try (
final JsonGenerator jsonGenerator = new JsonFactory()
.setCodec(mapper)
.createGenerator(System.out, JsonEncoding.UTF8)
) {
jsonGenerator.useDefaultPrettyPrinter();
jsonGenerator.writeObject(report);
jsonGenerator.writeRaw('\n');
} catch (IOException e) {
throw new RuntimeException("Unable to output JSON.", e);
}
try {
report.close();
} catch (IOException e) {
throw new RuntimeException("Exception while closing report.", e);
}
return cmd;
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
public void run() {
// restart the clock.
this.rowMerger = new RowMerger(rowObserver);
adapter = new CallToStreamObserverAdapter();
synchronized (callLock) {
super.run();
// pre-fetch one more result, for performance reasons.
adapter.request(1);
if (rowObserver instanceof ClientResponseObserver) {
((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter);
}
lastResponseMs = clock.currentTimeMillis();
}
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
public void run() {
// restart the clock.
lastResponseMs = clock.currentTimeMillis();
this.rowMerger = new RowMerger(rowObserver);
synchronized (callLock) {
super.run();
// pre-fetch one more result, for performance reasons.
adapter = new CallToStreamObserverAdapter<ReadRowsRequest>(call);
adapter.request(1);
if (rowObserver instanceof ClientResponseObserver) {
((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter);
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Test
public void testMutation() throws IOException, InterruptedException {
when(mockClient.mutateRowAsync(any(MutateRowRequest.class)))
.thenReturn(mockFuture);
BigtableBufferedMutator underTest = createMutator(new Configuration(false));
underTest.mutate(SIMPLE_PUT);
Assert.assertTrue(underTest.hasInflightRequests());
// Leave some time for the async worker to handle the request.
Thread.sleep(100);
verify(mockClient, times(1)).mutateRowAsync(any(MutateRowRequest.class));
Assert.assertTrue(underTest.hasInflightRequests());
completeCall();
Assert.assertFalse(underTest.hasInflightRequests());
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Test
public void testMutation() throws IOException, InterruptedException {
final ReentrantLock lock = new ReentrantLock();
final Condition mutateRowAsyncCalled = lock.newCondition();
when(mockClient.mutateRowAsync(any(MutateRowRequest.class)))
.thenAnswer(
new Answer<ListenableFuture<Empty>>() {
@Override
public ListenableFuture<Empty> answer(InvocationOnMock invocation) throws Throwable {
lock.lock();
try {
mutateRowAsyncCalled.signalAll();
return mockFuture;
} finally {
lock.unlock();
}
}
});
BigtableBufferedMutator underTest = createMutator(new Configuration(false));
underTest.mutate(SIMPLE_PUT);
Assert.assertTrue(underTest.hasInflightRequests());
// Leave some time for the async worker to handle the request.
lock.lock();
try {
mutateRowAsyncCalled.await(100, TimeUnit.SECONDS);
} finally {
lock.unlock();
}
verify(mockClient, times(1)).mutateRowAsync(any(MutateRowRequest.class));
Assert.assertTrue(underTest.hasInflightRequests());
completeCall();
Assert.assertFalse(underTest.hasInflightRequests());
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static Credentials getCredentialFromPrivateKeyServiceAccount(
String serviceAccountEmail, String privateKeyFile, List<String> scopes)
throws IOException, GeneralSecurityException {
PrivateKey privateKey =
SecurityUtils.loadPrivateKeyFromKeyStore(
SecurityUtils.getPkcs12KeyStore(),
new FileInputStream(privateKeyFile),
"notasecret",
"privatekey",
"notasecret");
// Since the user specified scopes, we can't use JWT tokens
return patchCredentials(
ServiceAccountCredentials.newBuilder()
.setClientEmail(serviceAccountEmail)
.setPrivateKey(privateKey)
.setScopes(scopes)
.setHttpTransportFactory(getHttpTransportFactory())
.build());
}
|
#vulnerable code
public static Credentials getCredentialFromPrivateKeyServiceAccount(
String serviceAccountEmail, String privateKeyFile, List<String> scopes)
throws IOException, GeneralSecurityException {
PrivateKey privateKey =
SecurityUtils.loadPrivateKeyFromKeyStore(
SecurityUtils.getPkcs12KeyStore(),
new FileInputStream(privateKeyFile),
"notasecret",
"privatekey",
"notasecret");
// Since the user specified scopes, we can't use JWT tokens
return ServiceAccountCredentials.newBuilder()
.setClientEmail(serviceAccountEmail)
.setPrivateKey(privateKey)
.setScopes(scopes)
.setHttpTransportFactory(getHttpTransportFactory())
.build();
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testRefresh() throws IOException {
Mockito.when(mockCredentials.refreshAccessToken()).thenReturn(
new AccessToken("", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)));
underTest = new RefreshingOAuth2CredentialsInterceptor(MoreExecutors.newDirectExecutorService(),
mockCredentials);
underTest.getHeaderSafe();
Assert.assertEquals(CacheState.Good, underTest.getCacheState());
Assert.assertFalse(underTest.isRefreshing());
}
|
#vulnerable code
@Test
public void testRefresh() throws IOException {
Mockito.when(credentials.refreshAccessToken()).thenReturn(
new AccessToken("", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)));
underTest = new RefreshingOAuth2CredentialsInterceptor(MoreExecutors.newDirectExecutorService(),
credentials);
underTest.syncRefresh();
Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState());
Assert.assertFalse(underTest.isRefreshing());
}
#location 8
#vulnerability type UNSAFE_GUARDED_BY_ACCESS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
/**
* Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh
* logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it
* triggers a call to syncRefresh() which potentially waits for refresh that was initiated
* from another thread either through syncRefresh() or asyncRefresh(). This test case simulates
* that condition.
*/
public void testRefreshDoesntHang() throws Exception,
TimeoutException {
// Assume that the user starts at this time... it's an arbitrarily big number which will
// assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not
// be negative.
long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10;
setTime(start);
// RefreshingOAuth2CredentialsInterceptor will show that the access token is stale.
final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1;
// Create a mechanism that will allow us to control when the accessToken is returned.
// credentials.refreshAccessToken() will get called asynchronously and will wait until the
// lock is notified before returning. That will allow us to set up multiple concurrent calls
final Object lock = new String("");
Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() {
@Override
public AccessToken answer(InvocationOnMock invocation) throws Throwable {
synchronized (lock) {
lock.wait();
}
return new AccessToken("", new Date(expiration));
}
});
// Force a synchronous refresh. This ought to wait until a refresh happening in another thread
// completes.
Callable<Void> syncRefreshCallable = new Callable<Void>() {
@Override
public Void call() throws Exception {
underTest.syncRefresh();
return null;
}
};
underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials);
// At this point, the access token wasn't retrieved yet. The
// RefreshingOAuth2CredentialsInterceptor considers null to be Expired.
Assert.assertEquals(CacheState.Expired,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
syncCall(lock, syncRefreshCallable);
// Check to make sure that the AccessToken was retrieved.
Assert.assertEquals(CacheState.Stale,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
// Check to make sure we're no longer refreshing.
Assert.assertFalse(underTest.isRefreshing.get());
// Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be
// necessary, but also should not be harmful, since there are likely to be multiple concurrent
// requests that call asyncRefresh() when the token turns stale.
underTest.asyncRefresh();
underTest.asyncRefresh();
underTest.asyncRefresh();
syncCall(lock, syncRefreshCallable);
Assert.assertFalse(underTest.isRefreshing.get());
}
|
#vulnerable code
@Test
/**
* Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh
* logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it
* triggers a call to syncRefresh() which potentially waits for refresh that was initiated
* from another thread either through syncRefresh() or asyncRefresh(). This test case simulates
* that condition.
*/
public void testRefreshDoesntHang() throws Exception,
TimeoutException {
// Assume that the user starts at this time... it's an arbitrarily big number which will
// assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not
// be negative.
long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10;
setTime(start);
// RefreshingOAuth2CredentialsInterceptor will show that the access token is stale.
final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1;
// Create a mechanism that will allow us to control when the accessToken is returned.
// credentials.refreshAccessToken() will get called asynchronously and will wait until the
// lock is notified before returning. That will allow us to set up multiple concurrent calls
final Object lock = new String("");
Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() {
@Override
public AccessToken answer(InvocationOnMock invocation) throws Throwable {
synchronized (lock) {
lock.wait();
}
return new AccessToken("", new Date(expiration));
}
});
// Force a synchronous refresh. This ought to wait until a refresh happening in another thread
// completes.
Callable<Void> syncRefreshCallable = new Callable<Void>() {
@Override
public Void call() throws Exception {
underTest.syncRefresh();
return null;
}
};
underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials);
// At this point, the access token wasn't retrieved yet. The
// RefreshingOAuth2CredentialsInterceptor considers null to be Expired.
Assert.assertEquals(CacheState.Expired,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
Future<Void> future = executorService.submit(syncRefreshCallable);
// let the Thread running syncRefreshCallable() have a turn so that it can initiate the call
// to refreshAccessToken().
Thread.yield();
synchronized(lock) {
lock.notifyAll();
}
// Try to get the access token, which should be calculated at this point. There's
// a possibility that some hanging occurs in the test code. If the operation times out
// so timeout after 1 second, this will throw a TimeoutException.
future.get(1, TimeUnit.SECONDS);
// Check to make sure that the AccessToken was retrieved.
Assert.assertEquals(CacheState.Stale,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
// Check to make sure we're no longer refreshing.
Assert.assertFalse(underTest.isRefreshing.get());
// Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be
// necessary, but also should not be harmful, since there are likely to be multiple concurrent
// requests that call asyncRefresh() when the token turns stale.
underTest.asyncRefresh();
underTest.asyncRefresh();
underTest.asyncRefresh();
future = executorService.submit(syncRefreshCallable);
// Let the asyncRefreshes do their thing.
Thread.yield();
// There should be a single thread kicked off by the underTest.asyncRefresh() calls about
// actually doing a refresh at this point; the other ones will have see that a refresh is in
// progress and finish the invocation of the Thread without performing a refres().. Make sure
// that at least 1 refresh process is in progress.
Assert.assertTrue(underTest.isRefreshing.get());
synchronized(lock) {
// Release the lock so that all of the async refreshing can complete.
lock.notifyAll();
}
// Wait for no more than a second to make sure that the call to underTest.syncRefresh()
// completes properly. If a second passes without syncRefresh() completing, future.get(..)
// will throw a TimeoutException.
future.get(1, TimeUnit.SECONDS);
Assert.assertFalse(underTest.isRefreshing.get());
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
/**
* Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh
* logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it
* triggers a call to syncRefresh() which potentially waits for refresh that was initiated
* from another thread either through syncRefresh() or asyncRefresh(). This test case simulates
* that condition.
*/
public void testRefreshDoesntHang() throws Exception,
TimeoutException {
// Assume that the user starts at this time... it's an arbitrarily big number which will
// assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not
// be negative.
long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10;
setTime(start);
// RefreshingOAuth2CredentialsInterceptor will show that the access token is stale.
final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1;
// Create a mechanism that will allow us to control when the accessToken is returned.
// credentials.refreshAccessToken() will get called asynchronously and will wait until the
// lock is notified before returning. That will allow us to set up multiple concurrent calls
final Object lock = new String("");
Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() {
@Override
public AccessToken answer(InvocationOnMock invocation) throws Throwable {
synchronized (lock) {
lock.wait();
}
return new AccessToken("", new Date(expiration));
}
});
// Force a synchronous refresh. This ought to wait until a refresh happening in another thread
// completes.
Callable<Void> syncRefreshCallable = new Callable<Void>() {
@Override
public Void call() throws Exception {
underTest.syncRefresh();
return null;
}
};
underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials);
// At this point, the access token wasn't retrieved yet. The
// RefreshingOAuth2CredentialsInterceptor considers null to be Expired.
Assert.assertEquals(CacheState.Expired,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
syncCall(lock, syncRefreshCallable);
// Check to make sure that the AccessToken was retrieved.
Assert.assertEquals(CacheState.Stale,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
// Check to make sure we're no longer refreshing.
Assert.assertFalse(underTest.isRefreshing.get());
// Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be
// necessary, but also should not be harmful, since there are likely to be multiple concurrent
// requests that call asyncRefresh() when the token turns stale.
underTest.asyncRefresh();
underTest.asyncRefresh();
underTest.asyncRefresh();
syncCall(lock, syncRefreshCallable);
Assert.assertFalse(underTest.isRefreshing.get());
}
|
#vulnerable code
@Test
/**
* Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh
* logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it
* triggers a call to syncRefresh() which potentially waits for refresh that was initiated
* from another thread either through syncRefresh() or asyncRefresh(). This test case simulates
* that condition.
*/
public void testRefreshDoesntHang() throws Exception,
TimeoutException {
// Assume that the user starts at this time... it's an arbitrarily big number which will
// assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not
// be negative.
long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10;
setTime(start);
// RefreshingOAuth2CredentialsInterceptor will show that the access token is stale.
final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1;
// Create a mechanism that will allow us to control when the accessToken is returned.
// credentials.refreshAccessToken() will get called asynchronously and will wait until the
// lock is notified before returning. That will allow us to set up multiple concurrent calls
final Object lock = new String("");
Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() {
@Override
public AccessToken answer(InvocationOnMock invocation) throws Throwable {
synchronized (lock) {
lock.wait();
}
return new AccessToken("", new Date(expiration));
}
});
// Force a synchronous refresh. This ought to wait until a refresh happening in another thread
// completes.
Callable<Void> syncRefreshCallable = new Callable<Void>() {
@Override
public Void call() throws Exception {
underTest.syncRefresh();
return null;
}
};
underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials);
// At this point, the access token wasn't retrieved yet. The
// RefreshingOAuth2CredentialsInterceptor considers null to be Expired.
Assert.assertEquals(CacheState.Expired,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
Future<Void> future = executorService.submit(syncRefreshCallable);
// let the Thread running syncRefreshCallable() have a turn so that it can initiate the call
// to refreshAccessToken().
Thread.yield();
synchronized(lock) {
lock.notifyAll();
}
// Try to get the access token, which should be calculated at this point. There's
// a possibility that some hanging occurs in the test code. If the operation times out
// so timeout after 1 second, this will throw a TimeoutException.
future.get(1, TimeUnit.SECONDS);
// Check to make sure that the AccessToken was retrieved.
Assert.assertEquals(CacheState.Stale,
RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get()));
// Check to make sure we're no longer refreshing.
Assert.assertFalse(underTest.isRefreshing.get());
// Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be
// necessary, but also should not be harmful, since there are likely to be multiple concurrent
// requests that call asyncRefresh() when the token turns stale.
underTest.asyncRefresh();
underTest.asyncRefresh();
underTest.asyncRefresh();
future = executorService.submit(syncRefreshCallable);
// Let the asyncRefreshes do their thing.
Thread.yield();
// There should be a single thread kicked off by the underTest.asyncRefresh() calls about
// actually doing a refresh at this point; the other ones will have see that a refresh is in
// progress and finish the invocation of the Thread without performing a refres().. Make sure
// that at least 1 refresh process is in progress.
Assert.assertTrue(underTest.isRefreshing.get());
synchronized(lock) {
// Release the lock so that all of the async refreshing can complete.
lock.notifyAll();
}
// Wait for no more than a second to make sure that the call to underTest.syncRefresh()
// completes properly. If a second passes without syncRefresh() completing, future.get(..)
// will throw a TimeoutException.
future.get(1, TimeUnit.SECONDS);
Assert.assertFalse(underTest.isRefreshing.get());
}
#location 70
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{
ServerSocket serverSocket = new ServerSocket(0);
final int availablePort = serverSocket.getLocalPort();
serverSocket.close();
//Creates non-ssl server.
createServer(availablePort);
BigtableOptions bigtableOptions =
BigtableOptions.builder()
.setDataHost("localhost")
.setAdminHost("localhost")
.setProjectId(TEST_PROJECT_ID)
.setInstanceId(TEST_INSTANCE_ID)
.setUserAgent(TEST_USER_AGENT)
.setUsePlaintextNegotiation(true)
.setCredentialOptions(CredentialOptions.nullCredential())
.setPort(availablePort)
.build();
xGoogApiPattern = Pattern.compile(".* cbt/.*");
try (BigtableSession session = new BigtableSession(bigtableOptions)) {
session.getClientWrapper()
.readFlatRows(Query.create("fake-table")).next();
Assert.assertTrue(serverPasses.get());
}
}
|
#vulnerable code
@Test
public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{
ServerSocket serverSocket = new ServerSocket(0);
final int availablePort = serverSocket.getLocalPort();
serverSocket.close();
//Creates non-ssl server.
createServer(availablePort);
BigtableOptions bigtableOptions =
BigtableOptions.builder()
.setDataHost("localhost")
.setAdminHost("localhost")
.setProjectId(TEST_PROJECT_ID)
.setInstanceId(TEST_INSTANCE_ID)
.setUserAgent(TEST_USER_AGENT)
.setUsePlaintextNegotiation(true)
.setCredentialOptions(CredentialOptions.nullCredential())
.setPort(availablePort)
.build();
xGoogApiPattern = Pattern.compile(".* cbt/.*");
try (BigtableSession session = new BigtableSession(bigtableOptions)) {
session.getDataClient()
.readFlatRows(ReadRowsRequest.getDefaultInstance()).next();
Assert.assertTrue(serverPasses.get());
}
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.