repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptFunctionApplyContextInterpreter.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ipa.callgraph.AstContextInsensitiveSSAContextInterpreter;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummarizedFunction;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummary;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
/**
* TODO cache generated IRs
*
* @see <a
* href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply">MDN
* Function.apply() docs</a>
*/
public class JavaScriptFunctionApplyContextInterpreter
extends AstContextInsensitiveSSAContextInterpreter {
private static final TypeName APPLY_TYPE_NAME =
TypeName.findOrCreate("Lprologue.js/Function_prototype_apply");
public JavaScriptFunctionApplyContextInterpreter(
AnalysisOptions options, IAnalysisCacheView cache) {
super(options, cache);
}
@Override
public boolean understands(CGNode node) {
return node.getMethod().getDeclaringClass().getName().equals(APPLY_TYPE_NAME);
}
@Override
public IR getIR(CGNode node) {
assert understands(node);
@SuppressWarnings("unchecked")
ContextItem.Value<Boolean> isNonNullArray =
(ContextItem.Value<Boolean>)
node.getContext().get(JavaScriptFunctionApplyContextSelector.APPLY_NON_NULL_ARGS);
// isNonNullArray can be null if, e.g., due to recursion bounding we have no
// information on the arguments parameter
if (isNonNullArray == null || isNonNullArray.getValue()) {
return makeIRForArgList(node);
} else {
return makeIRForNoArgList(node);
}
}
private static IR makeIRForArgList(CGNode node) {
// we have: v1 is dummy apply method
// v2 is function to be invoked
// v3 is argument to be passed as 'this'
// v4 is array containing remaining arguments
// Ideally, we would take advantage of cases like constant arrays and
// precisely pass arguments in the appropriate slots. Unfortunately, in the
// pointer analysis fixed-point computation, it's possible that we will
// process the apply() call and then process some update to the arguments
// array, reflected only in its property values and object catalog. Perhaps
// eventually, we could create contexts based on the catalog of the object
// and then do a better job, but since the catalog is not passed directly as
// a parameter to apply(), this is not so easy.
// In the meantime, we do things imprecisely. We read an arbitrary
// enumerable property name of the argument list (via an
// EachElementGetInstruction), perform a dynamic read of that property, and
// then pass the resulting values in all argument positions (except 'this').
//
// NOTE: we don't know how many arguments the callee will take, whether it
// uses
// the arguments array, etc. For now, we use an unsound hack and pass the
// argument 10 times.
//
// NOTE: strictly speaking, using EachElementGet could be imprecise, as it
// should
// return properties inherited via the prototype chain. However, since this
// behavior
// is not modeled in WALA as of now, using the instruction is ok.
MethodReference ref = node.getMethod().getReference();
IClass declaringClass = node.getMethod().getDeclaringClass();
JSInstructionFactory insts =
(JSInstructionFactory) declaringClass.getClassLoader().getInstructionFactory();
// nargs needs to match that of Function.apply(), even though no argsList
// argument was passed in this case
int nargs = 4;
JavaScriptSummary S = new JavaScriptSummary(ref, nargs);
int numParamsToPass = 10;
int[] paramsToPassToInvoked = new int[numParamsToPass + 1];
// pass the 'this' argument first
paramsToPassToInvoked[0] = 3;
// int curValNum = passArbitraryPropertyValAsParams(insts, nargs, S, paramsToPassToInvoked);
int curValNum = passActualPropertyValsAsParams(insts, nargs, S, paramsToPassToInvoked);
CallSiteReference cs =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNumberOfStatements());
// function being invoked is in v2
int resultVal = curValNum++;
int excVal = curValNum++;
S.addStatement(
insts.Invoke(S.getNumberOfStatements(), 2, resultVal, paramsToPassToInvoked, excVal, cs));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), resultVal, false));
S.getNumberOfStatements();
JavaScriptSummarizedFunction t = new JavaScriptSummarizedFunction(ref, S, declaringClass);
return t.makeIR(node.getContext(), null);
}
@SuppressWarnings("unused")
private static int passArbitraryPropertyValAsParams(
JSInstructionFactory insts, int nargs, JavaScriptSummary S, int[] paramsToPassToInvoked) {
// read an arbitrary property name via EachElementGet
int curValNum = nargs + 2;
int eachElementGetResult = curValNum++;
int nullPredVn = curValNum++;
S.addConstant(nullPredVn, new ConstantValue(null));
S.addStatement(
insts.EachElementGetInstruction(
S.getNumberOfStatements(), eachElementGetResult, 4, nullPredVn));
S.getNumberOfStatements();
// read value from the arbitrary property name
int propertyReadResult = curValNum++;
S.addStatement(
insts.PropertyRead(S.getNumberOfStatements(), propertyReadResult, 4, eachElementGetResult));
S.getNumberOfStatements();
for (int i = 1; i < paramsToPassToInvoked.length; i++) {
paramsToPassToInvoked[i] = propertyReadResult;
}
return curValNum;
}
private static int passActualPropertyValsAsParams(
JSInstructionFactory insts, int nargs, JavaScriptSummary S, int[] paramsToPassToInvoked) {
// read an arbitrary property name via EachElementGet
int nullVn = nargs + 2;
S.addConstant(nullVn, new ConstantValue(null));
int curValNum = nargs + 3;
for (int i = 1; i < paramsToPassToInvoked.length; i++) {
// create a String constant for i-1
final int constVN = curValNum++;
// the commented line is correct, but it doesn't work because
// of our broken handling of int constants as properties.
// TODO fix property handling, and then fix this
S.addConstant(constVN, new ConstantValue(Integer.toString(i - 1)));
// S.addConstant(constVN, new ConstantValue(i-1));
int propertyReadResult = curValNum++;
// 4 is position of arguments array
S.addStatement(insts.PropertyWrite(S.getNumberOfStatements(), 4, constVN, nullVn));
S.getNumberOfStatements();
S.addStatement(insts.PropertyRead(S.getNumberOfStatements(), propertyReadResult, 4, constVN));
S.getNumberOfStatements();
paramsToPassToInvoked[i] = propertyReadResult;
}
return curValNum;
}
private static IR makeIRForNoArgList(CGNode node) {
// kind of a hack; re-use the summarized function infrastructure
MethodReference ref = node.getMethod().getReference();
IClass declaringClass = node.getMethod().getDeclaringClass();
JSInstructionFactory insts =
(JSInstructionFactory) declaringClass.getClassLoader().getInstructionFactory();
// nargs needs to match that of Function.apply(), even though no argsList
// argument was passed in this case
int nargs = 4;
JavaScriptSummary S = new JavaScriptSummary(ref, nargs);
// generate invocation instruction for the real method being invoked
int resultVal = nargs + 2;
CallSiteReference cs =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNumberOfStatements());
int[] params = new int[1];
params[0] = 3;
// function being invoked is in v2
S.addStatement(
insts.Invoke(S.getNumberOfStatements(), 2, resultVal, params, resultVal + 1, cs));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), resultVal, false));
S.getNumberOfStatements();
JavaScriptSummarizedFunction t = new JavaScriptSummarizedFunction(ref, S, declaringClass);
return t.makeIR(node.getContext(), null);
}
@Override
public DefUse getDU(CGNode node) {
assert understands(node);
return new DefUse(getIR(node));
}
}
| 9,160
| 41.21659
| 101
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptFunctionApplyContextSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.cfa.OneLevelSiteContextSelector;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
/**
* @see <a
* href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply">MDN
* Function.prototype.apply() docs</a>
*/
public class JavaScriptFunctionApplyContextSelector implements ContextSelector {
/* whether to use a one-level callstring context in addition to the apply context */
private static final boolean USE_ONE_LEVEL = true;
private static final TypeName APPLY_TYPE_NAME =
TypeName.findOrCreate("Lprologue.js/Function_prototype_apply");
private static final TypeName CALL_TYPE_NAME =
TypeName.findOrCreate("Lprologue.js/Function_prototype_call");
public static final ContextKey APPLY_NON_NULL_ARGS = new ContextKey() {};
private final ContextSelector base;
private final ContextSelector oneLevel;
public JavaScriptFunctionApplyContextSelector(ContextSelector base) {
this.base = base;
// this.oneLevel = new nCFAContextSelector(1, base);
this.oneLevel = new OneLevelSiteContextSelector(base);
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
// 0 for function (synthetic apply), 1 for this (function being invoked), 2
// for this arg of function being invoked,
// 3 for arguments array
MutableIntSet params = IntSetUtil.make();
for (int i = 0; i < 4 && i < caller.getIR().getCalls(site)[0].getNumberOfUses(); i++) {
params.add(i);
}
return params.union(base.getRelevantParameters(caller, site));
}
public static class ApplyContext implements Context {
private final Context delegate;
/** was the argsList argument a non-null Array? */
private final ContextItem.Value<Boolean> isNonNullArray;
ApplyContext(Context delegate, boolean isNonNullArray) {
this.delegate = delegate;
this.isNonNullArray = ContextItem.Value.make(isNonNullArray);
}
@Override
public ContextItem get(ContextKey name) {
if (APPLY_NON_NULL_ARGS.equals(name)) {
return isNonNullArray;
} else {
return delegate.get(name);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + delegate.hashCode();
result = prime * result + isNonNullArray.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ApplyContext other = (ApplyContext) obj;
if (!delegate.equals(other.delegate)) return false;
if (!isNonNullArray.equals(other.isNonNullArray)) return false;
return true;
}
@Override
public String toString() {
return "ApplyContext [delegate=" + delegate + ", isNonNullArray=" + isNonNullArray + ']';
}
}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
IClass declaringClass = callee.getDeclaringClass();
IMethod method = declaringClass.getMethod(AstMethodReference.fnSelector);
Context baseCtxt = base.getCalleeTarget(caller, site, callee, receiver);
if (method != null) {
TypeName tn = method.getReference().getDeclaringClass().getName();
if (tn.equals(APPLY_TYPE_NAME)) {
boolean isNonNullArray = false;
if (receiver.length >= 4) {
InstanceKey argsList = receiver[3];
if (argsList != null
&& argsList
.getConcreteType()
.equals(caller.getClassHierarchy().lookupClass(JavaScriptTypes.Array))) {
isNonNullArray = true;
}
}
if (USE_ONE_LEVEL && caller.getContext().get(APPLY_NON_NULL_ARGS) == null)
baseCtxt = oneLevel.getCalleeTarget(caller, site, callee, receiver);
return new ApplyContext(baseCtxt, isNonNullArray);
} else if (USE_ONE_LEVEL && tn.equals(CALL_TYPE_NAME)) {
return oneLevel.getCalleeTarget(caller, site, callee, receiver);
}
}
return baseCtxt;
}
}
| 5,260
| 35.79021
| 101
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptFunctionApplyTargetSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummarizedFunction;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummary;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
/**
* We need to generate synthetic methods for Function.apply() in the target selector, so that the
* AstMethod for Function_prototype_apply() in the prologue doesn't actually get used in the CGNodes
* used for calls to Function.prototype.apply(). The generated dummy methods should <em>never</em>
* actually be used except as a stub.
*/
public class JavaScriptFunctionApplyTargetSelector implements MethodTargetSelector {
private final MethodTargetSelector base;
private static final TypeName APPLY_TYPE_NAME =
TypeName.findOrCreate("Lprologue.js/Function_prototype_apply");
private IMethod applyMethod;
public JavaScriptFunctionApplyTargetSelector(MethodTargetSelector base) {
this.base = base;
}
private static IMethod createApplyDummyMethod(IClass declaringClass) {
final MethodReference ref = genSyntheticMethodRef(declaringClass);
// number of args doesn't matter
JavaScriptSummary S = new JavaScriptSummary(ref, 1);
return new JavaScriptSummarizedFunction(ref, S, declaringClass);
}
public static final String SYNTHETIC_APPLY_METHOD_PREFIX = "$$ apply_dummy";
private static MethodReference genSyntheticMethodRef(IClass receiver) {
Atom atom = Atom.findOrCreateUnicodeAtom(SYNTHETIC_APPLY_METHOD_PREFIX);
Descriptor desc = Descriptor.findOrCreateUTF8(JavaScriptLoader.JS, "()LRoot;");
MethodReference ref = MethodReference.findOrCreate(receiver.getReference(), atom, desc);
return ref;
}
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) {
IMethod method = receiver.getMethod(AstMethodReference.fnSelector);
if (method != null) {
TypeName tn = method.getReference().getDeclaringClass().getName();
if (tn.equals(APPLY_TYPE_NAME)) {
if (applyMethod == null) {
applyMethod = createApplyDummyMethod(receiver);
}
return applyMethod;
}
}
return base.getCalleeTarget(caller, site, receiver);
}
}
| 3,035
| 38.428571
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptFunctionDotCallTargetSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummarizedFunction;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummary;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.intset.IntIterator;
import java.util.Map;
/**
* Generate IR to model Function.call()
*
* @see <a
* href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call">MDN
* Function.call() docs</a>
* @author manu
*/
public class JavaScriptFunctionDotCallTargetSelector implements MethodTargetSelector {
/*
* Call graph imprecision often leads to spurious invocations of Function.prototype.call; two common
* patterns are invocations of "new" on Function.prototype.call (which in reality would lead to a
* type error), and self-applications of Function.prototype.call.
*
* While neither of these situations is a priori impossible, they are most likely due to analysis
* imprecision. If this flag is set to true, we emit a warning when seeing them.
*/
public static boolean WARN_ABOUT_IMPRECISE_CALLGRAPH = true;
public static final boolean DEBUG_SYNTHETIC_CALL_METHODS = false;
private static final TypeName CALL_TYPE_NAME =
TypeName.findOrCreate("Lprologue.js/Function_prototype_call");
private final MethodTargetSelector base;
public JavaScriptFunctionDotCallTargetSelector(MethodTargetSelector base) {
this.base = base;
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ipa.callgraph.MethodTargetSelector#getCalleeTarget(com.ibm
* .wala.ipa.callgraph.CGNode, com.ibm.wala.classLoader.CallSiteReference,
* com.ibm.wala.classLoader.IClass)
*/
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) {
IMethod method = receiver.getMethod(AstMethodReference.fnSelector);
if (method != null) {
TypeName tn = method.getReference().getDeclaringClass().getName();
if (tn.equals(CALL_TYPE_NAME)) {
/* invoking Function.prototype.call as a constructor results in a TypeError
* see ECMA-262 5.1, 15: "None of the built-in functions described in this clause that
* are not constructors shall implement the [[Construct]] internal method unless otherwise
* specified" */
if (!site.getDeclaredTarget().equals(JavaScriptMethods.ctorReference)) {
IMethod target = getFunctionCallTarget(caller, site, receiver);
if (target != null) return target;
}
// if we get here, we either saw an invocation of "call" as a constructor, or an invocation
// without receiver object; in either case, this is likely due to bad call graph info
if (WARN_ABOUT_IMPRECISE_CALLGRAPH) warnAboutImpreciseCallGraph(caller, site);
}
}
return base.getCalleeTarget(caller, site, receiver);
}
protected void warnAboutImpreciseCallGraph(CGNode caller, CallSiteReference site) {
IntIterator indices = caller.getIR().getCallInstructionIndices(site).intIterator();
IMethod callerMethod = caller.getMethod();
Position pos = null;
if (indices.hasNext() && callerMethod instanceof AstMethod) {
pos = ((AstMethod) callerMethod).getSourcePosition(indices.next());
}
System.err.println(
"Detected improbable call to Function.prototype.call "
+ (pos == null ? "in function " + caller : "at position " + pos)
+ "; this is likely caused by call graph imprecision.");
}
private static final boolean SEPARATE_SYNTHETIC_METHOD_PER_SITE = false;
/** cache synthetic method for each arity of Function.call() invocation */
private final Map<Object, JavaScriptSummarizedFunction> callModels = HashMapFactory.make();
/** generate a synthetic method modeling the invocation of Function.call() at the site */
private IMethod getFunctionCallTarget(CGNode caller, CallSiteReference site, IClass receiver) {
int nargs = getNumberOfArgsPassed(caller, site);
if (nargs < 2) return null;
String key = getKey(nargs, caller, site);
if (callModels.containsKey(key)) {
return callModels.get(key);
}
JSInstructionFactory insts =
(JSInstructionFactory) receiver.getClassLoader().getInstructionFactory();
MethodReference ref = genSyntheticMethodRef(receiver, key);
JavaScriptSummary S = new JavaScriptSummary(ref, nargs);
if (WARN_ABOUT_IMPRECISE_CALLGRAPH
&& caller.getMethod().getName().toString().contains(SYNTHETIC_CALL_METHOD_PREFIX))
warnAboutImpreciseCallGraph(caller, site);
// print information about where the method was created if desired
if (DEBUG_SYNTHETIC_CALL_METHODS) {
IMethod method = caller.getMethod();
if (method instanceof AstMethod) {
int line =
((AstMethod) method)
.getLineNumber(caller.getIR().getCallInstructionIndices(site).intIterator().next());
System.err.println("creating " + ref.getName() + " at line " + line + " in " + caller);
} else {
System.err.println("creating " + ref.getName() + " in " + method.getName());
}
}
// generate invocation instruction for the real method being invoked
int resultVal = nargs + 2;
CallSiteReference cs =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNumberOfStatements());
int[] params = new int[nargs - 2];
// add 3 to skip v1 (which points to Function.call() itself) and v2 (the
// real function being invoked)
for (int i = 0; i < params.length; i++) {
params[i] = i + 3;
}
// function being invoked is in v2
S.addStatement(
insts.Invoke(S.getNumberOfStatements(), 2, resultVal, params, resultVal + 1, cs));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), resultVal, false));
S.getNumberOfStatements();
JavaScriptSummarizedFunction t = new JavaScriptSummarizedFunction(ref, S, receiver);
callModels.put(key, t);
return t;
}
public static final String SYNTHETIC_CALL_METHOD_PREFIX = "$$ call_";
private static MethodReference genSyntheticMethodRef(IClass receiver, String key) {
Atom atom = Atom.findOrCreateUnicodeAtom(SYNTHETIC_CALL_METHOD_PREFIX + key);
Descriptor desc = Descriptor.findOrCreateUTF8(JavaScriptLoader.JS, "()LRoot;");
MethodReference ref = MethodReference.findOrCreate(receiver.getReference(), atom, desc);
return ref;
}
private static String getKey(int nargs, CGNode caller, CallSiteReference site) {
if (SEPARATE_SYNTHETIC_METHOD_PER_SITE) {
return CAstCallGraphUtil.getShortName(caller)
+ '_'
+ caller.getGraphNodeId()
+ '_'
+ site.getProgramCounter();
} else {
return String.valueOf(nargs);
}
}
private static int getNumberOfArgsPassed(CGNode caller, CallSiteReference site) {
IR callerIR = caller.getIR();
SSAAbstractInvokeInstruction callStmts[] = callerIR.getCalls(site);
assert callStmts.length == 1;
int nargs = callStmts[0].getNumberOfPositionalParameters();
return nargs;
}
}
| 8,462
| 41.742424
| 102
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptScopeMappingInstanceKeys.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod.LexicalParent;
import com.ibm.wala.cast.loader.CAstAbstractModuleLoader.DynamicMethodObject;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallString;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallStringContextSelector;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.Pair;
import java.util.Collection;
import java.util.Collections;
public class JavaScriptScopeMappingInstanceKeys extends ScopeMappingInstanceKeys {
private final IClassHierarchy cha;
private final IClass codeBody;
public JavaScriptScopeMappingInstanceKeys(
IClassHierarchy cha, PropagationCallGraphBuilder builder, InstanceKeyFactory basic) {
super(builder, basic);
this.cha = cha;
this.codeBody = cha.lookupClass(JavaScriptTypes.CodeBody);
}
protected LexicalParent[] getParents(InstanceKey base) {
DynamicMethodObject function =
(DynamicMethodObject) base.getConcreteType().getMethod(AstMethodReference.fnSelector);
return function == null ? new LexicalParent[0] : function.getParents();
}
@Override
protected boolean needsScopeMappingKey(InstanceKey base) {
return cha.isSubclassOf(base.getConcreteType(), codeBody) && getParents(base).length > 0;
}
@Override
protected Collection<CGNode> getConstructorCallers(
ScopeMappingInstanceKey smik, Pair<String, String> name) {
// in JavaScript, the 'new' instruction is wrapped in a synthetic constructor method. we want
// the
// caller of that constructor method, which we obtain from the context for the constructor
// method
final Context creatorContext = smik.getCreator().getContext();
CGNode callerOfConstructor = (CGNode) creatorContext.get(ContextKey.CALLER);
Collection<CGNode> result = null;
if (callerOfConstructor != null) {
return Collections.singleton(callerOfConstructor);
} else {
CallString cs = (CallString) creatorContext.get(CallStringContextSelector.CALL_STRING);
if (cs != null) {
IMethod[] methods = cs.getMethods();
assert methods.length == 1;
IMethod m = methods[0];
result = builder.getCallGraph().getNodes(m.getReference());
}
}
if (result == null) {
IClassHierarchy cha = smik.getCreator().getClassHierarchy();
MethodReference ref =
MethodReference.findOrCreate(
JavaScriptLoader.JS,
TypeReference.findOrCreate(cha.getLoaders()[0].getReference(), name.snd),
AstMethodReference.fnAtomStr,
AstMethodReference.fnDesc.toString());
final IMethod method = cha.resolveMethod(ref);
if (method != null) {
return builder.getCallGraph().getNodes(method.getReference());
}
}
return result;
}
}
| 3,939
| 39.204082
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/LoadFileTargetSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
public class LoadFileTargetSelector implements MethodTargetSelector {
private final MethodTargetSelector base;
private final JSSSAPropagationCallGraphBuilder builder;
private final TypeReference loadFileRef =
TypeReference.findOrCreate(
JavaScriptTypes.jsLoader, TypeName.string2TypeName("Lprologue.js/loadFile"));
private final MethodReference loadFileFunRef = AstMethodReference.fnReference(loadFileRef);
private final HashSet<String> loadedFiles = HashSetFactory.make();
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) {
IMethod target = base.getCalleeTarget(caller, site, receiver);
if (target != null && target.getReference().equals(loadFileFunRef)) {
Set<String> names = new HashSet<>();
SSAInstruction call =
caller.getIR()
.getInstructions()[
caller.getIR().getCallInstructionIndices(site).intIterator().next()];
if (call.getNumberOfUses() > 1) {
LocalPointerKey fileNameV = new LocalPointerKey(caller, call.getUse(1));
OrdinalSet<InstanceKey> ptrs = builder.getPointerAnalysis().getPointsToSet(fileNameV);
for (InstanceKey k : ptrs) {
if (k instanceof ConstantKey) {
Object v = ((ConstantKey<?>) k).getValue();
if (v instanceof String) {
names.add((String) v);
}
}
}
if (names.size() == 1) {
String str = names.iterator().next();
try {
JavaScriptLoader cl =
(JavaScriptLoader) builder.getClassHierarchy().getLoader(JavaScriptTypes.jsLoader);
URL url = new URL(builder.getBaseURL(), str);
if (!loadedFiles.contains(url.toString())) {
// try to open the input stream for the URL. if it fails, we'll get an IOException
// and fall through to default case
try (InputStream inputStream = url.openConnection().getInputStream()) {}
JSCallGraphUtil.loadAdditionalFile(builder.getClassHierarchy(), cl, url);
loadedFiles.add(url.toString());
IClass script =
builder
.getClassHierarchy()
.lookupClass(
TypeReference.findOrCreate(cl.getReference(), 'L' + url.getFile()));
return script.getMethod(AstMethodReference.fnSelector);
}
} catch (RuntimeException | IOException e1) {
// do nothing, fall through and return 'target'
}
}
}
}
return target;
}
public LoadFileTargetSelector(
MethodTargetSelector base, JSSSAPropagationCallGraphBuilder builder) {
super();
this.base = base;
this.builder = builder;
}
}
| 4,177
| 37.685185
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/ObjectSensitivityContextSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ipa.callgraph.ArgumentInstanceContext;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import java.util.HashMap;
public class ObjectSensitivityContextSelector implements ContextSelector {
private final ContextSelector base;
public ObjectSensitivityContextSelector(ContextSelector base) {
this.base = base;
}
private final HashMap<MethodReference, Boolean> returnsThis_cache = HashMapFactory.make();
private final IRFactory<IMethod> factory = AstIRFactory.makeDefaultFactory();
// determine whether the method returns "this"
private boolean returnsThis(IMethod method) {
MethodReference mref = method.getReference();
if (method.getNumberOfParameters() < 1) return false;
Boolean b = returnsThis_cache.get(mref);
if (b != null) return b;
for (SSAInstruction inst :
factory
.makeIR(method, Everywhere.EVERYWHERE, SSAOptions.defaultOptions())
.getInstructions()) {
if (inst instanceof SSAReturnInstruction) {
SSAReturnInstruction ret = (SSAReturnInstruction) inst;
if (ret.getResult() == 2) {
returnsThis_cache.put(mref, true);
return true;
}
}
}
returnsThis_cache.put(mref, false);
return false;
}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] arguments) {
Context baseContext = base.getCalleeTarget(caller, site, callee, arguments);
if (returnsThis(callee)) {
if (arguments.length > 1 && arguments[1] != null) {
return new ArgumentInstanceContext(baseContext, 1, arguments[1]);
}
}
return baseContext;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (caller.getIR().getCalls(site)[0].getNumberOfUses() > 1) {
return IntSetUtil.make(new int[] {1}).union(base.getRelevantParameters(caller, site));
} else {
return base.getRelevantParameters(caller, site);
}
}
}
| 3,103
| 35.093023
| 92
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/PropertyNameContextSelector.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ir.ssa.AbstractReflectiveGet;
import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationFinder;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.ClosureExtractor;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.SingleInstanceFilter;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.SelectiveCPAContext;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.ReflectiveMemberAccess;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import java.util.Collections;
import java.util.HashMap;
/**
* A context selector that applies object sensitivity for the i'th parameter if it is used as a
* property name in a dynamic property access.
*
* <p>Works together with {@link CorrelationFinder} and {@link ClosureExtractor} to implement
* correlation tracking.
*/
public class PropertyNameContextSelector implements ContextSelector {
public static final ContextKey PROPNAME_KEY = new ContextKey() {};
public static final ContextItem PROPNAME_MARKER = new ContextItem() {};
public static final ContextKey PROPNAME_PARM_INDEX = new ContextKey() {};
public static final ContextKey INSTANCE_KEY_KEY = new ContextKey() {};
/** Context representing a particular name accessed by a correlated read/write pair. */
public class PropNameContext extends SelectiveCPAContext {
PropNameContext(Context base, InstanceKey obj) {
super(base, Collections.singletonMap(ContextKey.PARAMETERS[index], obj));
}
@Override
public ContextItem get(ContextKey key) {
if (PROPNAME_KEY.equals(key)) {
return PROPNAME_MARKER;
} else if (PROPNAME_PARM_INDEX.equals(key)) {
return ContextItem.Value.make(index);
} else if (INSTANCE_KEY_KEY.equals(key)) {
return ContextItem.Value.make(
((SingleInstanceFilter) get(ContextKey.PARAMETERS[index])).getInstance());
} else {
return super.get(key);
}
}
@Override
public String toString() {
return "property name context for "
+ get(ContextKey.PARAMETERS[index])
+ " over "
+ this.base;
}
}
/**
* A "dummy" for-in context used for callees of a method analyzed in a real {@link
* PropNameContext}. The purpose of this class is to clone callees based on the same {@link
* InstanceKey} used for the caller context, but without returning a {@link SingleInstanceFilter}
* {@link ContextItem} that filters possible parameter values.
*/
class MarkerForInContext extends PropNameContext {
MarkerForInContext(Context base, InstanceKey obj) {
super(base, obj);
}
/**
* Like {@link PropNameContext#get(ContextKey)}, but don't return a {@link SingleInstanceFilter}
* for the distinguishing {@link InstanceKey}
*/
@Override
public ContextItem get(ContextKey key) {
if (INSTANCE_KEY_KEY.equals(key)) {
return ContextItem.Value.make(
((SingleInstanceFilter) super.get(ContextKey.PARAMETERS[index])).getInstance());
} else {
final ContextItem contextItem = super.get(key);
return (contextItem instanceof SingleInstanceFilter) ? null : contextItem;
}
}
}
private final IAnalysisCacheView cache;
private final ContextSelector base;
private final int index;
private void collectValues(DefUse du, SSAInstruction inst, MutableIntSet values) {
if (inst instanceof SSAGetInstruction) {
SSAGetInstruction g = (SSAGetInstruction) inst;
values.add(g.getRef());
if (g.getRef() != -1) {
collectValues(du, du.getDef(g.getRef()), values);
}
} else if (inst instanceof AbstractReflectiveGet) {
AbstractReflectiveGet g = (AbstractReflectiveGet) inst;
values.add(g.getObjectRef());
collectValues(du, du.getDef(g.getObjectRef()), values);
values.add(g.getMemberRef());
collectValues(du, du.getDef(g.getMemberRef()), values);
}
}
private IntSet identifyDependentParameters(CGNode caller, CallSiteReference site) {
MutableIntSet dependentParameters = IntSetUtil.make();
SSAAbstractInvokeInstruction inst = caller.getIR().getCalls(site)[0];
DefUse du = caller.getDU();
for (int i = 0; i < inst.getNumberOfPositionalParameters(); i++) {
MutableIntSet values = IntSetUtil.make();
values.add(inst.getUse(i));
collectValues(du, du.getDef(inst.getUse(i)), values);
if (values.contains(index + 1)) dependentParameters.add(i);
}
return dependentParameters;
}
public PropertyNameContextSelector(IAnalysisCacheView cache, ContextSelector base) {
this(cache, 2, base);
}
public PropertyNameContextSelector(IAnalysisCacheView cache, int index, ContextSelector base) {
this.cache = cache;
this.index = index;
this.base = base;
}
private enum Frequency {
NEVER,
SOMETIMES,
ALWAYS
}
private final HashMap<MethodReference, Frequency> usesFirstArgAsPropertyName_cache =
HashMapFactory.make();
/**
* Determine whether the method never/sometimes/always uses its first argument as a property name.
*/
private Frequency usesFirstArgAsPropertyName(IMethod method) {
MethodReference mref = method.getReference();
if (method.getNumberOfParameters() < index) return Frequency.NEVER;
Frequency f = usesFirstArgAsPropertyName_cache.get(mref);
if (f != null) return f;
boolean usedAsPropertyName = false, usedAsSomethingElse = false;
DefUse du = cache.getDefUse(cache.getIR(method));
for (SSAInstruction use : Iterator2Iterable.make(du.getUses(index + 1))) {
if (use instanceof ReflectiveMemberAccess) {
ReflectiveMemberAccess rma = (ReflectiveMemberAccess) use;
if (rma.getMemberRef() == index + 1) {
usedAsPropertyName = true;
continue;
}
} else if (use instanceof AstIsDefinedInstruction) {
AstIsDefinedInstruction aidi = (AstIsDefinedInstruction) use;
if (aidi.getNumberOfUses() > 1 && aidi.getUse(1) == index + 1) {
usedAsPropertyName = true;
continue;
}
}
usedAsSomethingElse = true;
}
if (!usedAsPropertyName) f = Frequency.NEVER;
else if (usedAsSomethingElse) f = Frequency.SOMETIMES;
else f = Frequency.ALWAYS;
usesFirstArgAsPropertyName_cache.put(mref, f);
return f;
}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, final InstanceKey[] receiver) {
Context baseContext = base.getCalleeTarget(caller, site, callee, receiver);
if (receiver.length > index && receiver[index] instanceof ConstantKey) {
Frequency f = usesFirstArgAsPropertyName(callee);
if (f == Frequency.ALWAYS || f == Frequency.SOMETIMES)
return new PropNameContext(baseContext, receiver[index]);
}
if (PROPNAME_MARKER.equals(caller.getContext().get(PROPNAME_KEY))) {
if (!identifyDependentParameters(caller, site).isEmpty()) {
// use a MarkerForInContext to clone based on the InstanceKey used in the caller context
@SuppressWarnings("unchecked")
InstanceKey callerIk =
((ContextItem.Value<InstanceKey>) caller.getContext().get(INSTANCE_KEY_KEY)).getValue();
return new MarkerForInContext(baseContext, callerIk);
} else {
return baseContext;
}
}
return baseContext;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (caller.getIR().getCalls(site)[0].getNumberOfUses() > index) {
return IntSetUtil.make(new int[] {index}).union(base.getRelevantParameters(caller, site));
} else {
return base.getRelevantParameters(caller, site);
}
}
}
| 9,062
| 37.730769
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/RecursionBoundContextSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.analysis.reflection.InstanceKeyWithNode;
import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys.ScopeMappingInstanceKey;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions.JavaScriptConstructor;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.SingleInstanceFilter;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallString;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallStringContext;
import com.ibm.wala.util.intset.IntSet;
/**
* A context selector that attempts to detect recursion beyond some depth in a base selector. If
* such recursion is detected, the base selector's context is replaced with {@link
* Everywhere#EVERYWHERE}.
*/
public class RecursionBoundContextSelector implements ContextSelector {
private final ContextSelector base;
private final int recursionBound;
/**
* the highest parameter index that we'll check . this is a HACK. ideally, given a context, we'd
* have some way to know all the {@link ContextKey}s that it knows about.
*
* @see ContextKey#PARAMETERS
*/
private static final int MAX_INTERESTING_PARAM = 5;
/**
* @param recursionBound bound on recursion depth, with the top level of the context returned by
* the base selector being depth 0. The {@link Everywhere#EVERYWHERE} context is returned if
* the base context <em>exceeds</em> this bound.
*/
public RecursionBoundContextSelector(ContextSelector base, int recursionBound) {
this.base = base;
this.recursionBound = recursionBound;
}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] actualParameters) {
Context baseContext = base.getCalleeTarget(caller, site, callee, actualParameters);
final boolean exceedsRecursionBound = exceedsRecursionBound(baseContext, 0);
if (!exceedsRecursionBound) {
return baseContext;
} else if (callee instanceof JavaScriptConstructor) {
// for constructors, we want to keep some basic context sensitivity to
// avoid horrible imprecision
return new CallStringContext(new CallString(site, caller.getMethod()));
} else {
// TODO somehow k-limit more smartly?
return Everywhere.EVERYWHERE;
}
}
private boolean exceedsRecursionBound(Context baseContext, int curLevel) {
if (curLevel > recursionBound) {
return true;
}
// we just do a case analysis here. we might have to add cases later to
// account for new types of context / recursion.
CGNode callerNode = (CGNode) baseContext.get(ContextKey.CALLER);
if (callerNode != null && exceedsRecursionBound(callerNode.getContext(), curLevel + 1)) {
return true;
}
for (int i = 0; i < MAX_INTERESTING_PARAM; i++) {
FilteredPointerKey.SingleInstanceFilter filter =
(SingleInstanceFilter) baseContext.get(ContextKey.PARAMETERS[i]);
if (filter != null) {
InstanceKey ik = filter.getInstance();
if (ik instanceof ScopeMappingInstanceKey) {
ik = ((ScopeMappingInstanceKey) ik).getBase();
}
if (ik instanceof InstanceKeyWithNode) {
if (exceedsRecursionBound(
((InstanceKeyWithNode) ik).getNode().getContext(), curLevel + 1)) {
return true;
}
}
}
}
return false;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return base.getRelevantParameters(caller, site);
}
}
| 4,389
| 38.909091
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/RecursionCheckContextSelector.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.analysis.reflection.InstanceKeyWithNode;
import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys.ScopeMappingInstanceKey;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.SingleInstanceFilter;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.IntSet;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* ensures that no contexts returned by a base context selector are recursive (assertion failure
* otherwise)
*/
public class RecursionCheckContextSelector implements ContextSelector {
private final ContextSelector base;
/**
* the highest parameter index that we'll check . this is a HACK. ideally, given a context, we'd
* have some way to know all the {@link ContextKey}s that it knows about.
*
* @see ContextKey#PARAMETERS
*/
private static final int MAX_INTERESTING_PARAM = 5;
public RecursionCheckContextSelector(ContextSelector base) {
this.base = base;
}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] actualParameters) {
Context baseContext = base.getCalleeTarget(caller, site, callee, actualParameters);
assert !recursiveContext(baseContext, callee);
return baseContext;
}
private static boolean recursiveContext(Context baseContext, IMethod callee) {
if (!recursionPossible(callee)) {
return false;
}
ArrayDeque<Pair<Context, Collection<IMethod>>> worklist = new ArrayDeque<>();
worklist.push(Pair.make(baseContext, (Collection<IMethod>) Collections.singleton(callee)));
while (!worklist.isEmpty()) {
Pair<Context, Collection<IMethod>> p = worklist.removeFirst();
Context curContext = p.fst;
Collection<IMethod> curEncountered = p.snd;
// we just do a case analysis here. we might have to add cases later to
// account for new types of context / recursion.
CGNode callerNode = (CGNode) curContext.get(ContextKey.CALLER);
if (callerNode != null) {
if (!updateForNode(baseContext, curEncountered, worklist, callerNode)) {
System.err.println("callee " + callee);
return true;
}
}
for (int i = 0; i < MAX_INTERESTING_PARAM; i++) {
FilteredPointerKey.SingleInstanceFilter filter =
(SingleInstanceFilter) curContext.get(ContextKey.PARAMETERS[i]);
if (filter != null) {
InstanceKey ik = filter.getInstance();
if (ik instanceof ScopeMappingInstanceKey) {
ik = ((ScopeMappingInstanceKey) ik).getBase();
}
if (ik instanceof InstanceKeyWithNode) {
CGNode node = ((InstanceKeyWithNode) ik).getNode();
if (!updateForNode(baseContext, curEncountered, worklist, node)) {
System.err.println("callee " + callee);
return true;
}
}
}
}
}
return false;
}
private static boolean updateForNode(
Context baseContext,
Collection<IMethod> curEncountered,
ArrayDeque<Pair<Context, Collection<IMethod>>> worklist,
CGNode callerNode) {
final IMethod method = callerNode.getMethod();
if (!recursionPossible(method)) {
assert !curEncountered.contains(method);
return true;
}
if (curEncountered.contains(method)) {
System.err.println("recursion in context on method " + method);
System.err.println("encountered methods: ");
for (IMethod m : curEncountered) {
System.err.println(" " + m);
}
System.err.println("context " + baseContext);
return false;
}
Collection<IMethod> newEncountered = new ArrayList<>(curEncountered);
newEncountered.add(method);
worklist.add(Pair.make(callerNode.getContext(), newEncountered));
return true;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return base.getRelevantParameters(caller, site);
}
/** is it possible for m to be involved in a recursive cycle? */
private static boolean recursionPossible(IMethod m) {
// object or array constructors cannot be involved
if (m.getReference().getName().equals(JavaScriptMethods.ctorAtom)) {
TypeReference declaringClass = m.getReference().getDeclaringClass();
if (declaringClass.equals(JavaScriptTypes.Object)
|| declaringClass.equals(JavaScriptTypes.Array)) {
return false;
}
}
return true;
}
}
| 5,501
| 36.944828
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/TransitivePrototypeKey.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
public class TransitivePrototypeKey extends AbstractFieldPointerKey {
public String getName() {
return "transitive prototype of " + getInstanceKey().toString();
}
public TransitivePrototypeKey(InstanceKey object) {
super(object);
}
@Override
public boolean equals(Object x) {
return (x instanceof TransitivePrototypeKey)
&& ((TransitivePrototypeKey) x).getInstanceKey().equals(getInstanceKey());
}
@Override
public int hashCode() {
return getInstanceKey().hashCode();
}
@Override
public String toString() {
return "<proto:" + getName() + '>';
}
}
| 1,157
| 26.571429
| 82
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/Correlation.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import java.util.HashSet;
import java.util.Set;
/**
* A correlation exists between a dynamic property read r and a dynamic property write w such that
* the value read in r may flow into w, and r and w are guaranteed to access a property of the same
* name.
*
* <p>We additionally track the set of local variables the value read in r may flow through before
* reaching w. These will be candidates for localisation when extracting the correlation into a
* closure.
*
* @author mschaefer
*/
public abstract class Correlation {
private final String indexName;
private final Set<String> flownThroughLocals;
protected Correlation(String indexName, Set<String> flownThroughLocals) {
this.indexName = indexName;
this.flownThroughLocals = new HashSet<>(flownThroughLocals);
}
public String getIndexName() {
return indexName;
}
public Set<String> getFlownThroughLocals() {
return flownThroughLocals;
}
public abstract Position getStartPosition(SSASourcePositionMap positions);
public abstract Position getEndPosition(SSASourcePositionMap positions);
public abstract String pp(SSASourcePositionMap positions);
public abstract <T> T accept(CorrelationVisitor<T> visitor);
}
| 1,709
| 30.666667
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/CorrelationFinder.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope;
import com.ibm.wala.cast.ir.ssa.AbstractReflectiveGet;
import com.ibm.wala.cast.ir.ssa.AbstractReflectivePut;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.AstMethod.LexicalInformation;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.classLoader.SourceURLModule;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.IOperator;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.ObjectArrayMapping;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.BitVectorIntSet;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Helper class for identifying correlated read/write pairs.
*
* @author mschaefer
*/
public class CorrelationFinder {
private static final boolean TRACK_ESCAPES = true;
private static final boolean IGNORE_NUMERIC_INDICES = false;
private final JavaScriptTranslatorFactory translatorFactory;
public CorrelationFinder(JavaScriptTranslatorFactory translatorFactory) {
this.translatorFactory = translatorFactory;
}
@SuppressWarnings("unused")
public static CorrelationSummary findCorrelatedAccesses(IMethod method, IR ir) {
AstMethod astMethod = (AstMethod) method;
DefUse du = new DefUse(ir);
OrdinalSetMapping<SSAInstruction> instrIndices = new ObjectArrayMapping<>(ir.getInstructions());
CorrelationSummary summary = new CorrelationSummary(method, instrIndices);
// collect all dynamic property writes in the method
ArrayDeque<AbstractReflectivePut> puts = new ArrayDeque<>();
for (SSAInstruction inst : Iterator2Iterable.make(ir.iterateNormalInstructions()))
if (inst instanceof AbstractReflectivePut) puts.addFirst((AbstractReflectivePut) inst);
SSAInstruction insts[] = ir.getInstructions();
instrs:
for (int ii = 0; ii < insts.length; ii++) {
SSAInstruction inst = insts[ii];
if (inst instanceof AbstractReflectiveGet) {
AbstractReflectiveGet get = (AbstractReflectiveGet) inst;
int index = get.getMemberRef();
if (ir.getSymbolTable().isConstant(index)) continue;
if (ir.getSymbolTable().isParameter(index)) continue;
// try to determine what "index" is called at the source level
String indexName = getSourceLevelName(ir, ii, index);
if (indexName == null) continue instrs;
// check that "index" is not accessed in an inner function
LexicalInformation lexicalInfo = astMethod.lexicalInfo();
if (lexicalInfo.getExposedNames() != null) {
for (Pair<String, String> n : lexicalInfo.getExposedNames()) {
if (n.fst.equals(indexName) && lexicalInfo.getScopingName().equals(n.snd))
continue instrs;
}
}
// if "index" is a numeric variable, it is not worth extracting
if (IGNORE_NUMERIC_INDICES && mustBeNumeric(ir, du, index)) continue instrs;
// set of SSA variables into which the value read by 'get' may flow
MutableIntSet reached = new BitVectorIntSet();
reached.add(get.getDef());
// saturate reached by following def-use chains through phi instructions and across function
// calls
ArrayDeque<Integer> worklist = new ArrayDeque<>();
MutableIntSet done = new BitVectorIntSet();
worklist.add(get.getDef());
while (!worklist.isEmpty()) {
Integer i = worklist.pop();
done.add(i);
for (SSAInstruction inst2 : Iterator2Iterable.make(du.getUses(i))) {
int i2 = instrIndices.getMappedIndex(inst2);
if (inst2 instanceof SSAPhiInstruction) {
int def = inst2.getDef();
if (reached.add(def) && !done.contains(def)) worklist.add(def);
} else if (inst2 instanceof SSAAbstractInvokeInstruction) {
int def = inst2.getDef();
if (reached.add(def) && !done.contains(def)) worklist.add(def);
// if the index also flows into this invocation, record an escape correlation
if (TRACK_ESCAPES) {
for (int j = 0; j < inst2.getNumberOfUses(); ++j) {
if (inst2.getUse(j) == index) {
summary.addCorrelation(
new EscapeCorrelation(
get,
(SSAAbstractInvokeInstruction) inst2,
indexName,
getSourceLevelNames(ir, i2, reached)));
break;
}
}
}
}
}
}
// now find property writes with the same index whose RHS is in 'reached'
for (AbstractReflectivePut put : puts)
if (put.getMemberRef() == index && reached.contains(put.getValue()))
summary.addCorrelation(
new ReadWriteCorrelation(
get, put, indexName, getSourceLevelNames(ir, ii, reached)));
}
}
return summary;
}
// tries to determine which source level variable an SSA variable corresponds to
// if it does not correspond to any variable, or to more than one, null is returned
private static String getSourceLevelName(IR ir, int index, int vn) {
String indexName = null;
String[] sourceNamesForValues = ir.getLocalNames(index, vn);
if (sourceNamesForValues == null) return null;
for (String candidateName : sourceNamesForValues) {
if (indexName != null) {
indexName = null;
break;
}
if (!candidateName.contains(" ")) // ignore internal names
indexName = candidateName;
}
return indexName;
}
private static Set<String> getSourceLevelNames(IR ir, int index, IntSet vs) {
Set<String> res = new HashSet<>();
for (IntIterator iter = vs.intIterator(); iter.hasNext(); ) {
String name = getSourceLevelName(ir, index, iter.next());
if (name != null) res.add(name);
}
return res;
}
// checks whether the given SSA variable must always be assigned a numeric value
private static boolean mustBeNumeric(IR ir, DefUse du, int v) {
ArrayDeque<Integer> worklist = new ArrayDeque<>();
MutableIntSet done = new BitVectorIntSet();
worklist.add(v);
while (!worklist.isEmpty()) {
int i = worklist.pop();
done.add(i);
if (ir.getSymbolTable().isConstant(i)
&& ir.getSymbolTable().getConstantValue(i) instanceof Number) continue;
SSAInstruction inst2 = du.getDef(i);
if (inst2 instanceof SSAPhiInstruction) {
for (int j = 0; j < inst2.getNumberOfUses(); ++j) {
int use = inst2.getUse(j);
if (!done.contains(use)) worklist.add(use);
}
} else if (inst2 instanceof SSABinaryOpInstruction) {
IOperator operator = ((SSABinaryOpInstruction) inst2).getOperator();
// if it is an ADD, both operands have to be provably numeric
if (operator == IBinaryOpInstruction.Operator.ADD) {
for (int j = 0; j < inst2.getNumberOfUses(); ++j) {
int use = inst2.getUse(j);
if (!done.contains(use)) worklist.add(use);
}
}
// otherwise the result is definitely numeric
} else {
// found a definition that doesn't look numeric
return false;
}
}
// found no non-numeric definitions
return true;
}
@SuppressWarnings("unused")
private void printCorrelatedAccesses(URL url) throws ClassHierarchyException {
printCorrelatedAccesses(findCorrelatedAccesses(url));
}
private static void printCorrelatedAccesses(Map<IMethod, CorrelationSummary> summaries) {
List<Pair<Position, String>> correlations = new ArrayList<>();
for (CorrelationSummary summary : summaries.values()) correlations.addAll(summary.pp());
correlations.sort(Comparator.comparing(o -> o.fst));
int i = 0;
for (Pair<Position, String> p : correlations)
System.out.println(i++ + " -- " + p.fst + ": " + p.snd);
}
public Map<IMethod, CorrelationSummary> findCorrelatedAccesses(URL url)
throws ClassHierarchyException {
Set<? extends SourceModule> scripts = null;
if (url.getPath().endsWith(".js")) {
scripts = Collections.singleton(new SourceURLModule(url));
} else {
JavaScriptLoader.addBootstrapFile(WebUtil.preamble);
try {
scripts = WebUtil.extractScriptFromHTML(url, DefaultSourceExtractor.factory).fst;
} catch (Error e) {
e.printStackTrace();
assert false : e.warning;
}
}
Map<IMethod, CorrelationSummary> summaries = findCorrelatedAccesses(scripts);
return summaries;
}
public Map<IMethod, CorrelationSummary> findCorrelatedAccesses(
Collection<? extends SourceModule> scripts) throws ClassHierarchyException {
return findCorrelatedAccesses(scripts.toArray(new SourceModule[0]));
}
public Map<IMethod, CorrelationSummary> findCorrelatedAccesses(SourceModule[] scripts_array)
throws ClassHierarchyException {
JSCallGraphUtil.setTranslatorFactory(translatorFactory);
JavaScriptLoaderFactory loaders = JSCallGraphUtil.makeLoaders(null);
CAstAnalysisScope scope =
new CAstAnalysisScope(scripts_array, loaders, Collections.singleton(JavaScriptLoader.JS));
IClassHierarchy cha = ClassHierarchyFactory.make(scope, loaders, JavaScriptLoader.JS);
try {
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
} catch (WalaException e) {
return Collections.emptyMap();
}
IRFactory<IMethod> factory = AstIRFactory.makeDefaultFactory();
SSAOptions ssaOptions = SSAOptions.defaultOptions();
ssaOptions.setDefaultValues((symtab, valueNumber) -> symtab.getNullConstant());
Map<IMethod, CorrelationSummary> correlations = HashMapFactory.make();
for (IClass klass : cha) {
for (IMethod method : klass.getAllMethods()) {
IR ir = factory.makeIR(method, Everywhere.EVERYWHERE, ssaOptions);
CorrelationSummary summary = findCorrelatedAccesses(method, ir);
if (!summary.getCorrelations().isEmpty()) correlations.put(method, summary);
}
}
return correlations;
}
@SuppressWarnings("unused")
private URL toUrl(String src) throws MalformedURLException {
// first try interpreting as local file name, if that doesn't work just assume it's a URL
try {
File f = new FileProvider().getFileFromClassLoader(src, this.getClass().getClassLoader());
URL url = f.toURI().toURL();
return url;
} catch (FileNotFoundException fnfe) {
return new URL(src);
}
}
}
| 12,876
| 39.75
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/CorrelationSummary.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* A utility class holding information about correlations identified by a {@link CorrelationFinder}.
*
* @author mschaefer
*/
public final class CorrelationSummary {
private final SSASourcePositionMap positions;
private final Set<Correlation> correlations = HashSetFactory.make();
public CorrelationSummary(IMethod method, OrdinalSetMapping<SSAInstruction> instrIndices) {
positions = new SSASourcePositionMap((AstMethod) method, instrIndices);
}
public void addCorrelation(Correlation correlation) {
correlations.add(correlation);
}
public List<Pair<Position, String>> pp() {
List<Pair<Position, String>> res = new ArrayList<>();
for (Correlation correlation : correlations) {
res.add(Pair.make(correlation.getStartPosition(positions), correlation.pp(positions)));
}
return res;
}
public Set<Correlation> getCorrelations() {
return correlations;
}
public boolean isEmpty() {
return correlations.isEmpty();
}
public SSASourcePositionMap getPositions() {
return positions;
}
}
| 1,893
| 29.548387
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/CorrelationVisitor.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
/**
* Visitor class for performing case analysis on {@link Correlation}s.
*
* @author mschaefer
*/
public interface CorrelationVisitor<T> {
T visitReadWriteCorrelation(ReadWriteCorrelation rwc);
T visitEscapeCorrelation(EscapeCorrelation ec);
}
| 681
| 27.416667
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/EscapeCorrelation.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
import com.ibm.wala.cast.ir.ssa.AbstractReflectiveGet;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import java.util.Set;
/**
* An escape correlation conservatively captures inter-procedural correlated pairs: for a dynamic
* property read <i>r</i> of the form {@code e[p]}, if both the result of <i>r</i> and the value of
* {@code p} flow into a function call <i>c</i>, we consider <i>r</i> and <i>c</i> to be a
* correlated pair to account for the fact that the function called by <i>c</i> may perform a write
* of property {@code p}.
*
* @author mschaefer
*/
public class EscapeCorrelation extends Correlation {
private final AbstractReflectiveGet get;
private final SSAAbstractInvokeInstruction invoke;
public EscapeCorrelation(
AbstractReflectiveGet get,
SSAAbstractInvokeInstruction invoke,
String indexName,
Set<String> flownThroughLocals) {
super(indexName, flownThroughLocals);
this.get = get;
this.invoke = invoke;
}
@Override
public Position getStartPosition(SSASourcePositionMap positions) {
return positions.getPosition(get);
}
@Override
public Position getEndPosition(SSASourcePositionMap positions) {
return positions.getPosition(invoke);
}
public int getNumberOfArguments() {
return invoke.getNumberOfPositionalParameters()
- 2; // deduct one for the function object, one for the receiver
}
@Override
public String pp(SSASourcePositionMap positions) {
return get
+ "@"
+ positions.getPosition(get)
+ " ["
+ getIndexName()
+ "] ->? "
+ invoke
+ '@'
+ positions.getPosition(invoke);
}
@Override
public <T> T accept(CorrelationVisitor<T> visitor) {
return visitor.visitEscapeCorrelation(this);
}
}
| 2,287
| 29.506667
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/ReadWriteCorrelation.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
import com.ibm.wala.cast.ir.ssa.AbstractReflectiveGet;
import com.ibm.wala.cast.ir.ssa.AbstractReflectivePut;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import java.util.Set;
/**
* The most basic form of correlation: an intra-procedurally correlated pair of a dynamic property
* read and a dynamic property write.
*
* @author mschaefer
*/
public class ReadWriteCorrelation extends Correlation {
private final AbstractReflectiveGet get;
private final AbstractReflectivePut put;
public ReadWriteCorrelation(
AbstractReflectiveGet get,
AbstractReflectivePut put,
String indexName,
Set<String> flownThroughLocals) {
super(indexName, flownThroughLocals);
this.get = get;
this.put = put;
}
@Override
public Position getStartPosition(SSASourcePositionMap positions) {
return positions.getPosition(get);
}
@Override
public Position getEndPosition(SSASourcePositionMap positions) {
return positions.getPosition(put);
}
@Override
public String pp(SSASourcePositionMap positions) {
return get
+ "@"
+ positions.getPosition(get)
+ " ["
+ getIndexName()
+ "]-> "
+ put
+ '@'
+ positions.getPosition(put);
}
@Override
public <T> T accept(CorrelationVisitor<T> visitor) {
return visitor.visitReadWriteCorrelation(this);
}
}
| 1,814
| 26.089552
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/SSASourcePositionMap.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.intset.OrdinalSetMapping;
/**
* Utility class used by {@link CorrelationSummary} to map SSA instructions to source positions.
*
* @author mschaefer
*/
public class SSASourcePositionMap {
private final AstMethod method;
private final OrdinalSetMapping<SSAInstruction> instrIndices;
public SSASourcePositionMap(AstMethod method, OrdinalSetMapping<SSAInstruction> instrIndices) {
this.method = method;
this.instrIndices = instrIndices;
}
public Position getPosition(SSAInstruction inst) {
return method.getSourcePosition(instrIndices.getMappedIndex(inst));
}
}
| 1,186
| 31.081081
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/CAstRewriterExt.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NoKey;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Extension of {@link CAstRewriter} which allows adding or deleting control flow edges, and keeps
* track of the current entity.
*
* <p>TODO: This class is an unholy mess. It should be restructured considerably.
*
* @author mschaefer
*/
public abstract class CAstRewriterExt extends CAstRewriter<NodePos, NoKey> {
/**
* A control flow edge to be added to the CFG.
*
* @author mschaefer
*/
protected static class Edge {
private final CAstNode from;
private final Object label;
private final CAstNode to;
public Edge(CAstNode from, Object label, CAstNode to) {
assert from != null;
assert to != null;
this.from = from;
this.label = label;
this.to = to;
}
@Override
public int hashCode() {
final int prime = 31;
int result = prime + from.hashCode();
result = prime * result + ((label == null) ? 0 : label.hashCode());
result = prime * result + to.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Edge)) return false;
Edge that = (Edge) obj;
return this.from.equals(that.from)
&& Objects.equals(this.label, that.label)
&& this.to.equals(that.to);
}
}
private final Map<CAstControlFlowMap, Set<CAstNode>> extra_nodes = HashMapFactory.make();
private final Map<CAstControlFlowMap, Set<Edge>> extra_flow = HashMapFactory.make();
private final Map<CAstControlFlowMap, Set<CAstNode>> flow_to_delete = HashMapFactory.make();
// information about an entity to add to the AST
private static class Entity {
private final CAstNode anchor;
private final CAstEntity me;
public Entity(CAstNode anchor, CAstEntity me) {
assert me != null;
this.anchor = anchor;
this.me = me;
}
@Override
public int hashCode() {
final int prime = 31;
int result = prime + ((anchor == null) ? 0 : anchor.hashCode());
return prime * result + me.hashCode();
}
}
private final HashSet<Entity> entities_to_add = HashSetFactory.make();
private final ArrayDeque<CAstEntity> entities = new ArrayDeque<>();
public CAstNode addNode(CAstNode node, CAstControlFlowMap flow) {
Set<CAstNode> nodes = extra_nodes.get(flow);
if (nodes == null) extra_nodes.put(flow, nodes = HashSetFactory.make());
nodes.add(node);
return node;
}
public CAstNode addFlow(CAstNode node, Object label, CAstNode target, CAstControlFlowMap flow) {
Set<Edge> edges = extra_flow.get(flow);
if (edges == null) extra_flow.put(flow, edges = HashSetFactory.make());
edges.add(new Edge(node, label, target));
return node;
}
public void deleteFlow(CAstNode node, CAstEntity entity) {
CAstControlFlowMap flow = entity.getControlFlow();
Set<CAstNode> tmp = flow_to_delete.get(flow);
if (tmp == null) flow_to_delete.put(flow, tmp = HashSetFactory.make());
tmp.add(node);
}
protected boolean isFlowDeleted(CAstNode node, CAstEntity entity) {
CAstControlFlowMap flow = entity.getControlFlow();
return flow_to_delete.containsKey(flow) && flow_to_delete.get(flow).contains(node);
}
public CAstEntity getCurrentEntity() {
return entities.peek();
}
public Iterable<CAstEntity> getEnclosingEntities() {
return entities;
}
public void addEntity(CAstNode anchor, CAstEntity entity) {
entities_to_add.add(new Entity(anchor, entity));
}
@Override
protected Map<CAstNode, Collection<CAstEntity>> copyChildren(
CAstNode root,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap,
Map<CAstNode, Collection<CAstEntity>> children) {
Map<CAstNode, Collection<CAstEntity>> map = super.copyChildren(root, nodeMap, children);
// extend with local mapping information
for (Iterator<Entity> es = entities_to_add.iterator(); es.hasNext(); ) {
Entity e = es.next();
boolean relevant =
NodePos.inSubtree(e.anchor, nodeMap.get(Pair.make(root, null)))
|| NodePos.inSubtree(e.anchor, root);
if (relevant) {
Collection<CAstEntity> c = map.get(e.anchor);
if (c == null) map.put(e.anchor, c = HashSetFactory.make());
c.add(e.me);
es.remove();
}
}
return map;
}
@Override
protected CAstNode flowOutTo(
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap,
CAstNode oldSource,
Object label,
CAstNode oldTarget,
CAstControlFlowMap orig,
CAstSourcePositionMap src) {
if (oldTarget == CAstControlFlowMap.EXCEPTION_TO_EXIT) return oldTarget;
Assertions.UNREACHABLE();
return super.flowOutTo(nodeMap, oldSource, label, oldTarget, orig, src);
}
@Override
protected CAstControlFlowMap copyFlow(
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap,
CAstControlFlowMap orig,
CAstSourcePositionMap newSrc) {
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMapCopy = HashMapFactory.make(nodeMap);
// delete flow if necessary
// TODO: this is bad; what if one of the deleted nodes occurs as a cflow target?
if (flow_to_delete.containsKey(orig)) {
for (CAstNode node : flow_to_delete.get(orig)) {
nodeMapCopy.remove(Pair.make(node, null));
}
// flow_to_delete.remove(orig);
}
CAstControlFlowRecorder flow =
(CAstControlFlowRecorder) super.copyFlow(nodeMapCopy, orig, newSrc);
// extend with local flow information
if (extra_nodes.containsKey(orig)) {
for (CAstNode nd : extra_nodes.get(orig)) flow.map(nd, nd);
}
if (extra_flow.containsKey(orig)) {
for (Edge e : extra_flow.get(orig)) {
CAstNode from = e.from;
Object label = e.label;
CAstNode to = e.to;
if (nodeMap.containsKey(Pair.make(from, null))) from = nodeMap.get(Pair.make(from, null));
if (nodeMap.containsKey(Pair.make(to, null))) to = nodeMap.get(Pair.make(to, null));
if (!flow.isMapped(from)) flow.map(from, from);
if (!flow.isMapped(to)) flow.map(to, to);
flow.add(from, to, label);
}
/*
* Here, we would like to say extra_flow.remove(orig) to get rid of the extra control flow
* information, but that would not be correct: a single old cfg may be carved up into several
* new ones, each of which needs to be extended with the appropriate extra flow from the old cfg.
*
* Unfortunately, we now end up extending _every_ new cfg with _all_ the extra flow from the old
* cfg, which doesn't sound right either.
*/
}
return flow;
}
Map<CAstEntity, CAstEntity> rewrite_cache = HashMapFactory.make();
@Override
public CAstEntity rewrite(CAstEntity root) {
// avoid rewriting the same entity more than once
// TODO: figure out why this happens in the first place
if (rewrite_cache.containsKey(root)) {
return rewrite_cache.get(root);
} else {
entities.push(root);
enterEntity(root);
CAstEntity entity = super.rewrite(root);
rewrite_cache.put(root, entity);
leaveEntity();
entities.pop();
return entity;
}
}
protected void enterEntity(@SuppressWarnings("unused") CAstEntity entity) {}
protected void leaveEntity() {}
public CAstRewriterExt(CAst Ast, boolean recursive, NodePos rootContext) {
super(Ast, recursive, rootContext);
}
}
| 8,564
| 33.123506
| 103
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ChildPos.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstNode;
/**
* A {@link NodePos} for a non-root node; includes information about the parent node, the child
* index, and the position of the parent node.
*
* @author mschaefer
*/
public class ChildPos extends NodePos {
private final CAstNode parent;
private final int index;
private final NodePos parent_pos;
public ChildPos(CAstNode parent, int index, NodePos parent_pos) {
this.parent = parent;
this.index = index;
this.parent_pos = parent_pos;
}
public CAstNode getParent() {
return parent;
}
public int getIndex() {
return index;
}
public NodePos getParentPos() {
return parent_pos;
}
public CAstNode getChild() {
return parent.getChild(index);
}
public ChildPos getChildPos(int index) {
return new ChildPos(this.getChild(), index, this);
}
@Override
public <A> A accept(PosSwitch<A> ps) {
return ps.caseChildPos(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + index;
result = prime * result + ((parent == null) ? 0 : parent.hashCode());
result = prime * result + ((parent_pos == null) ? 0 : parent_pos.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ChildPos other = (ChildPos) obj;
if (index != other.index) return false;
if (parent == null) {
if (other.parent != null) return false;
} else if (!parent.equals(other.parent)) return false;
if (parent_pos == null) {
if (other.parent_pos != null) return false;
} else if (!parent_pos.equals(other.parent_pos)) return false;
return true;
}
}
| 2,235
| 25.619048
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ClosureExtractor.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import static com.ibm.wala.cast.tree.CAstNode.ASSIGN;
import static com.ibm.wala.cast.tree.CAstNode.BINARY_EXPR;
import static com.ibm.wala.cast.tree.CAstNode.BLOCK_STMT;
import static com.ibm.wala.cast.tree.CAstNode.CALL;
import static com.ibm.wala.cast.tree.CAstNode.CONSTANT;
import static com.ibm.wala.cast.tree.CAstNode.DECL_STMT;
import static com.ibm.wala.cast.tree.CAstNode.EMPTY;
import static com.ibm.wala.cast.tree.CAstNode.FUNCTION_EXPR;
import static com.ibm.wala.cast.tree.CAstNode.FUNCTION_STMT;
import static com.ibm.wala.cast.tree.CAstNode.GOTO;
import static com.ibm.wala.cast.tree.CAstNode.IF_STMT;
import static com.ibm.wala.cast.tree.CAstNode.LOCAL_SCOPE;
import static com.ibm.wala.cast.tree.CAstNode.OBJECT_LITERAL;
import static com.ibm.wala.cast.tree.CAstNode.OBJECT_REF;
import static com.ibm.wala.cast.tree.CAstNode.OPERATOR;
import static com.ibm.wala.cast.tree.CAstNode.RETURN;
import static com.ibm.wala.cast.tree.CAstNode.TRY;
import static com.ibm.wala.cast.tree.CAstNode.VAR;
import com.ibm.wala.cast.js.translator.JSAstTranslator;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstNodeTypeMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.cast.tree.impl.CAstSymbolImpl;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NoKey;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A CAst rewriter for extracting bits of code into one-shot closures. What to extract is determined
* by an {@link ExtractionPolicy}.
*
* <p>For instance, a {@link ForInBodyExtractionPolicy} extracts the body of every for-in loop in
* the program, whereas a {@link CorrelatedPairExtractionPolicy} extracts pieces of code containing
* correlated property reads and writes of the same property.
*
* <p>As an example, consider the following function:
*
* <pre>
* function extend(dest, src) {
* for(var p in src)
* dest[p] = src[p];
* }
* </pre>
*
* <p>Under both {@link ForInBodyExtractionPolicy} and {@link CorrelatedPairExtractionPolicy}, this
* should be transformed into
*
* <pre>
* function extend(dest, src) {
* for(var p in src)
* (function _forin_body_0(p) {
* dest[p] = src[p];
* })(p);
* }
* </pre>
*
* <p>There are four issues to be considered here.
*
* <ul>
* <li><b>References to {@code this}</b>:
* <p>If the code to extract contains references to {@code this}, these references have to be
* rewritten; otherwise they would refer to the global object in the transformed code.
* <p>We do this by giving the extracted function an extra parameter {@code thi$}, and
* rewriting {@code this} to {@code thi$} within the extracted code.
* <p>For instance,
* <pre>
* Object.prototype.extend = function(src) {
* for(var p in src)
* this[p] = src[p];
* }
* </pre>
* <p>becomes
* <pre>
* Object.prototype.extend = function(src) {
* for(var p in src)
* (function _forin_body_0(p, thi$) {
* thi$[p] = src[p];
* })(p, this);
* }
* </pre>
* <li><b>Local variable declarations</b>:
* <p>Local variable declarations inside the extracted code have to be hoisted to the
* enclosing function; otherwise they would become local variables of the extracted function
* instead.
* <p>This is already taken care of by the translation from Rhino's AST to CAst.
* <p>Optionally, the policy can request that one local variable of the surrounding function
* be turned into a local variable of the extracted closure. The rewriter checks that this is
* possible: the code to extract must not contain function calls or {@code new} expressions,
* and it must not contain {@code break}, {@code continue}, or {@code return} statements. The
* former requirement prevents a called function from observing a different value of the local
* variable than before. The latter requirement is necessary because the final value of the
* localised variable needs to be returned and assigned to its counterpart in the surrounding
* function; since non-local jumps are encoded by special return values (see next item), this
* would no longer be possible.
* <li><b>{@code break}, {@code continue}, {@code return}</b>:
* <p>A {@code break} or {@code continue} statement within the extracted loop body that refers
* to the loop itself or an enclosing loop would become invalid in the transformed code. A
* {@code return} statement would no longer return from the enclosing function, but instead
* from the extracted function.
* <p>We transform all three statements into {@code return} statements returning an object
* literal with a property {@code type} indicating whether this is a 'goto' (i.e., {@code
* break} or {@code return}) or a 'return'. In the former case, the 'target' property contains
* an integer identifying the jump target; in the latter case, the 'value' property contains
* the value to return.
* <p>The return value of the extracted function is then examined to determine whether it
* completed normally (i.e., returned {@code undefined}), or whether it returned an object
* indicating special control flow.
* <p>For example, consider this code from MooTools:
* <pre>
* for(var style in Element.ShortStyles) {
* if(property != style)
* continue;
* for(var s in Element.ShortStyles[style])
* result.push(this.getStyle(s));
* return result.join(' ');
* }
* </pre>
* <p>Under {@link ForInBodyExtractionPolicy}, this is transformed into
* <pre>
* for(var style in Element.ShortStyles) {
* var s;
* re$ = (function _forin_body_0(style, thi$) {
* if(property != style)
* return { type: 'goto', target: 1 };
* for(s in Element.ShortStyles[style]) {
* (function _forin_body_2(s) {
* result.push(thi$.getStyle(s));
* })(s);
* }
* return { type: 'return', value: result.join(' ') };
* })(style, this);
* if(re$) {
* if(re$.type == 'return')
* return re$.value;
* if(re$.type == 'goto') {
* if(re$.target == 1)
* continue;
* }
* }
* }
* </pre>
* <p>Note that at the CAst level, {@code break} and {@code continue} are represented as
* {@code goto} statements, which simplifies the translation somewhat. The numerical encoding
* of jump targets does not matter as long as the extracted function and the fixup code agree
* on which number represents which label.
* <li><b>Assignment to loop variable</b>:
* <p>The loop body may assign to the loop variable. If the variable is referenced after the
* loop, this assignment needs to be propagated back to the enclosing function in the
* extracted code.
* <p><b>TODO:</b> This is not handled at the moment.
* </ul>
*
* <p>Finally, note that exceptions do not need to be handled specially.
*
* @author mschaefer
*/
public class ClosureExtractor extends CAstRewriterExt {
private final ArrayDeque<ExtractionPolicy> policies = new ArrayDeque<>();
private final ExtractionPolicyFactory policyFactory;
private static final boolean LOCALISE = true;
// names for extracted functions are built from this string with a number appended
private static final String EXTRACTED_FUN_BASENAME = "_forin_body_";
private final NodeLabeller labeller = new NodeLabeller();
public ClosureExtractor(CAst Ast, ExtractionPolicyFactory policyFactory) {
super(Ast, true, new RootPos());
this.policyFactory = policyFactory;
}
@Override
protected void enterEntity(CAstEntity entity) {
policies.push(policyFactory.createPolicy(entity));
}
@Override
protected void leaveEntity() {
policies.pop();
}
@Override
protected CAstNode copyNodes(
CAstNode root,
CAstControlFlowMap cfg,
NodePos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
switch (root.getKind()) {
case OPERATOR:
return root;
case CONSTANT:
return copyConstant(root, context, nodeMap);
case BLOCK_STMT:
return copyBlock(root, cfg, context, nodeMap);
case RETURN:
return copyReturn(root, cfg, context, nodeMap);
case VAR:
return copyVar(root, cfg, context, nodeMap);
case GOTO:
return copyGoto(root, cfg, context, nodeMap);
default:
return copyNode(root, cfg, context, nodeMap);
}
}
/* Constants are not affected by the rewriting, they are just copied. */
private CAstNode copyConstant(
CAstNode root, NodePos context, Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
CAstNode newNode = Ast.makeConstant(root.getValue());
nodeMap.put(Pair.make(root, context.key()), newNode);
return newNode;
}
/* Ask the policy whether it wants anything extracted from this block; otherwise the node is simply copied. */
private CAstNode copyBlock(
CAstNode root,
CAstControlFlowMap cfg,
NodePos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
List<ExtractionRegion> regions = policies.getFirst().extract(root);
if (regions == null || usesArguments(root)) {
return copyNode(root, cfg, context, nodeMap);
} else {
ArrayList<CAstNode> copied_children = new ArrayList<>();
int next_child = 0;
// code in between regions is handled by invoking copyNodes, the regions themselves by
// extractRegion
for (ExtractionRegion region : regions) {
for (; next_child < region.getStart(); ++next_child)
copied_children.add(
copyNodes(
root.getChild(next_child),
cfg,
new ChildPos(root, next_child, context),
nodeMap));
copied_children.addAll(
extractRegion(root, cfg, new ExtractionPos(root, region, context), nodeMap));
next_child = region.getEnd();
}
for (; next_child < root.getChildCount(); ++next_child)
copied_children.add(
copyNodes(
root.getChild(next_child), cfg, new ChildPos(root, next_child, context), nodeMap));
CAstNode newNode = Ast.makeNode(root.getKind(), copied_children);
nodeMap.put(Pair.make(root, context.key()), newNode);
return newNode;
}
}
/*
* Normal variables are just copied, but 'this' references need to be rewritten if we are inside an extracted
* function body.
*/
private CAstNode copyVar(
CAstNode root,
CAstControlFlowMap cfg,
NodePos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
/*
* If this node is a "this" reference, the outermost enclosing extracted function needs to pass in
* the value of "this" as a parameter.
*
* NB: This has to be done by the _outermost_ function. If it were done by an inner function instead,
* the outermost one may not pass in the value of "this" at all, so the inner one would
* get the wrong value.
*/
if (root.getChild(0).getValue().equals("this")) {
ExtractionPos epos = ExtractionPos.getOutermostEnclosingExtractionPos(context);
if (epos != null) {
epos.addThis();
CAstNode newNode = makeVarRef(epos.getThisParmName());
addExnFlow(newNode, JavaScriptTypes.ReferenceError, getCurrentEntity(), context);
nodeMap.put(Pair.make(root, context.key()), newNode);
return newNode;
} else {
return copyNode(root, cfg, context, nodeMap);
}
} else {
return copyNode(root, cfg, context, nodeMap);
}
}
/*
* 'break' and 'continue' statements are both encoded as GOTO. If they refer to a target outside the innermost
* enclosing extracted function body, they are rewritten into a 'return' statement.
*/
private CAstNode copyGoto(
CAstNode root,
CAstControlFlowMap cfg,
NodePos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
CAstNode target = getCurrentEntity().getControlFlow().getTarget(root, null);
ExtractionPos epos = ExtractionPos.getEnclosingExtractionPos(context);
if (epos != null && !NodePos.inSubtree(target, epos.getParent())) {
epos.addGotoTarget(
root.getChildCount() > 0 ? (String) root.getChild(0).getValue() : null, target);
int label = labeller.addNode(target);
// return { type: 'goto', target: <label> }
CAstNode returnLit =
addNode(
Ast.makeNode(
OBJECT_LITERAL,
addExnFlow(
Ast.makeNode(
CALL,
addExnFlow(
makeVarRef("Object"),
JavaScriptTypes.ReferenceError,
getCurrentEntity(),
context),
Ast.makeConstant("ctor")),
null,
getCurrentEntity(),
context),
Ast.makeConstant("type"),
Ast.makeConstant("goto"),
Ast.makeConstant("target"),
Ast.makeConstant(String.valueOf((double) label))),
getCurrentEntity().getControlFlow());
addNode(returnLit, getCurrentEntity().getControlFlow());
CAstNode newNode = Ast.makeNode(RETURN, returnLit);
// remove outgoing cfg edges of the old node
deleteFlow(root, getCurrentEntity());
nodeMap.put(Pair.make(root, context.key()), newNode);
return newNode;
} else {
return copyNode(root, cfg, context, nodeMap);
}
}
/* 'return' statements inside an extracted function body need to be encoded in a similar fashion. */
private CAstNode copyReturn(
CAstNode root,
CAstControlFlowMap cfg,
NodePos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
ExtractionPos epos = ExtractionPos.getEnclosingExtractionPos(context);
if (epos == null || isSynthetic(root)) return copyNode(root, cfg, context, nodeMap);
// add a return to every enclosing extracted function body
do {
epos.addReturn();
epos = ExtractionPos.getEnclosingExtractionPos(epos.getParentPos());
} while (epos != null);
// emit appropriate 'return' statement
if (root.getChildCount() > 0) {
// return { type: 'return', value: <retval> }
CAstNode retval = copyNodes(root.getChild(0), cfg, new ChildPos(root, 0, context), nodeMap);
CAstNode newNode =
Ast.makeNode(
RETURN,
addNode(
Ast.makeNode(
OBJECT_LITERAL,
addExnFlow(
Ast.makeNode(
CALL,
addExnFlow(
makeVarRef("Object"),
JavaScriptTypes.ReferenceError,
getCurrentEntity(),
context),
Ast.makeConstant("ctor")),
null,
getCurrentEntity(),
context),
Ast.makeConstant("type"),
Ast.makeConstant("return"),
Ast.makeConstant("value"),
retval),
getCurrentEntity().getControlFlow()));
nodeMap.put(Pair.make(root, context.key()), newNode);
return newNode;
} else {
// return { type: 'return' }
CAstNode newNode =
Ast.makeNode(
RETURN,
addNode(
Ast.makeNode(
OBJECT_LITERAL,
addExnFlow(
Ast.makeNode(
CALL,
addExnFlow(
makeVarRef("Object"),
JavaScriptTypes.ReferenceError,
getCurrentEntity(),
context),
Ast.makeConstant("ctor")),
null,
getCurrentEntity(),
context),
Ast.makeConstant("type"),
Ast.makeConstant("return")),
getCurrentEntity().getControlFlow()));
nodeMap.put(Pair.make(root, context.key()), newNode);
return newNode;
}
}
/* Recursively copy child nodes. */
private CAstNode copyNode(
CAstNode node,
CAstControlFlowMap cfg,
NodePos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
List<CAstNode> children = new ArrayList<>(node.getChildCount());
// copy children
int i = 0;
for (CAstNode child : node.getChildren())
children.add(copyNodes(child, cfg, new ChildPos(node, i++, context), nodeMap));
// for non-constant case labels, the case expressions appear as labels on CFG edges; rewrite
// those as well
for (Object label : cfg.getTargetLabels(node)) {
if (label instanceof CAstNode) {
copyNodes((CAstNode) label, cfg, new LabelPos(node, context), nodeMap);
}
}
CAstNode newNode = Ast.makeNode(node.getKind(), children);
nodeMap.put(Pair.make(node, context.key()), newNode);
// if this node has a control flow successor beyond the innermost enclosing extracted function
// loop, we need to reroute
ExtractionPos epos = ExtractionPos.getEnclosingExtractionPos(context);
if (!isFlowDeleted(newNode, getCurrentEntity()) && epos != null) {
// CAstControlFlowMap cfg = getCurrentEntity().getControlFlow();
Collection<Object> labels = cfg.getTargetLabels(node);
boolean invalidateCFlow = false;
for (Object label : labels) {
CAstNode target = cfg.getTarget(node, label);
if (target != CAstControlFlowMap.EXCEPTION_TO_EXIT && !epos.contains(target)) {
invalidateCFlow = true;
break;
}
}
if (invalidateCFlow) {
deleteFlow(node, getCurrentEntity());
for (Object label : labels) {
CAstNode target = cfg.getTarget(node, label);
if (epos.contains(target)) addFlow(node, label, target, cfg);
else addFlow(node, label, CAstControlFlowMap.EXCEPTION_TO_EXIT, cfg);
}
}
}
return newNode;
}
private int anonymous_counter = 0;
private List<CAstNode> extractRegion(
CAstNode root,
CAstControlFlowMap cfg,
ExtractionPos context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
CAstEntity entity = getCurrentEntity();
// whether we are extracting a single statement that is itself a block
boolean extractingBlock =
context.getStart() + 1 == context.getEnd()
&& root.getChild(context.getStart()).getKind() == BLOCK_STMT;
// whether we are extracting the body of a local scope
boolean extractingLocalScope = false;
// whether we are extracting an empty loop body
boolean extractingEmpty = false;
String name = EXTRACTED_FUN_BASENAME + anonymous_counter++;
// Create a new entity for the extracted function.
ExtractedFunction new_entity = new ExtractedFunction(name, context);
context.setExtractedEntity(new_entity);
// rewrite the code to be extracted
/*
* First, we need to massage the code a little bit, prepending an assignment of the form '<name> = <name>'
* and appending a RETURN statement if it may complete normally (i.e., if execution may 'fall off'
* the end). Additionally, if the extraction starts inside a nested BLOCK_EXPR, we flatten it out into a list
* of statements.
*
* The whole thing is then wrapped into a block.
*/
ArrayList<CAstNode> prologue = new ArrayList<>();
ArrayList<CAstNode> fun_body_stmts = new ArrayList<>();
// if we are extracting a block, unwrap it
if (extractingBlock) {
CAstNode block = root.getChild(context.getStart());
fun_body_stmts.addAll(block.getChildren());
} else {
if (context.getRegion() instanceof TwoLevelExtractionRegion) {
CAstNode start = root.getChild(context.getStart());
TwoLevelExtractionRegion tler = (TwoLevelExtractionRegion) context.getRegion();
if (tler.getEndInner() != -1)
throw new UnimplementedError("Two-level extraction not fully implemented.");
int i;
if (start.getKind() == CAstNode.BLOCK_STMT) {
for (i = 0; i < tler.getStartInner(); ++i)
prologue.add(copyNodes(start.getChild(i), cfg, context, nodeMap));
if (i + 1 == start.getChildCount()) {
fun_body_stmts.add(addSpuriousExnFlow(start.getChild(i), cfg));
} else {
for (int j = 0; j + i < start.getChildCount(); ++j)
fun_body_stmts.add(addSpuriousExnFlow(start.getChild(j + i), cfg));
}
for (i = context.getStart() + 1; i < context.getEnd(); ++i)
fun_body_stmts.add(root.getChild(i));
} else if (start.getKind() == CAstNode.LOCAL_SCOPE) {
if (tler.getStartInner() != 0 || tler.getEnd() != tler.getStart() + 1)
throw new UnimplementedError("Unsupported two-level extraction");
fun_body_stmts.add(start.getChild(0));
extractingLocalScope = true;
} else {
throw new UnimplementedError("Unsupported two-level.");
}
} else {
if (context.getEnd() > context.getStart() + 1) {
List<CAstNode> stmts = new ArrayList<>(context.getEnd() - context.getStart());
for (int i = context.getStart(); i < context.getEnd(); ++i) stmts.add(root.getChild(i));
fun_body_stmts.add(Ast.makeNode(root.getKind(), stmts));
} else {
CAstNode node_to_extract = root.getChild(context.getStart());
if (node_to_extract.getKind() == CAstNode.EMPTY) extractingEmpty = true;
fun_body_stmts.add(wrapIn(BLOCK_STMT, node_to_extract));
}
}
}
List<String> locals = context.getRegion().getLocals();
String theLocal = null;
if (LOCALISE && locals.size() == 1 && noJumpsAndNoCalls(fun_body_stmts)) {
// the variable can be localised, remember its name
theLocal = locals.get(0);
// append "return <theLocal>;" to the end of the function body
CAstNode retLocal =
Ast.makeNode(
RETURN,
addExnFlow(makeVarRef(theLocal), JavaScriptTypes.ReferenceError, entity, context));
markSynthetic(retLocal);
// insert as last stmt if fun_body_stmts is a single block, otherwise append
if (fun_body_stmts.size() == 1 && fun_body_stmts.get(0).getKind() == BLOCK_STMT) {
List<CAstNode> stmts = new ArrayList<>(fun_body_stmts.get(0).getChildCount() + 1);
stmts.addAll(fun_body_stmts.get(0).getChildren());
stmts.add(retLocal);
fun_body_stmts.set(0, Ast.makeNode(BLOCK_STMT, stmts));
} else {
fun_body_stmts.add(retLocal);
}
// prepend declaration "var <theLocal>;"
CAstNode theLocalDecl =
Ast.makeNode(
DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(theLocal, JSAstTranslator.Any)),
addExnFlow(
makeVarRef("$$undefined"), JavaScriptTypes.ReferenceError, entity, context));
if (fun_body_stmts.size() > 1) {
CAstNode newBlock = Ast.makeNode(BLOCK_STMT, new ArrayList<>(fun_body_stmts));
fun_body_stmts.clear();
fun_body_stmts.add(newBlock);
}
// fun_body_stmts.add(0, Ast.makeNode(BLOCK_STMT, theLocalDecl));
fun_body_stmts.add(0, theLocalDecl);
}
CAstNode fun_body = Ast.makeNode(BLOCK_STMT, fun_body_stmts);
/*
* Now we rewrite the body and construct a Rewrite object.
*/
final Map<Pair<CAstNode, NoKey>, CAstNode> nodes = HashMapFactory.make();
final CAstNode newRoot = copyNodes(fun_body, cfg, context, nodes);
final CAstSourcePositionMap theSource = copySource(nodes, entity.getSourceMap());
final CAstControlFlowMap theCfg = copyFlow(nodes, entity.getControlFlow(), theSource);
final CAstNodeTypeMap theTypes = copyTypes(nodes, entity.getNodeTypeMap());
final Map<CAstNode, Collection<CAstEntity>> theChildren = HashMapFactory.make();
for (int i = context.getStart(); i < context.getEnd(); ++i)
theChildren.putAll(copyChildren(root.getChild(i), nodes, entity.getAllScopedEntities()));
Rewrite rw =
new Rewrite() {
@Override
public CAstNode newRoot() {
return newRoot;
}
@Override
public CAstControlFlowMap newCfg() {
return theCfg;
}
@Override
public CAstSourcePositionMap newPos() {
return theSource;
}
@Override
public CAstNodeTypeMap newTypes() {
return theTypes;
}
@Override
public Map<CAstNode, Collection<CAstEntity>> newChildren() {
return theChildren;
}
@Override
public CAstNode[] newDefaults() {
return null;
}
};
new_entity.setRewrite(rw);
/* Now we construct a call to the extracted function.
*
* If the body never referenced 'this', the function call will be of the form
*
* <extracted_fun_expr>("do", <global_object>, <parm1>, ... , <parmn>)
*
* The "do" argument is a dummy argument required by the CAst encoding for JavaScript.
*
* If, on the other hand, there are references to 'this', these will have been rewritten into references
* to an additional parameter 'thi$', so the call will be of the form
*
* <extracted_fun_expr>("do", <global_object>, <parm1>, ..., <parmn>, this)
*
* if we are in a function, and
*
* <extracted_fun_expr>("do", <global_object>, <parm1>, ..., <parmn>, <global_object>)
*
* at the top-level.
*
* In any case, we also add a CFG edge for a ReferenceError exception on the <parmi> arguments, and for
* a null pointer exception on the call; these are infeasible, but we add them anyway to get the same AST
* as with a manual extraction.
*/
List<CAstNode> args = new ArrayList<>();
CAstNode funExpr = Ast.makeNode(FUNCTION_EXPR, Ast.makeConstant(new_entity));
args.add(funExpr);
context.setCallSite(funExpr);
ExtractionPos outer = ExtractionPos.getEnclosingExtractionPos(context.getParentPos());
if (outer == null) {
addEntity(funExpr, new_entity);
} else {
outer.addNestedPos(context);
}
args.add(Ast.makeConstant("do"));
args.add(addNode(makeVarRef("__WALA__int3rnal__global"), entity.getControlFlow()));
for (String parmName : context.getParameters())
args.add(addExnFlow(makeVarRef(parmName), JavaScriptTypes.ReferenceError, entity, context));
if (context.containsThis())
args.add(inFunction() ? Ast.makeNode(VAR, Ast.makeConstant("this")) : Ast.makeConstant(null));
CAstNode call = Ast.makeNode(CALL, args);
addExnFlow(call, null, entity, context);
// if the extracted code contains jumps, we need to insert some fix-up code
List<CAstNode> stmts = new ArrayList<>(prologue);
if (context.containsJump()) {
CAstNode decl =
Ast.makeNode(
ASSIGN,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context),
call);
CAstNode fixup = null;
if (context.containsGoto()) fixup = createGotoFixup(context, entity);
if (context.containsReturn()) {
if (context.isOutermost()) {
CAstNode return_fixup = createReturnFixup(context, entity);
if (fixup != null) fixup = Ast.makeNode(BLOCK_STMT, return_fixup, fixup);
else fixup = return_fixup;
} else {
fixup =
Ast.makeNode(
RETURN,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context));
}
}
// if this is a nested for-in loop, we need to pass on unhandled jumps
if (!context.isOutermost() && (context.containsReturn() || context.containsOuterGoto()))
fixup =
Ast.makeNode(
RETURN,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context));
// if(re$) <check>;
fixup =
Ast.makeNode(
IF_STMT,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context),
Ast.makeNode(
LOCAL_SCOPE, wrapIn(BLOCK_STMT, fixup == null ? Ast.makeNode(EMPTY) : fixup)));
stmts.add(decl);
stmts.add(fixup);
} else if (theLocal != null) {
// assign final value of the localised variable back
stmts.add(
Ast.makeNode(
CAstNode.ASSIGN,
addExnFlow(makeVarRef(theLocal), JavaScriptTypes.ReferenceError, entity, context),
call));
} else {
stmts.add(call);
}
if (extractingBlock) {
// put the call and the fixup code together
CAstNode newNode = Ast.makeNode(BLOCK_STMT, stmts);
nodeMap.put(Pair.make(root, context.key()), newNode);
deleteFlow(root, getCurrentEntity());
stmts = Collections.singletonList(newNode);
}
if (extractingLocalScope || extractingEmpty) {
CAstNode newNode = Ast.makeNode(LOCAL_SCOPE, wrapIn(BLOCK_STMT, stmts));
stmts = Collections.singletonList(newNode);
}
return stmts;
}
private static CAstNode addSpuriousExnFlow(CAstNode node, CAstControlFlowMap cfg) {
CAstControlFlowRecorder flow = (CAstControlFlowRecorder) cfg;
if (node.getKind() == ASSIGN) {
if (node.getChild(0).getKind() == VAR) {
CAstNode var = node.getChild(0);
if (!flow.isMapped(var)) flow.map(var, var);
flow.add(var, CAstControlFlowMap.EXCEPTION_TO_EXIT, JavaScriptTypes.ReferenceError);
}
}
return node;
}
private CAstNode createReturnFixup(ExtractionPos context, CAstEntity entity) {
return Ast.makeNode(
IF_STMT,
Ast.makeNode(
BINARY_EXPR,
CAstOperator.OP_EQ,
addExnFlow(
Ast.makeNode(
OBJECT_REF,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context),
Ast.makeConstant("type")),
JavaScriptTypes.TypeError,
entity,
context),
Ast.makeConstant("return")),
Ast.makeNode(
RETURN,
addExnFlow(
Ast.makeNode(
OBJECT_REF,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context),
Ast.makeConstant("value")),
JavaScriptTypes.TypeError,
entity,
context)));
}
private CAstNode createGotoFixup(ExtractionPos context, CAstEntity entity) {
CAstNode fixup = null;
// add fixup code for every goto in the extracted code
for (Pair<String, CAstNode> goto_target : context.getGotoTargets()) {
// if(re$.target == <goto_target>) goto <goto_target>; else <fixup>
CAstNode cond =
Ast.makeNode(
BINARY_EXPR,
CAstOperator.OP_EQ,
addExnFlow(
Ast.makeNode(
OBJECT_REF,
addExnFlow(
makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context),
Ast.makeConstant("target")),
JavaScriptTypes.TypeError,
entity,
context),
Ast.makeConstant(String.valueOf((double) labeller.getLabel(goto_target.snd))));
CAstNode then_branch;
if (goto_target.fst != null)
then_branch = Ast.makeNode(GOTO, Ast.makeConstant(goto_target.fst));
else then_branch = Ast.makeNode(GOTO);
addFlow(then_branch, null, goto_target.snd, entity.getControlFlow());
if (fixup != null) fixup = Ast.makeNode(IF_STMT, cond, then_branch, fixup);
else fixup = Ast.makeNode(IF_STMT, cond, then_branch);
}
// add check whether re$ is actually a 'goto'
return Ast.makeNode(
IF_STMT,
Ast.makeNode(
BINARY_EXPR,
CAstOperator.OP_EQ,
addExnFlow(
Ast.makeNode(
OBJECT_REF,
addExnFlow(makeVarRef("re$"), JavaScriptTypes.ReferenceError, entity, context),
Ast.makeConstant("type")),
JavaScriptTypes.TypeError,
entity,
context),
Ast.makeConstant("goto")),
Ast.makeNode(LOCAL_SCOPE, wrapIn(BLOCK_STMT, fixup)));
}
// wrap given nodes into a node of the given kind, unless there is only a single node which is
// itself of the same kind
private CAstNode wrapIn(int kind, List<CAstNode> nodes) {
return nodes.size() == 1 ? wrapIn(kind, nodes.get(0)) : Ast.makeNode(kind, nodes);
}
// wrap given node into a node of the given kind, unless it is already of the same kind
private CAstNode wrapIn(int kind, CAstNode node) {
return node.getKind() == kind ? node : Ast.makeNode(kind, node);
}
// helper functions for adding exceptional CFG edges
private CAstNode addExnFlow(CAstNode node, Object label, CAstEntity entity, NodePos pos) {
return addExnFlow(node, label, entity.getControlFlow(), pos);
}
private CAstNode addExnFlow(CAstNode node, Object label, CAstControlFlowMap flow, NodePos pos) {
CAstNode target = getThrowTarget(pos);
return addFlow(node, label, target, flow);
}
// determine the innermost enclosing throw target at position pos
private CAstNode getThrowTarget(NodePos pos) {
return pos.accept(
new PosSwitch<>() {
@Override
public CAstNode caseRootPos(RootPos pos) {
return CAstControlFlowMap.EXCEPTION_TO_EXIT;
}
@Override
public CAstNode caseChildPos(ChildPos pos) {
int kind = pos.getParent().getKind();
if (kind == TRY && pos.getIndex() == 0) return pos.getParent().getChild(1);
if (kind == FUNCTION_EXPR || kind == FUNCTION_STMT)
return CAstControlFlowMap.EXCEPTION_TO_EXIT;
return getThrowTarget(pos.getParentPos());
}
@Override
public CAstNode caseForInLoopBodyPos(ExtractionPos pos) {
return getThrowTarget(pos.getParentPos());
}
@Override
public CAstNode caseLabelPos(LabelPos pos) {
return getThrowTarget(pos.getParentPos());
}
});
}
// helper function for creating VAR nodes
private CAstNode makeVarRef(String name) {
return Ast.makeNode(VAR, Ast.makeConstant(name));
}
// determine whether we are inside a function
private boolean inFunction() {
for (CAstEntity e : getEnclosingEntities())
if (e.getKind() == CAstEntity.FUNCTION_ENTITY) return true;
return false;
}
/*
* Due to the way CAst rewriting works, we sometimes have to insert nodes before rewriting
* a subtree. These nodes should not usually be rewritten again, however, so we mark them
* as "synthetic". Currently, this only applies to "return" statements.
*/
private final Set<CAstNode> synthetic = HashSetFactory.make();
private void markSynthetic(CAstNode node) {
this.synthetic.add(node);
}
private boolean isSynthetic(CAstNode node) {
return synthetic.contains(node);
}
private boolean noJumpsAndNoCalls(Collection<CAstNode> nodes) {
for (CAstNode node : nodes) if (!noJumpsAndNoCalls(node)) return false;
return true;
}
// determine whether the given subtree contains no unstructured control flow and calls
private boolean noJumpsAndNoCalls(CAstNode node) {
switch (node.getKind()) {
case CAstNode.BREAK:
case CAstNode.CONTINUE:
case CAstNode.GOTO:
case CAstNode.RETURN:
case CAstNode.CALL:
case CAstNode.NEW:
return false;
default:
// fall through to generic handlers below
}
for (CAstNode child : node.getChildren()) if (!noJumpsAndNoCalls(child)) return false;
return true;
}
// determines whether the given subtree refers to the variable "arguments"
private boolean usesArguments(CAstNode node) {
if (node.getKind() == CAstNode.VAR) {
return node.getChild(0).getValue().equals("arguments");
} else {
for (CAstNode child : node.getChildren()) if (usesArguments(child)) return true;
return false;
}
}
}
| 38,150
| 38.616822
| 113
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/CorrelatedPairExtractionPolicy.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.Correlation;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationSummary;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.EscapeCorrelation;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.ReadWriteCorrelation;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An {@link ExtractionPolicy} that specifies that correlated pairs should be extracted.
*
* <p>In principle, extracting an arbitrary correlated pair can be very difficult. We restrict our
* attention to the case where both read and write occur within the same block of statements, with
* the read preceding the write. In practice, most correlations are of this form.
*
* <p>TODO: The code for finding the correlated instructions is broken since Rhino only gives us
* line number positions. Consequently, it fails to find the relevant instructions every once in a
* while.
*
* @author mschaefer
*/
public class CorrelatedPairExtractionPolicy extends ExtractionPolicy {
private static final boolean DEBUG = false;
private final Map<CAstNode, List<ExtractionRegion>> region_map = HashMapFactory.make();
private CorrelatedPairExtractionPolicy() {}
private static void findNodesAtPos(
int kind, Position pos, CAstSourcePositionMap spmap, ChildPos nodep, Set<ChildPos> res) {
CAstNode node = nodep.getChild();
if (node == null) return;
Position ndpos = spmap.getPosition(node);
if (ndpos != null) {
// if we are in the wrong file or past the position pos, abort search
if (!ndpos.getURL().toString().equals(pos.getURL().toString())) return;
if (pos.getLastLine() >= 0 && ndpos.getFirstLine() > pos.getLastLine()) return;
// if(node.getKind() == kind && ndpos.getFirstLine() == pos.getFirstLine() &&
// ndpos.getLastLine() == pos.getLastLine())
if (node.getKind() == kind
&& ndpos.getFirstOffset() == pos.getFirstOffset()
&& ndpos.getLastOffset() == pos.getLastOffset()) res.add(nodep);
}
for (int i = 0; i < node.getChildCount(); ++i)
findNodesAtPos(kind, pos, spmap, nodep.getChildPos(i), res);
}
private static Set<ChildPos> findNodesAtPos(int kind, Position pos, CAstEntity entity) {
Set<ChildPos> res = HashSetFactory.make();
CAstSourcePositionMap spmap = entity.getSourceMap();
CAstNode ast = entity.getAST();
for (int i = 0; i < ast.getChildCount(); ++i)
findNodesAtPos(kind, pos, spmap, new ChildPos(ast, i, new RootPos()), res);
return res;
}
// create an ExtractRegion for the given correlation
private boolean addCorrelation(
CAstEntity entity, Correlation corr, CorrelationSummary correlations) {
Position startPos = corr.getStartPosition(correlations.getPositions()),
endPos = corr.getEndPosition(correlations.getPositions());
// TODO: enable these assertions; currently we're getting getLastLine() == -1 a lot
assert startPos.getFirstLine() != -1;
// assert startPos.getLastLine() != -1;
assert endPos.getFirstLine() != -1;
// assert endPos.getLastLine() != -1;
if (!entity.getPosition().getURL().toString().equals(startPos.getURL().toString())) return true;
Set<ChildPos> startNodes = findNodesAtPos(CAstNode.OBJECT_REF, startPos, entity);
Set<ChildPos> endNodes = null;
if (corr instanceof ReadWriteCorrelation) {
endNodes = findNodesAtPos(CAstNode.ASSIGN, endPos, entity);
} else if (corr instanceof EscapeCorrelation) {
int arity = ((EscapeCorrelation) corr).getNumberOfArguments();
endNodes = findNodesAtPos(CAstNode.CALL, endPos, entity);
for (Iterator<ChildPos> iter = endNodes.iterator(); iter.hasNext(); ) {
CAstNode candidate = iter.next().getChild();
// need to deduct three here: one for the function expression, one for "do"/"ctor", and one
// for the receiver expression
if (candidate.getChildCount() - 3 != arity) iter.remove();
}
} else {
throw new IllegalArgumentException("Unknown correlation type.");
}
if (startNodes.isEmpty() || endNodes.isEmpty()) {
if (DEBUG)
System.err.println(
"Couldn't find any "
+ (startNodes.isEmpty() ? endNodes.isEmpty() ? "boundary" : "start" : "end")
+ " nodes for correlation "
+ corr.pp(correlations.getPositions()));
return true;
}
ChildPos startNode, endNode;
filterNames(startNodes, corr.getIndexName());
filterNames(endNodes, corr.getIndexName());
Iterator<ChildPos> iter = startNodes.iterator();
if (startNodes.size() == 2 && endNodes.equals(startNodes)) {
startNode = iter.next();
endNode = iter.next();
} else if (startNodes.size() != 1) {
if (DEBUG)
System.err.println(
"Couldn't find unique start node for correlation "
+ corr.pp(correlations.getPositions()));
return false;
} else if (endNodes.size() != 1) {
if (DEBUG)
System.err.println(
"Couldn't find unique end node for correlation "
+ corr.pp(correlations.getPositions()));
return false;
} else {
startNode = startNodes.iterator().next();
endNode = endNodes.iterator().next();
}
List<String> locals =
corr.getFlownThroughLocals().size() == 1
? Collections.singletonList(corr.getFlownThroughLocals().iterator().next())
: Collections.<String>emptyList();
Pair<CAstNode, ? extends ExtractionRegion> region_info =
findClosestContainingBlock(entity, startNode, endNode, corr.getIndexName(), locals);
if (region_info == null) {
if (DEBUG)
System.err.println(
"Couldn't find enclosing block for correlation "
+ corr.pp(correlations.getPositions()));
return false;
}
List<ExtractionRegion> regions =
region_map.computeIfAbsent(region_info.fst, k -> new ArrayList<>());
for (int i = 0; i < regions.size(); ++i) {
ExtractionRegion region2 = regions.get(i);
if (region2.getEnd() <= region_info.snd.getStart()) continue;
if (region2.getStart() < region_info.snd.getEnd()) {
if (region_info.snd.getParameters().equals(region2.getParameters())) {
region2.setStart(Math.min(region_info.snd.getStart(), region2.getStart()));
region2.setEnd(Math.max(region_info.snd.getEnd(), region2.getEnd()));
if (DEBUG)
System.err.println(
"Successfully processed correlation " + corr.pp(correlations.getPositions()));
return true;
}
if (DEBUG) System.err.println("Overlapping regions.");
return false;
}
regions.add(i, region_info.snd);
if (DEBUG)
System.out.println(
"Successfully processed correlation " + corr.pp(correlations.getPositions()));
return true;
}
if (DEBUG)
System.out.println(
"Successfully processed correlation " + corr.pp(correlations.getPositions()));
regions.add(region_info.snd);
return true;
}
private static void filterNames(Set<ChildPos> nodes, String indexName) {
for (Iterator<ChildPos> iter = nodes.iterator(); iter.hasNext(); ) {
CAstNode node = iter.next().getChild();
if (node.getKind() == CAstNode.OBJECT_REF) {
CAstNode index = node.getChild(1);
if (index.getKind() != CAstNode.VAR || !index.getChild(0).getValue().equals(indexName)) {
iter.remove();
}
}
}
}
private static Pair<CAstNode, ? extends ExtractionRegion> findClosestContainingBlock(
CAstEntity entity,
ChildPos startNode,
ChildPos endNode,
String parmName,
List<String> locals) {
ChildPos pos = startNode;
CAstNode block = null;
int start = -1, end = 0;
int start_inner = -1, end_inner = -1;
do {
if (pos != startNode && pos.getParentPos() instanceof ChildPos)
pos = (ChildPos) pos.getParentPos();
// find the next closest block around the node at position "pos"
while (pos.getParent().getKind() != CAstNode.BLOCK_STMT) {
if (pos.getParentPos() instanceof ChildPos) pos = (ChildPos) pos.getParentPos();
else return null;
}
block = pos.getParent();
start = pos.getIndex();
end = getCoveringChildIndex(block, start, endNode.getChild()) + 1;
} while (end == 0);
// expand region to include forward goto targets
CAstControlFlowMap cfg = entity.getControlFlow();
for (int i = start; i < end; ++i) {
CAstNode stmt = block.getChild(i);
for (Object targetLabel : cfg.getTargetLabels(stmt)) {
CAstNode target = cfg.getTarget(stmt, targetLabel);
int targetIndex = getCoveringChildIndex(block, start, target);
if (targetIndex >= end) end = targetIndex + 1;
}
}
// special hack to handle "var p = ..., x = y[p];", where startNode = "y[p]"
if (block.getChild(0).getKind() == CAstNode.BLOCK_STMT && start == 0) {
final Iterator<CAstNode> blockChild = block.getChild(0).getChildren().iterator();
for (start_inner = 0; start_inner < block.getChild(0).getChildCount(); ++start_inner)
if (NodePos.inSubtree(startNode.getChild(), blockChild.next()))
return Pair.make(
block,
new TwoLevelExtractionRegion(
start, end, start_inner, end_inner, Collections.singletonList(parmName), locals));
}
// special hack to handle the case where we're extracting the body of a local scope
else if (block.getChild(start).getKind() == CAstNode.LOCAL_SCOPE && end == start + 1) {
return Pair.make(
block,
new TwoLevelExtractionRegion(
start, end, 0, -1, Collections.singletonList(parmName), locals));
}
return Pair.make(
block, new ExtractionRegion(start, end, Collections.singletonList(parmName), locals));
}
private static int getCoveringChildIndex(CAstNode parent, int start, CAstNode child) {
for (int i = start; i < parent.getChildCount(); ++i)
if (NodePos.inSubtree(child, parent.getChild(i))) return i;
return -1;
}
private static CorrelatedPairExtractionPolicy addCorrelations(
CAstEntity entity,
Map<Position, CorrelationSummary> summaries,
CorrelatedPairExtractionPolicy policy) {
// add correlations for this entity
if (entity.getAST() != null && summaries.containsKey(entity.getPosition())) {
CorrelationSummary correlations = summaries.get(entity.getPosition());
for (Correlation corr : correlations.getCorrelations())
policy.addCorrelation(entity, corr, correlations);
}
// recursively add correlations for scoped entities
Map<CAstNode, Collection<CAstEntity>> allScopedEntities = entity.getAllScopedEntities();
for (Collection<CAstEntity> scopedEntities : allScopedEntities.values())
for (CAstEntity scopedEntity : scopedEntities)
if (addCorrelations(scopedEntity, summaries, policy) == null) return null;
return policy;
}
public static CorrelatedPairExtractionPolicy make(
CAstEntity entity, Map<IMethod, CorrelationSummary> summaries) {
CorrelatedPairExtractionPolicy policy = new CorrelatedPairExtractionPolicy();
Map<Position, CorrelationSummary> summary_map = HashMapFactory.make();
for (Map.Entry<IMethod, CorrelationSummary> e : summaries.entrySet()) {
if (e.getKey() instanceof AstMethod) {
Position pos = ((AstMethod) e.getKey()).getSourcePosition();
if (pos != null) summary_map.put(pos, e.getValue());
}
}
return addCorrelations(entity, summary_map, policy);
}
@Override
public List<ExtractionRegion> extract(CAstNode node) {
return region_map.get(node);
}
}
| 12,867
| 41.609272
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/CorrelatedPairExtractorFactory.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationFinder;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationSummary;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NoKey;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import java.net.URL;
import java.util.Map;
public class CorrelatedPairExtractorFactory implements CAstRewriterFactory<NodePos, NoKey> {
private final Map<IMethod, CorrelationSummary> summaries;
public CorrelatedPairExtractorFactory(
JavaScriptTranslatorFactory translatorFactory, URL entryPoint)
throws ClassHierarchyException {
this(new CorrelationFinder(translatorFactory).findCorrelatedAccesses(entryPoint));
}
public CorrelatedPairExtractorFactory(
JavaScriptTranslatorFactory translatorFactory, SourceModule[] scripts)
throws ClassHierarchyException {
this(new CorrelationFinder(translatorFactory).findCorrelatedAccesses(scripts));
}
public CorrelatedPairExtractorFactory(Map<IMethod, CorrelationSummary> summaries) {
this.summaries = summaries;
}
@Override
public ClosureExtractor createCAstRewriter(CAst ast) {
ExtractionPolicyFactory policyFactory =
new ExtractionPolicyFactory() {
@Override
public ExtractionPolicy createPolicy(CAstEntity entity) {
CorrelatedPairExtractionPolicy policy =
CorrelatedPairExtractionPolicy.make(entity, summaries);
assert policy != null;
return policy;
}
};
return new ClosureExtractor(ast, policyFactory);
}
}
| 2,312
| 36.918033
| 92
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ExtractedFunction.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstAnnotation;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstNodeTypeMap;
import com.ibm.wala.cast.tree.CAstQualifier;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.CAstType;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter.Rewrite;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* A simple implementation of {@link CAstEntity} used by the {@link ClosureExtractor}.
*
* @author mschaefer
*/
class ExtractedFunction implements CAstEntity {
private final String name;
private String[] parms;
private final ExtractionPos pos;
private Rewrite r;
private CAstNode root;
private CAstControlFlowMap cfg;
private CAstSourcePositionMap posmap;
private CAstNodeTypeMap types;
private Map<CAstNode, Collection<CAstEntity>> scopedEntities;
public ExtractedFunction(String name, ExtractionPos pos) {
this.name = name;
this.pos = pos;
}
public void setRewrite(Rewrite r) {
assert this.r == null : "Rewrite shouldn't be set more than once.";
this.r = r;
this.root = r.newRoot();
this.cfg = r.newCfg();
this.posmap = r.newPos();
this.types = r.newTypes();
}
@Override
public int getKind() {
return CAstEntity.FUNCTION_ENTITY;
}
@Override
public String getName() {
return name;
}
@Override
public String getSignature() {
return null;
}
@Override
public String[] getArgumentNames() {
computeParms();
return parms;
}
@Override
public CAstNode[] getArgumentDefaults() {
return new CAstNode[0];
}
@Override
public int getArgumentCount() {
computeParms();
return parms.length;
}
private void computeParms() {
if (this.parms == null) {
ArrayList<String> parms = new ArrayList<>();
parms.add(name);
parms.add("this");
parms.addAll(pos.getParameters());
if (pos.containsThis()) parms.add(pos.getThisParmName());
this.parms = parms.toArray(new String[0]);
}
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
if (scopedEntities == null) {
scopedEntities = HashMapFactory.make();
// first, add all existing entities inside the body of this for loop
for (Entry<CAstNode, Collection<CAstEntity>> e : r.newChildren().entrySet()) {
if (NodePos.inSubtree(e.getKey(), root)) {
Collection<CAstEntity> c = scopedEntities.get(e.getKey());
if (c == null) scopedEntities.put(e.getKey(), c = HashSetFactory.make());
c.addAll(e.getValue());
}
}
// now, add all new entities which arise from extracted nested for-in loops
for (ExtractionPos nested_loop : Iterator2Iterable.make(pos.getNestedLoops())) {
CAstNode callsite = nested_loop.getCallSite();
CAstEntity scoped_entity = nested_loop.getExtractedEntity();
Collection<CAstEntity> c = scopedEntities.get(callsite);
if (c == null) scopedEntities.put(callsite, c = HashSetFactory.make());
c.add(scoped_entity);
}
}
return scopedEntities;
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
if (getAllScopedEntities().containsKey(construct)) {
return getAllScopedEntities().get(construct).iterator();
} else {
return EmptyIterator.instance();
}
}
@Override
public CAstNode getAST() {
return root;
}
@Override
public CAstControlFlowMap getControlFlow() {
return cfg;
}
@Override
public CAstSourcePositionMap getSourceMap() {
return posmap;
}
@Override
public Position getPosition() {
return getSourceMap().getPosition(root);
}
@Override
public CAstNodeTypeMap getNodeTypeMap() {
return types;
}
@Override
public Collection<CAstQualifier> getQualifiers() {
return null;
}
@Override
public CAstType getType() {
return null;
}
@Override
public Collection<CAstAnnotation> getAnnotations() {
return null;
}
@Override
public String toString() {
return "<JS function " + name + '>';
}
@Override
public Position getPosition(int arg) {
return null;
}
@Override
public Position getNamePosition() {
return null;
}
}
| 5,154
| 25.435897
| 86
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ExtractionPolicy.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstNode;
import java.util.List;
/**
* An extraction policy tells a {@link ClosureExtractor} which bits of code to extract into
* closures.
*
* @author mschaefer
*/
public abstract class ExtractionPolicy {
public abstract List<ExtractionRegion> extract(CAstNode node);
}
| 747
| 27.769231
| 91
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ExtractionPolicyFactory.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstEntity;
public abstract class ExtractionPolicyFactory {
public abstract ExtractionPolicy createPolicy(CAstEntity entity);
}
| 599
| 30.578947
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ExtractionPos.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* A special {@link ChildPos} representing the position of a node which is the body of a for-in
* loop.
*
* <p>This also stores some additional data obtained while rewriting the loop body, such as whether
* {@code return} statements were encountered.
*
* @author mschaefer
*/
public class ExtractionPos extends NodePos {
private final CAstNode parent;
private final ExtractionRegion region;
private final NodePos parent_pos;
private boolean contains_return;
private boolean contains_this;
private final Set<Pair<String, CAstNode>> goto_targets = HashSetFactory.make();
private boolean contains_outer_goto;
private final Set<ExtractionPos> nested_loops = HashSetFactory.make();
private CAstEntity extracted_entity;
private CAstNode callsite;
public ExtractionPos(CAstNode parent, ExtractionRegion region, NodePos parent_pos) {
this.parent = parent;
this.region = region;
this.parent_pos = parent_pos;
}
public CAstNode getParent() {
return parent;
}
public int getStart() {
return region.getStart();
}
public int getEnd() {
return region.getEnd();
}
public ExtractionRegion getRegion() {
return region;
}
public boolean contains(CAstNode node) {
for (int i = getStart(); i < getEnd(); ++i)
if (NodePos.inSubtree(node, parent.getChild(i))) return true;
return false;
}
public List<String> getParameters() {
return region.getParameters();
}
public void addGotoTarget(String label, CAstNode node) {
// check whether this target lies beyond an enclosing for-in loop
ExtractionPos outer = getEnclosingExtractionPos(parent_pos);
if (outer != null && !outer.contains(node)) {
// the goto needs to be handled by the outer loop
outer.addGotoTarget(label, node);
// but we need to remember to pass it on
contains_outer_goto = true;
} else {
// this goto is our responsibility
goto_targets.add(Pair.make(label, node));
}
}
public boolean containsReturn() {
return contains_return;
}
public void addReturn() {
this.contains_return = true;
}
public Set<Pair<String, CAstNode>> getGotoTargets() {
return Collections.unmodifiableSet(goto_targets);
}
public void addThis() {
contains_this = true;
}
public boolean containsThis() {
return contains_this;
}
public boolean containsGoto() {
return !getGotoTargets().isEmpty();
}
public boolean containsOuterGoto() {
return contains_outer_goto;
}
public boolean containsJump() {
return containsGoto() || containsReturn() || containsOuterGoto();
}
public String getThisParmName() {
return "thi$";
}
public void addNestedPos(ExtractionPos loop) {
nested_loops.add(loop);
}
public Iterator<ExtractionPos> getNestedLoops() {
return nested_loops.iterator();
}
public void setExtractedEntity(CAstEntity entity) {
assert this.extracted_entity == null : "Cannot reset extracted entity.";
extracted_entity = entity;
}
public CAstEntity getExtractedEntity() {
assert extracted_entity != null : "Extracted entity not set.";
return extracted_entity;
}
public void setCallSite(CAstNode callsite) {
assert this.callsite == null : "Cannot reset call site.";
this.callsite = callsite;
}
public CAstNode getCallSite() {
assert callsite != null : "Call site not set.";
return callsite;
}
@Override
public <A> A accept(PosSwitch<A> ps) {
return ps.caseForInLoopBodyPos(this);
}
// return the outermost enclosing extraction position around 'pos' within the same function;
// "null" if there is none
public static ExtractionPos getOutermostEnclosingExtractionPos(NodePos pos) {
return pos.accept(
new PosSwitch<>() {
@Override
public ExtractionPos caseRootPos(RootPos pos) {
return null;
}
@Override
public ExtractionPos caseChildPos(ChildPos pos) {
int kind = pos.getParent().getKind();
if (kind == CAstNode.FUNCTION_STMT || kind == CAstNode.FUNCTION_EXPR) return null;
return getOutermostEnclosingExtractionPos(pos.getParentPos());
}
@Override
public ExtractionPos caseForInLoopBodyPos(ExtractionPos pos) {
ExtractionPos outer = getEnclosingExtractionPos(pos.getParentPos());
return outer == null ? pos : outer;
}
@Override
public ExtractionPos caseLabelPos(LabelPos pos) {
return getOutermostEnclosingExtractionPos(pos.getParentPos());
}
});
}
// return the innermost enclosing extraction position around 'pos' within the same function;
// "null" if there is none
public static ExtractionPos getEnclosingExtractionPos(NodePos pos) {
return pos.accept(
new PosSwitch<>() {
@Override
public ExtractionPos caseRootPos(RootPos pos) {
return null;
}
@Override
public ExtractionPos caseChildPos(ChildPos pos) {
int kind = pos.getParent().getKind();
if (kind == CAstNode.FUNCTION_STMT || kind == CAstNode.FUNCTION_EXPR) return null;
return getEnclosingExtractionPos(pos.getParentPos());
}
@Override
public ExtractionPos caseForInLoopBodyPos(ExtractionPos pos) {
return pos;
}
@Override
public ExtractionPos caseLabelPos(LabelPos pos) {
return getEnclosingExtractionPos(pos.getParentPos());
}
});
}
// is this the outermost for-in loop within its enclosing function?
public boolean isOutermost() {
return getEnclosingExtractionPos(parent_pos) == null;
}
public NodePos getParentPos() {
return parent_pos;
}
}
| 6,545
| 27.837004
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ExtractionRegion.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import java.util.List;
/**
* A region for the {@link ClosureExtractor} to extract.
*
* @author mschaefer
*/
public class ExtractionRegion {
private int start, end;
// parameters for the extracted method
private final List<String> parameters;
// variables that should be made local to the extracted method if possible
private final List<String> locals;
public ExtractionRegion(int start, int end, List<String> parameters, List<String> locals) {
super();
this.start = start;
this.end = end;
this.parameters = parameters;
this.locals = locals;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public List<String> getParameters() {
return parameters;
}
public void setStart(int start) {
this.start = start;
}
public void setEnd(int end) {
this.end = end;
}
public List<String> getLocals() {
return locals;
}
}
| 1,369
| 21.096774
| 93
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/ForInBodyExtractionPolicy.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import static com.ibm.wala.cast.tree.CAstNode.ASSIGN;
import static com.ibm.wala.cast.tree.CAstNode.BLOCK_STMT;
import static com.ibm.wala.cast.tree.CAstNode.DECL_STMT;
import static com.ibm.wala.cast.tree.CAstNode.EACH_ELEMENT_GET;
import static com.ibm.wala.cast.tree.CAstNode.EMPTY;
import static com.ibm.wala.cast.tree.CAstNode.LABEL_STMT;
import static com.ibm.wala.cast.tree.CAstNode.LOCAL_SCOPE;
import static com.ibm.wala.cast.tree.CAstNode.VAR;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.pattern.Alt;
import com.ibm.wala.cast.tree.pattern.AnyNode;
import com.ibm.wala.cast.tree.pattern.NodeOfKind;
import com.ibm.wala.cast.tree.pattern.SomeConstant;
import com.ibm.wala.cast.tree.pattern.SubtreeOfKind;
import java.util.Collections;
import java.util.List;
/**
* A policy telling a {@link ClosureExtractor} to extract the body of every for-in loop.
*
* <p>NB: This policy matches on Rhino-specific encodings of for-in loops and hence is inherently
* non-portable.
*
* @author mschaefer
*/
public class ForInBodyExtractionPolicy extends ExtractionPolicy {
public static final ForInBodyExtractionPolicy INSTANCE = new ForInBodyExtractionPolicy();
public static final ExtractionPolicyFactory FACTORY =
new ExtractionPolicyFactory() {
@Override
public ExtractionPolicy createPolicy(CAstEntity entity) {
return INSTANCE;
}
};
private ForInBodyExtractionPolicy() {}
@Override
public List<ExtractionRegion> extract(CAstNode node) {
SomeConstant loopVar = new SomeConstant();
/*
* matches Rhino 1.7.3 encoding of for-in loop bodies:
*
* BLOCK_STMT
* decl/assign of loop variable
* optional SCOPE
* <loopBody>
*/
if (new NodeOfKind(
BLOCK_STMT,
new Alt(
new NodeOfKind(DECL_STMT, loopVar, new SubtreeOfKind(EACH_ELEMENT_GET)),
new NodeOfKind(
ASSIGN, new NodeOfKind(VAR, loopVar), new SubtreeOfKind(EACH_ELEMENT_GET))),
new AnyNode(),
new NodeOfKind(BLOCK_STMT, new SubtreeOfKind(LABEL_STMT), new SubtreeOfKind(EMPTY)))
.matches(node)) {
List<String> parms = Collections.singletonList((String) loopVar.getLastMatch());
if (node.getChild(1).getKind() == LOCAL_SCOPE) {
return Collections.<ExtractionRegion>singletonList(
new TwoLevelExtractionRegion(1, 2, 0, -1, parms, Collections.<String>emptyList()));
} else {
return Collections.singletonList(
new ExtractionRegion(1, 2, parms, Collections.<String>emptyList()));
}
}
/* matches Rhino < 1.7.3 encoding of for-in loop bodies:
*
* BLOCK_STMT
* ASSIGN
* VAR <loopVar>
* EACH_ELEMENT_GET
* VAR <forin_tmp>
* <loopBody>
*/
if (new NodeOfKind(
BLOCK_STMT,
new NodeOfKind(
ASSIGN, new NodeOfKind(VAR, loopVar), new SubtreeOfKind(EACH_ELEMENT_GET)),
new AnyNode())
.matches(node)) {
List<String> parms = Collections.singletonList((String) loopVar.getLastMatch());
return Collections.singletonList(
new ExtractionRegion(1, 2, parms, Collections.<String>emptyList()));
}
return null;
}
}
| 3,815
| 34.663551
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/LabelPos.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstNode;
/**
* A {@link NodePos} for a node that labels a CFG edge; currently only seems to occur with 'switch'
* statements.
*
* @author mschaefer
*/
public class LabelPos extends NodePos {
private final CAstNode parent;
private final NodePos parent_pos;
public LabelPos(CAstNode node, NodePos parent_pos) {
this.parent = node;
this.parent_pos = parent_pos;
}
public CAstNode getParent() {
return parent;
}
public NodePos getParentPos() {
return parent_pos;
}
@Override
public <A> A accept(PosSwitch<A> ps) {
return ps.caseLabelPos(this);
}
}
| 1,064
| 23.767442
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/NodeLabeller.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstNode;
import java.util.ArrayList;
/**
* A node labeller keeps a mapping from nodes to integers to allow consistent labelling of nodes.
*
* @author mschaefer
*/
public class NodeLabeller {
private final ArrayList<CAstNode> nodes = new ArrayList<>();
/**
* Adds a node to the mapping if it is not present yet.
*
* @param node the node to add
* @return the node's label
*/
public int addNode(CAstNode node) {
int label = getLabel(node);
if (label == -1) {
label = nodes.size();
nodes.add(node);
}
return label;
}
/**
* Determines the label of a node in the mapping.
*
* @param node the node whose label is to be determined
* @return if the node is mapped, returns its label; otherwise, returns -1
*/
public int getLabel(CAstNode node) {
return nodes.indexOf(node);
}
/** Determines the node associated with a given label. */
public CAstNode getNode(int label) {
return nodes.get(label);
}
}
| 1,454
| 25.454545
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/NodePos.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NoKey;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter;
/**
* Representation of a node's position in a CAst entity's syntax tree. The position is stored as a
* zipper data structure.
*
* @author mschaefer
*/
public abstract class NodePos implements CAstRewriter.RewriteContext<CAstBasicRewriter.NoKey> {
public abstract <A> A accept(PosSwitch<A> ps);
@Override
public NoKey key() {
return null;
}
/**
* Determines whether a node is inside the subtree rooted at some other node.
*
* @param node the node
* @param tree the subtree
* @return {@literal true} if {@code node} is a descendant of {@code tree}, {@literal false}
* otherwise
*/
public static boolean inSubtree(CAstNode node, CAstNode tree) {
if (node == tree) return true;
if (tree == null) return false;
for (CAstNode child : tree.getChildren()) if (inSubtree(node, child)) return true;
return false;
}
}
| 1,525
| 30.791667
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/PosSwitch.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
public abstract class PosSwitch<A> {
public abstract A caseRootPos(RootPos pos);
public abstract A caseChildPos(ChildPos pos);
public abstract A caseForInLoopBodyPos(ExtractionPos pos);
public abstract A caseLabelPos(LabelPos pos);
}
| 683
| 28.73913
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/RootPos.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
public final class RootPos extends NodePos {
@Override
public <A> A accept(PosSwitch<A> ps) {
return ps.caseRootPos(this);
}
@Override
public int hashCode() {
return 3741;
}
@Override
public boolean equals(Object obj) {
return obj instanceof RootPos;
}
}
| 725
| 23.2
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/correlations/extraction/TwoLevelExtractionRegion.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction;
import java.util.List;
public class TwoLevelExtractionRegion extends ExtractionRegion {
private final int start_inner, end_inner;
public TwoLevelExtractionRegion(
int start,
int end,
int start_inner,
int end_inner,
List<String> parameters,
List<String> locals) {
super(start, end, parameters, locals);
this.start_inner = start_inner;
this.end_inner = end_inner;
}
public int getStartInner() {
return this.start_inner;
}
public int getEndInner() {
return this.end_inner;
}
}
| 986
| 24.307692
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/modref/JavaScriptModRef.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.modref;
import com.ibm.wala.cast.ipa.callgraph.AstHeapModel;
import com.ibm.wala.cast.ipa.modref.AstModRef;
import com.ibm.wala.cast.js.ssa.JSInstructionVisitor;
import com.ibm.wala.cast.js.ssa.JavaScriptCheckReference;
import com.ibm.wala.cast.js.ssa.JavaScriptInstanceOf;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.ssa.JavaScriptTypeOfInstruction;
import com.ibm.wala.cast.js.ssa.JavaScriptWithRegion;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.cast.js.ssa.SetPrototype;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.modref.ExtendedHeapModel;
import java.util.Collection;
public class JavaScriptModRef<T extends InstanceKey> extends AstModRef<T> {
public static class JavaScriptRefVisitor<T extends InstanceKey> extends AstRefVisitor<T>
implements JSInstructionVisitor {
public JavaScriptRefVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) {
super(n, result, pa, (AstHeapModel) h);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke instruction) {
// do nothing
}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction instruction) {
// do nothing
}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf instruction) {
// do nothing
}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {
// do nothing
}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {
// do nothing
}
@Override
public void visitSetPrototype(SetPrototype instruction) {
// do nothing
}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {
// TODO Auto-generated method stub
}
}
@Override
protected RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) {
return new JavaScriptRefVisitor<>(n, result, pa, h);
}
public static class JavaScriptModVisitor<T extends InstanceKey> extends AstModVisitor<T>
implements JSInstructionVisitor {
public JavaScriptModVisitor(
CGNode n, Collection<PointerKey> result, ExtendedHeapModel h, PointerAnalysis<T> pa) {
super(n, result, (AstHeapModel) h, pa);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke instruction) {
// do nothing
}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction instruction) {
// do nothing
}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf instruction) {
// do nothing
}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {
// do nothing
}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {
// do nothing
}
@Override
public void visitSetPrototype(SetPrototype instruction) {
// TODO Auto-generated method stub
}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {
// do nothing
}
}
@Override
protected ModVisitor<T, ? extends ExtendedHeapModel> makeModVisitor(
CGNode n,
Collection<PointerKey> result,
PointerAnalysis<T> pa,
ExtendedHeapModel h,
boolean ignoreAllocHeapDefs) {
return new JavaScriptModVisitor<>(n, result, h, pa);
}
}
| 4,079
| 28.352518
| 94
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/summaries/JavaScriptConstructorFunctions.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.summaries;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction.Operator;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.collections.Pair;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class JavaScriptConstructorFunctions {
private final Map<Object, IMethod> constructors = HashMapFactory.make();
private final IClassHierarchy cha;
public JavaScriptConstructorFunctions(IClassHierarchy cha) {
this.cha = cha;
}
public static class JavaScriptConstructor extends JavaScriptSummarizedFunction {
private final String toStringExtra;
private final IClass constructorForType;
private JavaScriptConstructor(
MethodReference ref,
MethodSummary summary,
IClass declaringClass,
IClass constructorForType,
String toStringExtra) {
super(ref, summary, declaringClass);
this.toStringExtra = toStringExtra;
this.constructorForType = constructorForType;
}
private JavaScriptConstructor(
MethodReference ref,
MethodSummary summary,
IClass declaringClass,
IClass constructorForType) {
this(ref, summary, declaringClass, constructorForType, "");
}
@Override
public String toString() {
return "<ctor for " + getReference().getDeclaringClass() + toStringExtra + '>';
}
public IClass constructedType() {
return constructorForType;
}
}
private IMethod record(Object key, IMethod m) {
constructors.put(key, m);
return m;
}
private static IMethod makeNullaryValueConstructor(IClass cls, Object value) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = JavaScriptMethods.makeCtorReference(cls.getReference());
JavaScriptSummary S = new JavaScriptSummary(ref, 1);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 1, "prototype"));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
5,
NewSiteReference.make(S.getNumberOfStatements(), cls.getReference())));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), 5, 4));
// S.addStatement(insts.PutInstruction(5, 4, "__proto__"));
S.getNumberOfStatements();
S.addConstant(8, new ConstantValue(value));
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 5, 8, "$value"));
if (value instanceof String) {
S.addConstant(9, new ConstantValue(0));
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 5, 9, "length"));
}
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
S.getNumberOfStatements();
// S.addConstant(9, new ConstantValue("__proto__"));
return new JavaScriptConstructor(ref, S, cls, cls);
}
private static IMethod makeUnaryValueConstructor(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = JavaScriptMethods.makeCtorReference(cls.getReference());
JavaScriptSummary S = new JavaScriptSummary(ref, 2);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 5, 1, "prototype"));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
6,
NewSiteReference.make(S.getNumberOfStatements(), cls.getReference())));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), 6, 5));
// S.addStatement(insts.PutInstruction(6, 5, "__proto__"));
S.getNumberOfStatements();
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 6, 2, "$value"));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 6, false));
S.getNumberOfStatements();
// S.addConstant(7, new ConstantValue("__proto__"));
return new JavaScriptConstructor(ref, S, cls, cls);
}
private IMethod makeValueConstructor(IClass cls, int nargs, Object value) {
if (nargs == 0 || nargs == 1) {
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
else
return record(
key,
(nargs == 0)
? makeNullaryValueConstructor(cls, value)
: makeUnaryValueConstructor(cls));
} else {
// not a legal call, likely due to dataflow imprecision
return null;
}
}
/** create a method for constructing an Object with no arguments passed */
private IMethod makeNullaryObjectConstructor(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = JavaScriptMethods.makeCtorReference(JavaScriptTypes.Object);
JavaScriptSummary S = new JavaScriptSummary(ref, 1);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 1, "prototype"));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
5,
NewSiteReference.make(S.getNumberOfStatements(), JavaScriptTypes.Object)));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), 5, 4));
// S.addStatement(insts.PutInstruction(5, 4, "__proto__"));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
S.getNumberOfStatements();
// S.addConstant(6, new ConstantValue("__proto__"));
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.Object));
}
private IMethod makeUnaryObjectConstructor(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = JavaScriptMethods.makeCtorReference(JavaScriptTypes.Object);
JavaScriptSummary S = new JavaScriptSummary(ref, 2);
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 2, false));
S.getNumberOfStatements();
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.Object));
}
private IMethod makeObjectConstructor(IClass cls, int nargs) {
if (nargs == 0 || nargs == 1) {
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
else
return record(
key,
(nargs == 0) ? makeNullaryObjectConstructor(cls) : makeUnaryObjectConstructor(cls));
} else {
// not a legal call, likely the result of analysis imprecision
return null;
}
}
private IMethod makeObjectCall(IClass cls, int nargs) {
assert nargs == 0;
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
else return record(key, makeNullaryObjectConstructor(cls));
}
private IMethod makeArrayLengthConstructor(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = JavaScriptMethods.makeCtorReference(JavaScriptTypes.Array);
JavaScriptSummary S = new JavaScriptSummary(ref, 2);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 5, 1, "prototype"));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
6,
NewSiteReference.make(S.getNumberOfStatements(), JavaScriptTypes.Array)));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), 6, 5));
// S.addStatement(insts.PutInstruction(6, 5, "__proto__"));
S.getNumberOfStatements();
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 6, 2, "length"));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 6, false));
S.getNumberOfStatements();
// S.addConstant(7, new ConstantValue("__proto__"));
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.Array));
}
private IMethod makeArrayContentsConstructor(IClass cls, int nargs) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = JavaScriptMethods.makeCtorReference(JavaScriptTypes.Array);
JavaScriptSummary S = new JavaScriptSummary(ref, nargs + 1);
S.addConstant(nargs + 3, new ConstantValue("prototype"));
S.addStatement(insts.PropertyRead(S.getNumberOfStatements(), nargs + 4, 1, nargs + 3));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
nargs + 5,
NewSiteReference.make(S.getNumberOfStatements(), JavaScriptTypes.Array)));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), nargs + 5, nargs + 4));
// S.addStatement(insts.PutInstruction(nargs + 5, nargs + 4, "__proto__"));
S.getNumberOfStatements();
S.addConstant(nargs + 7, new ConstantValue(nargs));
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), nargs + 5, nargs + 7, "length"));
S.getNumberOfStatements();
int vn = nargs + 9;
for (int i = 0; i < nargs; i++, vn += 2) {
S.addConstant(vn, new ConstantValue(i));
S.addStatement(insts.PropertyWrite(S.getNumberOfStatements(), nargs + 5, vn, i + 1));
S.getNumberOfStatements();
}
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
S.getNumberOfStatements();
// S.addConstant(vn, new ConstantValue("__proto__"));
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.Array));
}
private IMethod makeArrayConstructor(IClass cls, int nargs) {
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
else
return record(
key,
(nargs == 1)
? makeArrayLengthConstructor(cls)
: makeArrayContentsConstructor(cls, nargs));
}
private IMethod makeNullaryStringCall(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = AstMethodReference.fnReference(JavaScriptTypes.String);
JavaScriptSummary S = new JavaScriptSummary(ref, 1);
S.addConstant(2, new ConstantValue(""));
S.addConstant(3, new ConstantValue(0));
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 2, 3, "length"));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 2, false));
S.getNumberOfStatements();
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.String));
}
private IMethod makeUnaryStringCall(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = AstMethodReference.fnReference(JavaScriptTypes.String);
JavaScriptSummary S = new JavaScriptSummary(ref, 2);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 2, "toString"));
S.getNumberOfStatements();
CallSiteReference cs =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNumberOfStatements());
S.addStatement(insts.Invoke(S.getNumberOfStatements(), 4, 5, new int[] {2}, 6, cs));
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
S.getNumberOfStatements();
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.String));
}
private IMethod makeStringCall(IClass cls, int nargs) {
assert nargs == 0 || nargs == 1;
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
else return record(key, (nargs == 0) ? makeNullaryStringCall(cls) : makeUnaryStringCall(cls));
}
private IMethod makeNullaryNumberCall(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = AstMethodReference.fnReference(JavaScriptTypes.Number);
JavaScriptSummary S = new JavaScriptSummary(ref, 1);
S.addConstant(2, new ConstantValue(0.0));
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 2, false));
S.getNumberOfStatements();
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.Number));
}
private IMethod makeUnaryNumberCall(IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
MethodReference ref = AstMethodReference.fnReference(JavaScriptTypes.Number);
JavaScriptSummary S = new JavaScriptSummary(ref, 2);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 2, "toNumber"));
S.getNumberOfStatements();
CallSiteReference cs =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNumberOfStatements());
S.addStatement(insts.Invoke(S.getNumberOfStatements(), 4, 5, new int[] {2}, 6, cs));
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
S.getNumberOfStatements();
return new JavaScriptConstructor(ref, S, cls, cha.lookupClass(JavaScriptTypes.Number));
}
private IMethod makeNumberCall(IClass cls, int nargs) {
assert nargs == 0 || nargs == 1;
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
else return record(key, (nargs == 0) ? makeNullaryNumberCall(cls) : makeUnaryNumberCall(cls));
}
private IMethod makeFunctionConstructor(IClass receiver, IClass cls) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
Pair<IClass, IClass> tableKey = Pair.make(receiver, cls);
if (constructors.containsKey(tableKey)) return constructors.get(tableKey);
MethodReference ref = JavaScriptMethods.makeCtorReference(receiver.getReference());
JavaScriptSummary S = new JavaScriptSummary(ref, 1);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 1, "prototype"));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
5,
NewSiteReference.make(S.getNumberOfStatements(), cls.getReference())));
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
7,
NewSiteReference.make(S.getNumberOfStatements(), JavaScriptTypes.Object)));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), 5, 4));
// S.addStatement(insts.PutInstruction(5, 4, "__proto__"));
S.getNumberOfStatements();
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 5, 7, "prototype"));
S.getNumberOfStatements();
S.addStatement(insts.PutInstruction(S.getNumberOfStatements(), 7, 5, "constructor"));
S.getNumberOfStatements();
// TODO we need to set v7.__proto__ to Object.prototype
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
S.getNumberOfStatements();
// S.addConstant(8, new ConstantValue("__proto__"));
if (receiver != cls)
return record(
tableKey,
new JavaScriptConstructor(
ref, S, receiver, cls, "(" + cls.getReference().getName() + ')'));
else return record(tableKey, new JavaScriptConstructor(ref, S, receiver, cls));
}
private int ctorCount = 0;
private IMethod makeFunctionConstructor(
IR callerIR, SSAAbstractInvokeInstruction callStmt, IClass cls, int nargs) {
SymbolTable ST = callerIR.getSymbolTable();
switch (nargs) {
case 0:
return makeFunctionConstructor(cls, cls);
case 1:
if (ST.isStringConstant(callStmt.getUse(1))
&& !ST.getStringValue(callStmt.getUse(1)).isEmpty()) {
TypeReference ref =
TypeReference.findOrCreate(
JavaScriptTypes.jsLoader,
TypeName.string2TypeName(ST.getStringValue(callStmt.getUse(1))));
IClass cls2 = cha.lookupClass(ref);
if (cls2 != null) {
return makeFunctionConstructor(cls, cls2);
}
}
return makeFunctionConstructor(cls, cls);
default:
assert nargs > 1;
JavaScriptLoader cl = (JavaScriptLoader) cha.getLoader(JavaScriptTypes.jsLoader);
for (int i = 1; i < callStmt.getNumberOfUses(); i++)
if (!ST.isStringConstant(callStmt.getUse(i))) return makeFunctionConstructor(cls, cls);
final StringBuilder fun = new StringBuilder("function _fromctor (");
for (int j = 1; j < callStmt.getNumberOfUses() - 1; j++) {
if (j != 1) fun.append(',');
fun.append(ST.getStringValue(callStmt.getUse(j)));
}
fun.append(") {");
fun.append(ST.getStringValue(callStmt.getUse(callStmt.getNumberOfUses() - 1)));
fun.append('}');
try {
final String fileName = "ctor$" + ++ctorCount;
ModuleEntry ME =
new SourceModule() {
@Override
public String getName() {
return fileName;
}
@Override
public boolean isClassFile() {
return false;
}
@Override
public boolean isSourceFile() {
return true;
}
@Override
public InputStream getInputStream() {
return new InputStream() {
private int i = 0;
@Override
public int read() throws IOException {
if (i >= fun.length()) {
return -1;
} else {
return fun.codePointAt(i++);
}
}
};
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() {
return null;
}
@Override
public String getClassName() {
return fileName;
}
@Override
public Module getContainer() {
return null;
}
@Override
public Iterator<? extends ModuleEntry> getEntries() {
return new NonNullSingletonIterator<ModuleEntry>(this);
}
@Override
public Reader getInputReader() {
return new StringReader(fun.toString());
}
@Override
public URL getURL() {
try {
return new URL("file://" + fileName);
} catch (MalformedURLException e) {
assert false;
return null;
}
}
};
Set<String> fnNames = JSCallGraphUtil.loadAdditionalFile(cha, cl, ME);
IClass fcls = null;
for (String nm : fnNames) {
if (nm.endsWith("_fromctor")) {
fcls = cl.lookupClass(nm, cha);
}
}
if (fcls == null) {
// This can happen, e.g., if the arguments to the Function constructor call are
// malformed.
// In this case, return a synthetic constructor similar to the 0-argument case
return makeFunctionConstructor(cls, cls);
} else {
return makeFunctionConstructor(cls, fcls);
}
} catch (IOException e) {
}
return makeFunctionConstructor(cls, cls);
}
}
private IMethod makeFunctionObjectConstructor(IClass cls, int nargs) {
JSInstructionFactory insts =
(JSInstructionFactory) cls.getClassLoader().getInstructionFactory();
Object key = Pair.make(cls, nargs);
if (constructors.containsKey(key)) return constructors.get(key);
MethodReference ref = JavaScriptMethods.makeCtorReference(cls.getReference());
JavaScriptSummary S = new JavaScriptSummary(ref, nargs + 1);
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), nargs + 4, 1, "prototype"));
S.getNumberOfStatements();
S.addStatement(
insts.NewInstruction(
S.getNumberOfStatements(),
nargs + 5,
NewSiteReference.make(S.getNumberOfStatements(), JavaScriptTypes.Object)));
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), nargs + 5, nargs + 4));
S.getNumberOfStatements();
CallSiteReference cs =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNumberOfStatements());
int[] args = new int[nargs + 1];
args[0] = nargs + 5;
for (int i = 0; i < nargs; i++) args[i + 1] = i + 2;
S.addStatement(insts.Invoke(S.getNumberOfStatements(), 1, nargs + 7, args, nargs + 8, cs));
int pc = S.getNumberOfStatements();
S.addConstant(nargs + 9, null);
S.addStatement(
insts.ConditionalBranchInstruction(
S.getNumberOfStatements(),
Operator.EQ,
JavaScriptTypes.Root,
nargs + 7,
nargs + 9,
pc + 2));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), nargs + 7, false));
S.getNumberOfStatements();
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), nargs + 5, false));
S.getNumberOfStatements();
return record(key, new JavaScriptConstructor(ref, S, cls, cls));
}
public IMethod findOrCreateConstructorMethod(
IR callerIR, SSAAbstractInvokeInstruction callStmt, IClass receiver, int nargs) {
if (receiver.getReference().equals(JavaScriptTypes.Object))
return makeObjectConstructor(receiver, nargs);
else if (receiver.getReference().equals(JavaScriptTypes.Array))
return makeArrayConstructor(receiver, nargs);
else if (receiver.getReference().equals(JavaScriptTypes.StringObject))
return makeValueConstructor(receiver, nargs, "");
else if (receiver.getReference().equals(JavaScriptTypes.BooleanObject)) {
assert nargs == 1;
return makeValueConstructor(receiver, nargs, null);
} else if (receiver.getReference().equals(JavaScriptTypes.NumberObject))
return makeValueConstructor(receiver, nargs, 0);
else if (receiver.getReference().equals(JavaScriptTypes.Function))
return makeFunctionConstructor(callerIR, callStmt, receiver, nargs);
else if (cha.isSubclassOf(receiver, cha.lookupClass(JavaScriptTypes.CodeBody)))
return makeFunctionObjectConstructor(receiver, nargs);
else {
return null;
}
}
public IMethod findOrCreateCallMethod(
IR callerIR, SSAAbstractInvokeInstruction callStmt, IClass receiver, int nargs) {
if (receiver.getReference().equals(JavaScriptTypes.Object))
return makeObjectCall(receiver, nargs);
else if (receiver.getReference().equals(JavaScriptTypes.Array))
return makeArrayConstructor(receiver, nargs);
else if (receiver.getReference().equals(JavaScriptTypes.StringObject))
return makeStringCall(receiver, nargs);
else if (receiver.getReference().equals(JavaScriptTypes.NumberObject))
return makeNumberCall(receiver, nargs);
else if (receiver.getReference().equals(JavaScriptTypes.Function))
return makeFunctionConstructor(callerIR, callStmt, receiver, nargs);
else {
return null;
}
}
}
| 25,587
| 36.19186
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/summaries/JavaScriptSummarizedFunction.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.summaries;
import com.ibm.wala.cast.js.cfg.JSInducedCFG;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.ipa.summaries.SummarizedMethod;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
public class JavaScriptSummarizedFunction extends SummarizedMethod {
public JavaScriptSummarizedFunction(
MethodReference ref, MethodSummary summary, IClass declaringClass) {
super(ref, summary, declaringClass);
}
@Override
public boolean equals(Object o) {
return this == o;
}
@Override
public InducedCFG makeControlFlowGraph(SSAInstruction[] instructions) {
return new JSInducedCFG(instructions, this, Everywhere.EVERYWHERE);
}
}
| 1,247
| 31
| 74
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/summaries/JavaScriptSummary.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ipa.summaries;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
public class JavaScriptSummary extends MethodSummary {
private final int declaredParameters;
public JavaScriptSummary(MethodReference ref, int declaredParameters) {
super(ref);
this.declaredParameters = declaredParameters;
addStatement(
JavaScriptLoader.JS
.instructionFactory()
.NewInstruction(
getNumberOfStatements(),
declaredParameters + 1,
NewSiteReference.make(getNumberOfStatements(), JavaScriptTypes.Array)));
}
@Override
public int getNumberOfParameters() {
return declaredParameters;
}
@Override
public TypeReference getParameterType(int i) {
return JavaScriptTypes.Root;
}
}
| 1,416
| 29.804348
| 88
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/loader/JavaScriptLoader.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.loader;
import com.ibm.wala.analysis.typeInference.PrimitiveType;
import com.ibm.wala.cast.ir.ssa.AssignInstruction;
import com.ibm.wala.cast.ir.ssa.AstAssertInstruction;
import com.ibm.wala.cast.ir.ssa.AstEchoInstruction;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction;
import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access;
import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cast.ir.ssa.AstLexicalWrite;
import com.ibm.wala.cast.ir.ssa.AstPropertyRead;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
import com.ibm.wala.cast.ir.ssa.AstYieldInstruction;
import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction;
import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction;
import com.ibm.wala.cast.ir.translator.AstTranslator.AstLexicalInformation;
import com.ibm.wala.cast.ir.translator.AstTranslator.WalkContext;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.ir.translator.TranslatorToIR;
import com.ibm.wala.cast.js.analysis.typeInference.JSPrimitiveType;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph.JSFakeRoot;
import com.ibm.wala.cast.js.ipa.modref.JavaScriptModRef;
import com.ibm.wala.cast.js.ipa.modref.JavaScriptModRef.JavaScriptRefVisitor;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.ssa.JavaScriptCheckReference;
import com.ibm.wala.cast.js.ssa.JavaScriptInstanceOf;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.ssa.JavaScriptPropertyRead;
import com.ibm.wala.cast.js.ssa.JavaScriptPropertyWrite;
import com.ibm.wala.cast.js.ssa.JavaScriptTypeOfInstruction;
import com.ibm.wala.cast.js.ssa.JavaScriptWithRegion;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.cast.js.ssa.SetPrototype;
import com.ibm.wala.cast.js.translator.JSAstTranslator;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation;
import com.ibm.wala.cast.loader.CAstAbstractModuleLoader;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstQualifier;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.cast.types.AstTypeReference;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.LanguageImpl;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.modref.ExtendedHeapModel;
import com.ibm.wala.ipa.modref.ModRef.ModVisitor;
import com.ibm.wala.ipa.modref.ModRef.RefVisitor;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.IOperator;
import com.ibm.wala.shrike.shrikeBT.IComparisonInstruction.Operator;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.SSAAbstractBinaryInstruction;
import com.ibm.wala.ssa.SSAAddressOfInstruction;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadIndirectInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAStoreIndirectInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JavaScriptLoader extends CAstAbstractModuleLoader {
public static final Language JS =
new LanguageImpl() {
{
JSPrimitiveType.init();
}
@Override
public Atom getName() {
return Atom.findOrCreateUnicodeAtom("JavaScript");
}
@Override
public TypeReference getRootType() {
return JavaScriptTypes.Root;
}
@Override
public TypeReference getThrowableType() {
return JavaScriptTypes.Root;
}
@Override
public TypeReference getConstantType(Object o) {
if (o == null) {
return JavaScriptTypes.Null;
} else {
Class<?> c = o.getClass();
if (c == Boolean.class) {
return JavaScriptTypes.Boolean;
} else if (c == String.class) {
return JavaScriptTypes.String;
} else if (c == Integer.class) {
return JavaScriptTypes.Number;
} else if (c == Float.class) {
return JavaScriptTypes.Number;
} else if (c == Double.class) {
return JavaScriptTypes.Number;
} else {
assert false : "cannot determine type for " + o + " of class " + c;
return null;
}
}
}
@Override
public boolean isNullType(TypeReference type) {
return type.equals(JavaScriptTypes.Undefined) || type.equals(JavaScriptTypes.Null);
}
@Override
public TypeReference[] getArrayInterfaces() {
return new TypeReference[0];
}
@Override
public TypeName lookupPrimitiveType(String name) {
if ("Boolean".equals(name)) {
return JavaScriptTypes.Boolean.getName();
} else if ("Number".equals(name)) {
return JavaScriptTypes.Number.getName();
} else if ("String".equals(name)) {
return JavaScriptTypes.String.getName();
} else if ("Date".equals(name)) {
return JavaScriptTypes.Date.getName();
} else {
assert "RegExp".equals(name);
return JavaScriptTypes.RegExp.getName();
}
}
@Override
public Collection<TypeReference> inferInvokeExceptions(
MethodReference target, IClassHierarchy cha) throws InvalidClassFileException {
return Collections.singleton(JavaScriptTypes.Root);
}
@Override
public Object getMetadataToken(Object value) {
assert false;
return null;
}
@Override
public TypeReference getPointerType(TypeReference pointee)
throws UnsupportedOperationException {
throw new UnsupportedOperationException("JavaScript does not permit explicit pointers");
}
@Override
public boolean methodsHaveDeclaredParameterTypes() {
return false;
}
@Override
public JSInstructionFactory instructionFactory() {
return new JSInstructionFactory() {
@Override
public JavaScriptCheckReference CheckReference(int iindex, int ref) {
return new JavaScriptCheckReference(iindex, ref);
}
@Override
public SSAGetInstruction GetInstruction(int iindex, int result, int ref, String field) {
return GetInstruction(
iindex,
result,
ref,
FieldReference.findOrCreate(
JavaScriptTypes.Root,
Atom.findOrCreateUnicodeAtom(field),
JavaScriptTypes.Root));
}
@Override
public JavaScriptInstanceOf InstanceOf(
int iindex, int result, int objVal, int typeVal) {
return new JavaScriptInstanceOf(iindex, result, objVal, typeVal);
}
@Override
public JavaScriptInvoke Invoke(
int iindex,
int function,
int[] results,
int[] params,
int exception,
CallSiteReference site) {
return new JavaScriptInvoke(iindex, function, results, params, exception, site);
}
@Override
public JavaScriptInvoke Invoke(
int iindex,
int function,
int result,
int[] params,
int exception,
CallSiteReference site) {
return new JavaScriptInvoke(iindex, function, result, params, exception, site);
}
@Override
public JavaScriptInvoke Invoke(
int iindex, int function, int[] params, int exception, CallSiteReference site) {
return new JavaScriptInvoke(iindex, function, params, exception, site);
}
@Override
public AstPropertyRead PropertyRead(
int iindex, int result, int objectRef, int memberRef) {
return new JavaScriptPropertyRead(iindex, result, objectRef, memberRef);
}
@Override
public AstPropertyWrite PropertyWrite(
int iindex, int objectRef, int memberRef, int value) {
return new JavaScriptPropertyWrite(iindex, objectRef, memberRef, value);
}
@Override
public SSAPutInstruction PutInstruction(int iindex, int ref, int value, String field) {
try {
byte[] utf8 = field.getBytes("UTF-8");
return PutInstruction(
iindex,
ref,
value,
FieldReference.findOrCreate(
JavaScriptTypes.Root,
Atom.findOrCreate(utf8, 0, utf8.length),
JavaScriptTypes.Root));
} catch (UnsupportedEncodingException e) {
Assertions.UNREACHABLE();
return null;
}
}
@Override
public JavaScriptTypeOfInstruction TypeOfInstruction(int iindex, int lval, int object) {
return new JavaScriptTypeOfInstruction(iindex, lval, object);
}
@Override
public JavaScriptWithRegion WithRegion(int iindex, int expr, boolean isEnter) {
return new JavaScriptWithRegion(iindex, expr, isEnter);
}
@Override
public AstAssertInstruction AssertInstruction(
int iindex, int value, boolean fromSpecification) {
return new AstAssertInstruction(iindex, value, fromSpecification);
}
@Override
public com.ibm.wala.cast.ir.ssa.AssignInstruction AssignInstruction(
int iindex, int result, int val) {
return new AssignInstruction(iindex, result, val);
}
@Override
public com.ibm.wala.cast.ir.ssa.EachElementGetInstruction EachElementGetInstruction(
int iindex, int value, int objectRef, int prevProp) {
return new EachElementGetInstruction(iindex, value, objectRef, prevProp);
}
@Override
public com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction
EachElementHasNextInstruction(int iindex, int value, int objectRef, int prop) {
return new EachElementHasNextInstruction(iindex, value, objectRef, prop);
}
@Override
public AstEchoInstruction EchoInstruction(int iindex, int[] rvals) {
return new AstEchoInstruction(iindex, rvals);
}
@Override
public AstYieldInstruction YieldInstruction(int iindex, int[] rvals) {
return new AstYieldInstruction(iindex, rvals);
}
@Override
public AstGlobalRead GlobalRead(int iindex, int lhs, FieldReference global) {
return new AstGlobalRead(iindex, lhs, global);
}
@Override
public AstGlobalWrite GlobalWrite(int iindex, FieldReference global, int rhs) {
return new AstGlobalWrite(iindex, global, rhs);
}
@Override
public AstIsDefinedInstruction IsDefinedInstruction(
int iindex, int lval, int rval, int fieldVal, FieldReference fieldRef) {
return new AstIsDefinedInstruction(iindex, lval, rval, fieldVal, fieldRef);
}
@Override
public AstIsDefinedInstruction IsDefinedInstruction(
int iindex, int lval, int rval, FieldReference fieldRef) {
return new AstIsDefinedInstruction(iindex, lval, rval, fieldRef);
}
@Override
public AstIsDefinedInstruction IsDefinedInstruction(
int iindex, int lval, int rval, int fieldVal) {
return new AstIsDefinedInstruction(iindex, lval, rval, fieldVal);
}
@Override
public AstIsDefinedInstruction IsDefinedInstruction(int iindex, int lval, int rval) {
return new AstIsDefinedInstruction(iindex, lval, rval);
}
@Override
public AstLexicalRead LexicalRead(int iindex, Access[] accesses) {
return new AstLexicalRead(iindex, accesses);
}
@Override
public AstLexicalRead LexicalRead(int iindex, Access access) {
return new AstLexicalRead(iindex, access);
}
@Override
public AstLexicalRead LexicalRead(
int iindex, int lhs, String definer, String globalName, TypeReference type) {
return new AstLexicalRead(iindex, lhs, definer, globalName, type);
}
@Override
public AstLexicalWrite LexicalWrite(int iindex, Access[] accesses) {
return new AstLexicalWrite(iindex, accesses);
}
@Override
public AstLexicalWrite LexicalWrite(int iindex, Access access) {
return new AstLexicalWrite(iindex, access);
}
@Override
public AstLexicalWrite LexicalWrite(
int iindex, String definer, String globalName, TypeReference type, int rhs) {
return new AstLexicalWrite(iindex, definer, globalName, type, rhs);
}
@Override
public SSAArrayLengthInstruction ArrayLengthInstruction(
int iindex, int result, int arrayref) {
throw new UnsupportedOperationException();
}
@Override
public SSAArrayLoadInstruction ArrayLoadInstruction(
int iindex, int result, int arrayref, int index, TypeReference declaredType) {
throw new UnsupportedOperationException();
}
@Override
public SSAArrayStoreInstruction ArrayStoreInstruction(
int iindex, int arrayref, int index, int value, TypeReference declaredType) {
throw new UnsupportedOperationException();
}
@Override
public SSAAbstractBinaryInstruction BinaryOpInstruction(
int iindex,
IOperator operator,
boolean overflow,
boolean unsigned,
int result,
int val1,
int val2,
boolean mayBeInteger) {
return new SSABinaryOpInstruction(
iindex, operator, result, val1, val2, mayBeInteger) {
@Override
public boolean isPEI() {
return false;
}
@Override
public SSAInstruction copyForSSA(
SSAInstructionFactory insts, int[] defs, int[] uses) {
return insts.BinaryOpInstruction(
iIndex(),
getOperator(),
false,
false,
defs == null || defs.length == 0 ? getDef(0) : defs[0],
uses == null ? getUse(0) : uses[0],
uses == null ? getUse(1) : uses[1],
mayBeIntegerOp());
}
};
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, TypeReference[] types, boolean isPEI) {
throw new UnsupportedOperationException();
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, int[] typeValues, boolean isPEI) {
throw new UnsupportedOperationException();
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, int typeValue, boolean isPEI) {
assert isPEI;
return CheckCastInstruction(iindex, result, val, new int[] {typeValue}, true);
}
@Override
public SSACheckCastInstruction CheckCastInstruction(
int iindex, int result, int val, TypeReference type, boolean isPEI) {
assert isPEI;
return CheckCastInstruction(iindex, result, val, new TypeReference[] {type}, true);
}
@Override
public SSAComparisonInstruction ComparisonInstruction(
int iindex, Operator operator, int result, int val1, int val2) {
return new SSAComparisonInstruction(iindex, operator, result, val1, val2);
}
@Override
public SSAConditionalBranchInstruction ConditionalBranchInstruction(
int iindex,
com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction.IOperator operator,
TypeReference type,
int val1,
int val2,
int target) {
return new SSAConditionalBranchInstruction(
iindex, operator, type, val1, val2, target);
}
@Override
public SSAConversionInstruction ConversionInstruction(
int iindex,
int result,
int val,
TypeReference fromType,
TypeReference toType,
boolean overflow) {
assert !overflow;
return new SSAConversionInstruction(iindex, result, val, fromType, toType) {
@Override
public SSAInstruction copyForSSA(
SSAInstructionFactory insts, int[] defs, int[] uses)
throws IllegalArgumentException {
if (uses != null && uses.length == 0) {
throw new IllegalArgumentException("(uses != null) and (uses.length == 0)");
}
return insts.ConversionInstruction(
iIndex(),
defs == null || defs.length == 0 ? getDef(0) : defs[0],
uses == null ? getUse(0) : uses[0],
getFromType(),
getToType(),
false);
}
};
}
@Override
public SSAGetCaughtExceptionInstruction GetCaughtExceptionInstruction(
int iindex, int bbNumber, int exceptionValueNumber) {
return new SSAGetCaughtExceptionInstruction(iindex, bbNumber, exceptionValueNumber);
}
@Override
public SSAGetInstruction GetInstruction(int iindex, int result, FieldReference field) {
throw new UnsupportedOperationException();
}
@Override
public SSAGetInstruction GetInstruction(
int iindex, int result, int ref, FieldReference field) {
return new SSAGetInstruction(iindex, result, ref, field) {
@Override
public boolean isPEI() {
return false;
}
};
}
@Override
public SSAGotoInstruction GotoInstruction(int iindex, int target) {
return new SSAGotoInstruction(iindex, target);
}
@Override
public SSAInstanceofInstruction InstanceofInstruction(
int iindex, int result, int ref, TypeReference checkedType) {
throw new UnsupportedOperationException();
}
@Override
public SSAInvokeInstruction InvokeInstruction(
int iindex,
int result,
int[] params,
int exception,
CallSiteReference site,
BootstrapMethod bootstrap) {
throw new UnsupportedOperationException();
}
@Override
public SSAInvokeInstruction InvokeInstruction(
int iindex,
int[] params,
int exception,
CallSiteReference site,
BootstrapMethod bootstrap) {
throw new UnsupportedOperationException();
}
@Override
public SSALoadMetadataInstruction LoadMetadataInstruction(
int iindex, int lval, TypeReference entityType, Object token) {
throw new UnsupportedOperationException();
}
@Override
public SSAMonitorInstruction MonitorInstruction(int iindex, int ref, boolean isEnter) {
throw new UnsupportedOperationException();
}
@Override
public SSANewInstruction NewInstruction(int iindex, int result, NewSiteReference site) {
return new SSANewInstruction(iindex, result, site) {
@Override
public boolean isPEI() {
return true;
}
@Override
public Collection<TypeReference> getExceptionTypes() {
return Collections.singleton(JavaScriptTypes.TypeError);
}
};
}
@Override
public SSANewInstruction NewInstruction(
int iindex, int result, NewSiteReference site, int[] params) {
throw new UnsupportedOperationException();
}
@Override
public SSAPhiInstruction PhiInstruction(int iindex, int result, int[] params) {
return new SSAPhiInstruction(iindex, result, params);
}
@Override
public SSAPiInstruction PiInstruction(
int iindex,
int result,
int val,
int piBlock,
int successorBlock,
SSAInstruction cause) {
return new SSAPiInstruction(iindex, result, val, piBlock, successorBlock, cause);
}
@Override
public SSAPutInstruction PutInstruction(
int iindex, int ref, int value, FieldReference field) {
return new SSAPutInstruction(iindex, ref, value, field) {
@Override
public boolean isPEI() {
return false;
}
};
}
@Override
public SSAPutInstruction PutInstruction(int iindex, int value, FieldReference field) {
throw new UnsupportedOperationException();
}
@Override
public SSAReturnInstruction ReturnInstruction(int iindex) {
return new SSAReturnInstruction(iindex);
}
@Override
public SSAReturnInstruction ReturnInstruction(
int iindex, int result, boolean isPrimitive) {
return new SSAReturnInstruction(iindex, result, isPrimitive);
}
@Override
public SSASwitchInstruction SwitchInstruction(
int iindex, int val, int defaultLabel, int[] casesAndLabels) {
return new SSASwitchInstruction(iindex, val, defaultLabel, casesAndLabels);
}
@Override
public SSAThrowInstruction ThrowInstruction(int iindex, int exception) {
return new SSAThrowInstruction(iindex, exception) {
@Override
public boolean isPEI() {
return true;
}
@Override
public Collection<TypeReference> getExceptionTypes() {
return Collections.emptySet();
}
};
}
@Override
public SSAUnaryOpInstruction UnaryOpInstruction(
int iindex,
com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction.IOperator operator,
int result,
int val) {
return new SSAUnaryOpInstruction(iindex, operator, result, val);
}
@Override
public SSAAddressOfInstruction AddressOfInstruction(
int iindex, int lval, int local, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
@Override
public SSAAddressOfInstruction AddressOfInstruction(
int iindex, int lval, int local, int indexVal, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
@Override
public SSAAddressOfInstruction AddressOfInstruction(
int iindex, int lval, int local, FieldReference field, TypeReference pointeeType) {
throw new UnsupportedOperationException();
}
@Override
public SSALoadIndirectInstruction LoadIndirectInstruction(
int iindex, int lval, TypeReference t, int addressVal) {
throw new UnsupportedOperationException();
}
@Override
public SSAStoreIndirectInstruction StoreIndirectInstruction(
int iindex, int addressVal, int rval, TypeReference t) {
throw new UnsupportedOperationException();
}
@Override
public PrototypeLookup PrototypeLookup(int iindex, int lval, int object) {
return new PrototypeLookup(iindex, lval, object);
}
@Override
public SetPrototype SetPrototype(int iindex, int object, int prototype) {
return new SetPrototype(iindex, object, prototype);
}
};
}
@Override
public boolean isDoubleType(TypeReference type) {
return type == JavaScriptTypes.Number || type == JavaScriptTypes.NumberObject;
}
@Override
public boolean isFloatType(TypeReference type) {
return false;
}
@Override
public boolean isIntType(TypeReference type) {
return false;
}
@Override
public boolean isLongType(TypeReference type) {
return false;
}
@Override
public boolean isMetadataType(TypeReference type) {
return false;
}
@Override
public boolean isStringType(TypeReference type) {
return type == JavaScriptTypes.String || type == JavaScriptTypes.StringObject;
}
@Override
public boolean isVoidType(TypeReference type) {
return false;
}
@Override
public TypeReference getStringType() {
return JavaScriptTypes.String;
}
@Override
public PrimitiveType getPrimitive(TypeReference reference) {
return PrimitiveType.getPrimitive(reference);
}
@Override
public boolean isBooleanType(TypeReference type) {
return JavaScriptTypes.Boolean.equals(type);
}
@Override
public boolean isCharType(TypeReference type) {
return false;
}
@Override
public AbstractRootMethod getFakeRootMethod(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
return new JSFakeRoot(cha, options, cache);
}
@Override
public <T extends InstanceKey> RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor(
CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) {
return new JavaScriptRefVisitor<>(n, result, pa, h);
}
@Override
public <T extends InstanceKey> ModVisitor<T, ? extends ExtendedHeapModel> makeModVisitor(
CGNode n,
Collection<PointerKey> result,
PointerAnalysis<T> pa,
ExtendedHeapModel h,
boolean ignoreAllocHeapDefs) {
return new JavaScriptModRef.JavaScriptModVisitor<>(n, result, h, pa);
}
};
private final JavaScriptTranslatorFactory translatorFactory;
private final CAstRewriterFactory<?, ?> preprocessor;
public JavaScriptLoader(IClassHierarchy cha, JavaScriptTranslatorFactory translatorFactory) {
this(cha, translatorFactory, null);
}
public JavaScriptLoader(
IClassHierarchy cha,
JavaScriptTranslatorFactory translatorFactory,
CAstRewriterFactory<?, ?> preprocessor) {
super(cha);
this.translatorFactory = translatorFactory;
this.preprocessor = preprocessor;
}
private static final Set<CAstQualifier> functionQualifiers;
static {
functionQualifiers = HashSetFactory.make();
functionQualifiers.add(CAstQualifier.PUBLIC);
functionQualifiers.add(CAstQualifier.FINAL);
}
public IClass makeCodeBodyType(
String name,
TypeReference P,
CAstSourcePositionMap.Position sourcePosition,
CAstEntity entity,
WalkContext context) {
return new DynamicCodeBody(
TypeReference.findOrCreate(JavaScriptTypes.jsLoader, TypeName.string2TypeName(name)),
P,
this,
sourcePosition,
entity,
context);
}
public IClass defineFunctionType(
String name, CAstSourcePositionMap.Position pos, CAstEntity entity, WalkContext context) {
return makeCodeBodyType(name, JavaScriptTypes.Function, pos, entity, context);
}
public IClass defineScriptType(
String name, CAstSourcePositionMap.Position pos, CAstEntity entity, WalkContext context) {
return makeCodeBodyType(name, JavaScriptTypes.Script, pos, entity, context);
}
public IMethod defineCodeBodyCode(
String clsName,
AbstractCFG<?, ?> cfg,
SymbolTable symtab,
boolean hasCatchBlock,
Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes,
boolean hasMonitorOp,
AstLexicalInformation lexicalInfo,
DebuggingInformation debugInfo) {
DynamicCodeBody C = (DynamicCodeBody) lookupClass(clsName, cha);
assert C != null : clsName;
return C.setCodeBody(
makeCodeBodyCode(
cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo, C));
}
public DynamicMethodObject makeCodeBodyCode(
AbstractCFG<?, ?> cfg,
SymbolTable symtab,
boolean hasCatchBlock,
Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes,
boolean hasMonitorOp,
AstLexicalInformation lexicalInfo,
DebuggingInformation debugInfo,
IClass C) {
return new DynamicMethodObject(
C,
functionQualifiers,
cfg,
symtab,
hasCatchBlock,
caughtTypes,
hasMonitorOp,
lexicalInfo,
debugInfo);
}
final CoreClass ROOT = new CoreClass(AstTypeReference.rootTypeName, null, this, null);
final CoreClass UNDEFINED =
new CoreClass(
JavaScriptTypes.Undefined.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass PRIMITIVES =
new CoreClass(
JavaScriptTypes.Primitives.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass FAKEROOT =
new CoreClass(JavaScriptTypes.FakeRoot.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass STRING =
new CoreClass(JavaScriptTypes.String.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass NULL =
new CoreClass(JavaScriptTypes.Null.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass ARRAY =
new CoreClass(JavaScriptTypes.Array.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass OBJECT =
new CoreClass(JavaScriptTypes.Object.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass TYPE_ERROR =
new CoreClass(
JavaScriptTypes.TypeError.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass CODE_BODY =
new CoreClass(JavaScriptTypes.CodeBody.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass FUNCTION =
new CoreClass(
JavaScriptTypes.Function.getName(), JavaScriptTypes.CodeBody.getName(), this, null);
final CoreClass SCRIPT =
new CoreClass(
JavaScriptTypes.Script.getName(), JavaScriptTypes.CodeBody.getName(), this, null);
final CoreClass BOOLEAN =
new CoreClass(JavaScriptTypes.Boolean.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass NUMBER =
new CoreClass(JavaScriptTypes.Number.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass DATE =
new CoreClass(JavaScriptTypes.Date.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass REGEXP =
new CoreClass(JavaScriptTypes.RegExp.getName(), JavaScriptTypes.Root.getName(), this, null);
final CoreClass BOOLEAN_OBJECT =
new CoreClass(
JavaScriptTypes.BooleanObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final CoreClass NUMBER_OBJECT =
new CoreClass(
JavaScriptTypes.NumberObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final CoreClass DATE_OBJECT =
new CoreClass(
JavaScriptTypes.DateObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final CoreClass REGEXP_OBJECT =
new CoreClass(
JavaScriptTypes.RegExpObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final CoreClass STRING_OBJECT =
new CoreClass(
JavaScriptTypes.StringObject.getName(), JavaScriptTypes.Object.getName(), this, null);
@Override
public Language getLanguage() {
return JS;
}
@Override
public ClassLoaderReference getReference() {
return JavaScriptTypes.jsLoader;
}
@Override
public SSAInstructionFactory getInstructionFactory() {
return JS.instructionFactory();
}
/**
* JavaScript files with code to model various aspects of the language semantics. See
* com.ibm.wala.cast.js/dat/prologue.js.
*/
public static final Set<String> bootstrapFileNames;
private static String prologueFileName = "prologue.js";
public static void resetPrologueFile() {
prologueFileName = "prologue.js";
}
public static void setPrologueFile(String name) {
prologueFileName = name;
}
public static void addBootstrapFile(String fileName) {
bootstrapFileNames.add(fileName);
}
static {
bootstrapFileNames = HashSetFactory.make();
bootstrapFileNames.add(prologueFileName);
}
@Override
protected TranslatorToCAst getTranslatorToCAst(
final CAst ast, ModuleEntry module, List<Module> allModules) {
TranslatorToCAst translator = translatorFactory.make(ast, module);
if (preprocessor != null) translator.addRewriter(preprocessor, true);
return translator;
}
@Override
protected TranslatorToIR initTranslator(Set<Pair<CAstEntity, ModuleEntry>> topLevelEntities) {
return new JSAstTranslator(this);
}
@Override
protected boolean shouldTranslate(CAstEntity entity) {
return true;
}
}
| 38,379
| 36.010608
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/loader/JavaScriptLoaderFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.loader;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.SingleClassLoaderFactory;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
/** Creates the single {@link IClassLoader class loader} used for JavaScript. */
public class JavaScriptLoaderFactory extends SingleClassLoaderFactory {
protected final JavaScriptTranslatorFactory translatorFactory;
protected final CAstRewriterFactory<?, ?> preprocessor;
public JavaScriptLoaderFactory(JavaScriptTranslatorFactory factory) {
this(factory, null);
}
public JavaScriptLoaderFactory(
JavaScriptTranslatorFactory factory, CAstRewriterFactory<?, ?> preprocessor) {
this.translatorFactory = factory;
this.preprocessor = preprocessor;
}
@Override
protected IClassLoader makeTheLoader(IClassHierarchy cha) {
return new JavaScriptLoader(cha, translatorFactory, preprocessor);
}
@Override
public ClassLoaderReference getTheReference() {
return JavaScriptTypes.jsLoader;
}
}
| 1,623
| 34.304348
| 84
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JSAbstractInstructionVisitor.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.ir.ssa.AstAbstractInstructionVisitor;
import com.ibm.wala.cast.ir.ssa.AstPropertyRead;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
public class JSAbstractInstructionVisitor extends AstAbstractInstructionVisitor
implements JSInstructionVisitor {
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke instruction) {}
@Override
public void visitPropertyRead(AstPropertyRead instruction) {}
@Override
public void visitPropertyWrite(AstPropertyWrite instruction) {}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction instruction) {}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf instruction) {}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {}
@Override
public void visitSetPrototype(SetPrototype instruction) {}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {}
}
| 1,420
| 29.234043
| 79
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JSInstructionFactory.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.ir.ssa.AstInstructionFactory;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
public interface JSInstructionFactory extends AstInstructionFactory {
JavaScriptCheckReference CheckReference(int iindex, int ref);
SSAGetInstruction GetInstruction(int iindex, int result, int ref, String field);
JavaScriptInstanceOf InstanceOf(int iindex, int result, int objVal, int typeVal);
JavaScriptInvoke Invoke(
int iindex, int function, int results[], int[] params, int exception, CallSiteReference site);
JavaScriptInvoke Invoke(
int iindex, int function, int result, int[] params, int exception, CallSiteReference site);
JavaScriptInvoke Invoke(
int iindex, int function, int[] params, int exception, CallSiteReference site);
SSAPutInstruction PutInstruction(int iindex, int ref, int value, String field);
JavaScriptTypeOfInstruction TypeOfInstruction(int iindex, int lval, int object);
JavaScriptWithRegion WithRegion(int iindex, int expr, boolean isEnter);
PrototypeLookup PrototypeLookup(int iindex, int lval, int object);
SetPrototype SetPrototype(int iindex, int object, int prototype);
}
| 1,652
| 35.733333
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JSInstructionVisitor.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.ir.ssa.AstInstructionVisitor;
public interface JSInstructionVisitor extends AstInstructionVisitor {
void visitJavaScriptInvoke(JavaScriptInvoke instruction);
void visitTypeOf(JavaScriptTypeOfInstruction instruction);
void visitJavaScriptInstanceOf(JavaScriptInstanceOf instruction);
void visitWithRegion(JavaScriptWithRegion instruction);
void visitCheckRef(JavaScriptCheckReference instruction);
void visitSetPrototype(SetPrototype instruction);
void visitPrototypeLookup(PrototypeLookup instruction);
}
| 962
| 30.064516
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptCheckReference.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
import java.util.Collections;
/**
* Checks if a reference is null or undefined, and if so, throws a ReferenceError. Otherwise, it's a
* no-op.
*/
public class JavaScriptCheckReference extends SSAInstruction {
private final int ref;
public JavaScriptCheckReference(int iindex, int ref) {
super(iindex);
this.ref = ref;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return ((JSInstructionFactory) insts).CheckReference(iIndex(), uses == null ? ref : uses[0]);
}
@Override
public Collection<TypeReference> getExceptionTypes() {
return Collections.singleton(JavaScriptTypes.ReferenceError);
}
@Override
public int hashCode() {
return 87621 * ref;
}
@Override
public boolean isFallThrough() {
return true;
}
@Override
public String toString(SymbolTable symbolTable) {
return "check " + getValueString(symbolTable, ref);
}
@Override
public void visit(IVisitor v) {
((JSInstructionVisitor) v).visitCheckRef(this);
}
@Override
public boolean isPEI() {
return true;
}
@Override
public int getNumberOfUses() {
return 1;
}
@Override
public int getUse(int i) {
assert i == 0;
return ref;
}
}
| 1,904
| 23.113924
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptInstanceOf.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collection;
import java.util.Collections;
public class JavaScriptInstanceOf extends SSAInstruction {
private final int objVal;
private final int typeVal;
private final int result;
public JavaScriptInstanceOf(int iindex, int result, int objVal, int typeVal) {
super(iindex);
this.objVal = objVal;
this.typeVal = typeVal;
this.result = result;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return ((JSInstructionFactory) insts)
.InstanceOf(
iIndex(),
defs == null ? result : defs[0],
uses == null ? objVal : uses[0],
uses == null ? typeVal : uses[1]);
}
@Override
public Collection<TypeReference> getExceptionTypes() {
return Collections.singleton(JavaScriptTypes.TypeError);
}
@Override
public boolean isPEI() {
return true;
}
@Override
public int hashCode() {
return objVal * 31771 + typeVal * 23 + result;
}
@Override
public boolean isFallThrough() {
return true;
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, result)
+ " = "
+ getValueString(symbolTable, objVal)
+ " is instance of "
+ getValueString(symbolTable, typeVal);
}
@Override
public void visit(IVisitor v) {
((JSInstructionVisitor) v).visitJavaScriptInstanceOf(this);
}
@Override
public int getNumberOfDefs() {
return 1;
}
@Override
public int getDef(int i) {
assert i == 0;
return result;
}
@Override
public int getNumberOfUses() {
return 2;
}
@Override
public int getUse(int i) {
switch (i) {
case 0:
return objVal;
case 1:
return typeVal;
default:
Assertions.UNREACHABLE();
return -1;
}
}
}
| 2,535
| 22.700935
| 89
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptInvoke.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.ir.ssa.MultiReturnValueInvokeInstruction;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
public class JavaScriptInvoke extends MultiReturnValueInvokeInstruction {
/** The value numbers of the arguments passed to the call. */
private final int[] params;
private final int function;
public JavaScriptInvoke(
int iindex,
int function,
int results[],
int[] params,
int exception,
CallSiteReference site) {
super(iindex, results, exception, site);
this.function = function;
this.params = params;
}
public JavaScriptInvoke(
int iindex, int function, int result, int[] params, int exception, CallSiteReference site) {
this(iindex, function, new int[] {result}, params, exception, site);
}
public JavaScriptInvoke(
int iindex, int function, int[] params, int exception, CallSiteReference site) {
this(iindex, function, null, params, exception, site);
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
int fn = function;
int newParams[] = params;
if (uses != null) {
int i = 0;
fn = uses[i++];
newParams = new int[params.length];
for (int j = 0; j < newParams.length; j++) newParams[j] = uses[i++];
}
int[] newLvals = results.clone();
int newExp = exception;
if (defs != null) {
int i = 0;
if (getNumberOfReturnValues() > 0) {
newLvals[0] = defs[i++];
}
newExp = defs[i++];
for (int j = 1; j < getNumberOfReturnValues(); j++) {
newLvals[j] = defs[i++];
}
}
return ((JSInstructionFactory) insts).Invoke(iIndex(), fn, newLvals, newParams, newExp, site);
}
@Override
public int getNumberOfUses() {
return getNumberOfPositionalParameters();
}
@Override
public String toString(SymbolTable symbolTable) {
StringBuilder s = new StringBuilder();
if (getNumberOfReturnValues() > 0) {
s.append(getValueString(symbolTable, getReturnValue(0)));
s.append(" = ");
}
if (site.getDeclaredTarget().equals(JavaScriptMethods.ctorReference)) s.append("construct ");
else if (site.getDeclaredTarget().equals(JavaScriptMethods.dispatchReference))
s.append("dispatch ");
else s.append("invoke ");
s.append(getValueString(symbolTable, function));
if (site != null) s.append('@').append(site.getProgramCounter());
if (params != null) {
if (params.length > 0) {
s.append(' ').append(getValueString(symbolTable, params[0]));
}
for (int i = 1; i < params.length; i++) {
s.append(',').append(getValueString(symbolTable, params[i]));
}
}
if (exception == -1) {
s.append(" exception: NOT MODELED");
} else {
s.append(" exception:").append(getValueString(symbolTable, exception));
}
return s.toString();
}
@Override
public void visit(IVisitor v) {
assert v instanceof JSInstructionVisitor;
((JSInstructionVisitor) v).visitJavaScriptInvoke(this);
}
@Override
public int getNumberOfPositionalParameters() {
if (params == null) {
return 1;
} else {
return params.length + 1;
}
}
@Override
public int getUse(int j) {
if (j == 0) return function;
else if (j <= params.length) return params[j - 1];
else {
return super.getUse(j);
}
}
public int getFunction() {
return function;
}
/*
* (non-Javadoc)
* @see com.ibm.domo.ssa.Instruction#getExceptionTypes()
*/
@Override
public Collection<TypeReference> getExceptionTypes() {
return Util.typeErrorExceptions();
}
@Override
public int hashCode() {
return site.hashCode() * function * 7529;
}
// public boolean equals(Object obj) {
// if (obj instanceof JavaScriptInvoke) {
// JavaScriptInvoke other = (JavaScriptInvoke)obj;
// if (site.equals(other.site)) {
// if (getNumberOfUses() == other.getNumberOfUses()) {
// for(int i = 0; i < getNumberOfUses(); i++) {
// if (getUse(i) != other.getUse(i)) {
// return false;
// }
// }
//
// if (getNumberOfDefs() == other.getNumberOfDefs()) {
// for(int i = 0; i < getNumberOfDefs(); i++) {
// if (getDef(i) != other.getDef(i)) {
// return false;
// }
// }
//
// return true;
// }
// }
// }
// }
//
// return false;
// }
}
| 5,034
| 25.781915
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptPropertyRead.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.ir.ssa.AstPropertyRead;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
public class JavaScriptPropertyRead extends AstPropertyRead {
public JavaScriptPropertyRead(int iindex, int result, int objectRef, int memberRef) {
super(iindex, result, objectRef, memberRef);
}
/* (non-Javadoc)
* @see com.ibm.domo.ssa.Instruction#getExceptionTypes()
*/
@Override
public Collection<TypeReference> getExceptionTypes() {
return Util.typeErrorExceptions();
}
}
| 932
| 30.1
| 87
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptPropertyWrite.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
public class JavaScriptPropertyWrite extends AstPropertyWrite {
public JavaScriptPropertyWrite(int iindex, int objectRef, int memberRef, int value) {
super(iindex, objectRef, memberRef, value);
}
/*
* (non-Javadoc)
* @see com.ibm.domo.ssa.Instruction#getExceptionTypes()
*/
@Override
public Collection<TypeReference> getExceptionTypes() {
return Util.typeErrorExceptions();
}
}
| 940
| 28.40625
| 87
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptTypeOfInstruction.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.ssa.SSAAbstractUnaryInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
public class JavaScriptTypeOfInstruction extends SSAAbstractUnaryInstruction {
public JavaScriptTypeOfInstruction(int iindex, int lval, int object) {
super(iindex, lval, object);
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return ((JSInstructionFactory) insts)
.TypeOfInstruction(
iIndex(), (defs != null ? defs[0] : getDef(0)), (uses != null ? uses[0] : getUse(0)));
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, getDef(0))
+ " = typeof("
+ getValueString(symbolTable, getUse(0))
+ ')';
}
@Override
public void visit(IVisitor v) {
((JSInstructionVisitor) v).visitTypeOf(this);
}
@Override
public Collection<TypeReference> getExceptionTypes() {
return Util.noExceptions();
}
}
| 1,539
| 29.196078
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/JavaScriptWithRegion.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
public class JavaScriptWithRegion extends SSAInstruction {
private final int expr;
private final boolean isEnter;
public JavaScriptWithRegion(int iindex, int expr, boolean isEnter) {
super(iindex);
this.expr = expr;
this.isEnter = isEnter;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return ((JSInstructionFactory) insts)
.WithRegion(iIndex(), uses == null ? expr : uses[0], isEnter);
}
@Override
public Collection<TypeReference> getExceptionTypes() {
return null;
}
@Override
public int hashCode() {
return 353456 * expr * (isEnter ? 1 : -1);
}
@Override
public boolean isFallThrough() {
return true;
}
@Override
public String toString(SymbolTable symbolTable) {
return (isEnter ? "enter" : "exit") + " of with " + getValueString(symbolTable, expr);
}
@Override
public void visit(IVisitor v) {
((JSInstructionVisitor) v).visitWithRegion(this);
}
@Override
public int getNumberOfUses() {
return 1;
}
@Override
public int getUse(int i) {
assert i == 0;
return expr;
}
}
| 1,744
| 23.577465
| 90
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/PrototypeLookup.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.ssa.SSAAbstractUnaryInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
/**
* Non-deterministically assigns some object in the prototype chain of val (or val itself) to
* result.
*/
public class PrototypeLookup extends SSAAbstractUnaryInstruction {
public PrototypeLookup(int iindex, int result, int val) {
super(iindex, result, val);
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return ((JSInstructionFactory) insts)
.PrototypeLookup(
iIndex(), (defs != null ? defs[0] : getDef(0)), (uses != null ? uses[0] : getUse(0)));
}
@Override
public String toString(SymbolTable symbolTable) {
return getValueString(symbolTable, getDef(0))
+ " = prototype_values("
+ getValueString(symbolTable, getUse(0))
+ ')';
}
@Override
public void visit(IVisitor v) {
((JSInstructionVisitor) v).visitPrototypeLookup(this);
}
}
| 1,460
| 29.4375
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/SetPrototype.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SymbolTable;
public class SetPrototype extends SSAInstruction {
private final int object;
private final int prototype;
public SetPrototype(int iindex, int object, int prototype) {
super(iindex);
this.object = object;
this.prototype = prototype;
}
@Override
public int getNumberOfUses() {
return 2;
}
@Override
public int getUse(int j) throws UnsupportedOperationException {
assert j >= 0 && j <= 1;
return (j == 0) ? object : prototype;
}
@Override
public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) {
return ((JSInstructionFactory) insts)
.SetPrototype(
iIndex(), (uses != null ? uses[0] : object), (uses != null ? uses[1] : prototype));
}
@Override
public String toString(SymbolTable symbolTable) {
return "set_prototype("
+ getValueString(symbolTable, object)
+ ", "
+ getValueString(symbolTable, prototype)
+ ')';
}
@Override
public void visit(IVisitor v) {
((JSInstructionVisitor) v).visitSetPrototype(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + object;
result = prime * result + prototype;
return result;
}
@Override
public boolean isFallThrough() {
return true;
}
}
| 1,856
| 24.438356
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ssa/Util.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.ssa;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.types.TypeReference;
import java.util.Collection;
import java.util.Collections;
class Util {
private static final Collection<TypeReference> TYPE_ERROR_EXCEPTIONS =
Collections.singleton(JavaScriptTypes.TypeError);
public static Collection<TypeReference> typeErrorExceptions() {
return TYPE_ERROR_EXCEPTIONS;
}
public static Collection<TypeReference> noExceptions() {
return Collections.emptySet();
}
}
| 910
| 29.366667
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/JSAstTranslator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.AstTranslator;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.ssa.JavaScriptInstanceOf;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.CAstSymbol;
import com.ibm.wala.cast.tree.CAstType;
import com.ibm.wala.cast.tree.impl.CAstSymbolImpl;
import com.ibm.wala.cast.tree.visit.CAstVisitor;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/** Specialization of {@link AstTranslator} for JavaScript. */
public class JSAstTranslator extends AstTranslator {
private static final boolean DEBUG = false;
public JSAstTranslator(JavaScriptLoader loader) {
super(loader);
}
private static boolean isPrologueScript(WalkContext context) {
return JavaScriptLoader.bootstrapFileNames.contains(context.getModule().getName());
}
@Override
protected boolean useDefaultInitValues() {
return false;
}
@Override
protected boolean hasImplicitGlobals() {
return true;
}
@Override
protected boolean treatGlobalsAsLexicallyScoped() {
return false;
}
@Override
protected TypeReference defaultCatchType() {
return JavaScriptTypes.Root;
}
@Override
protected TypeReference makeType(CAstType type) {
assert "Any".equals(type.getName());
return JavaScriptTypes.Root;
}
@Override
protected boolean ignoreName(String name) {
return super.ignoreName(name) || name.endsWith(" temp");
}
@Override
protected String[] makeNameMap(CAstEntity n, Set<Scope> scopes, SSAInstruction[] insts) {
String[] names = super.makeNameMap(n, scopes, insts);
for (SSAInstruction inst : insts) {
if (inst instanceof PrototypeLookup) {
if (names[inst.getUse(0)] != null) {
names[inst.getDef()] = names[inst.getUse(0)];
}
}
}
return names;
}
/**
* generate an instruction that checks if readVn is undefined and throws an exception if it isn't
*/
private void addDefinedCheck(CAstNode n, WalkContext context, int readVn) {
context.cfg().addPreNode(n);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.CheckReference(context.cfg().getCurrentInstruction(), readVn));
CAstNode target = context.getControlFlow().getTarget(n, JavaScriptTypes.Root);
context.cfg().addPreNode(n, context.getUnwindState());
context.cfg().newBlock(true);
if (target != null) {
context.cfg().addPreEdge(n, target, true);
} else {
context.cfg().addPreEdgeToExit(n, true);
}
}
@Override
protected int doLexicallyScopedRead(
CAstNode n, WalkContext context, String name, TypeReference type) {
int readVn = super.doLexicallyScopedRead(n, context, name, type);
// should get an exception if name is undefined
addDefinedCheck(n, context, readVn);
return readVn;
}
@Override
protected int doGlobalRead(CAstNode n, WalkContext context, String name, TypeReference type) {
int readVn = super.doGlobalRead(n, context, name, type);
// add a check if name is undefined, unless we're reading the value 'undefined'
if (n != null
&& !("undefined".equals(name)
|| "$$undefined".equals(name)
|| "__WALA__int3rnal__global".equals(name))) {
addDefinedCheck(n, context, readVn);
}
return readVn;
}
@Override
protected boolean defineType(CAstEntity type, WalkContext wc) {
Assertions.UNREACHABLE(
"JavaScript doesn't have types. I suggest you look elsewhere for your amusement.");
return false;
}
@Override
protected void defineField(CAstEntity topEntity, WalkContext wc, CAstEntity n) {
Assertions.UNREACHABLE("JavaScript doesn't have fields");
}
@Override
protected String composeEntityName(WalkContext parent, CAstEntity f) {
if (f.getKind() == CAstEntity.SCRIPT_ENTITY) return f.getName();
else return parent.getName() + '/' + f.getName();
}
@Override
protected void declareFunction(CAstEntity N, WalkContext context) {
String fnName = composeEntityName(context, N);
if (N.getKind() == CAstEntity.SCRIPT_ENTITY) {
((JavaScriptLoader) loader).defineScriptType('L' + fnName, N.getPosition(), N, context);
} else if (N.getKind() == CAstEntity.FUNCTION_ENTITY) {
((JavaScriptLoader) loader).defineFunctionType('L' + fnName, N.getPosition(), N, context);
} else {
Assertions.UNREACHABLE();
}
}
@Override
protected void defineFunction(
CAstEntity N,
WalkContext definingContext,
AbstractCFG<SSAInstruction, ? extends IBasicBlock<SSAInstruction>> cfg,
SymbolTable symtab,
boolean hasCatchBlock,
Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes,
boolean hasMonitorOp,
AstLexicalInformation LI,
DebuggingInformation debugInfo) {
if (DEBUG) System.err.println(("\n\nAdding code for " + N));
String fnName = composeEntityName(definingContext, N);
if (DEBUG) System.err.println(cfg);
((JavaScriptLoader) loader)
.defineCodeBodyCode(
'L' + fnName, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, LI, debugInfo);
}
@Override
protected void doThrow(WalkContext context, int exception) {
context
.cfg()
.addInstruction(insts.ThrowInstruction(context.cfg().getCurrentInstruction(), exception));
}
@Override
protected void doCall(
WalkContext context,
CAstNode call,
int result,
int exception,
CAstNode name,
int receiver,
int[] arguments) {
MethodReference ref =
name.getValue().equals("ctor")
? JavaScriptMethods.ctorReference
: name.getValue().equals("dispatch")
? JavaScriptMethods.dispatchReference
: AstMethodReference.fnReference(JavaScriptTypes.CodeBody);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.Invoke(
context.cfg().getCurrentInstruction(),
receiver,
result,
arguments,
exception,
new DynamicCallSiteReference(ref, context.cfg().getCurrentInstruction())));
context.cfg().addPreNode(call, context.getUnwindState());
// this new block is for the normal termination case
context.cfg().newBlock(true);
// exceptional case: flow to target given in CAst, or if null, the exit node
if (context.getControlFlow().getTarget(call, null) != null)
context.cfg().addPreEdge(call, context.getControlFlow().getTarget(call, null), true);
else context.cfg().addPreEdgeToExit(call, true);
}
@Override
protected void doNewObject(
WalkContext context, CAstNode newNode, int result, Object type, int[] arguments) {
assert arguments == null;
TypeReference typeRef =
TypeReference.findOrCreate(JavaScriptTypes.jsLoader, TypeName.string2TypeName("L" + type));
context
.cfg()
.addInstruction(
insts.NewInstruction(
context.cfg().getCurrentInstruction(),
result,
NewSiteReference.make(context.cfg().getCurrentInstruction(), typeRef)));
}
@Override
protected void doMaterializeFunction(
CAstNode n, WalkContext context, int result, int exception, CAstEntity fn) {
int nm = context.currentScope().getConstantValue('L' + composeEntityName(context, fn));
// "Function" is the name we use to model the constructor of function values
int tmp = super.doGlobalRead(n, context, "Function", JavaScriptTypes.Function);
Position old = null;
if (n.getKind() == CAstNode.FUNCTION_STMT) {
// For function statements, set the current position (used for the constructor invocation
// instruction added below) to be the location of the statement itself.
old = getCurrentPosition();
CAstEntity entity = (CAstEntity) n.getChild(0).getValue();
currentPosition = entity.getPosition();
}
try {
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.Invoke(
context.cfg().getCurrentInstruction(),
tmp,
result,
new int[] {nm},
exception,
new DynamicCallSiteReference(
JavaScriptMethods.ctorReference, context.cfg().getCurrentInstruction())));
} finally {
// Reset the current position if it was temporarily updated for a function statement
if (old != null) {
currentPosition = old;
}
}
}
@Override
public void doArrayRead(
WalkContext context, int result, int arrayValue, CAstNode arrayRef, int[] dimValues) {
Assertions.UNREACHABLE("JSAstTranslator.doArrayRead() called!");
}
@Override
public void doArrayWrite(
WalkContext context, int arrayValue, CAstNode arrayRef, int[] dimValues, int rval) {
Assertions.UNREACHABLE("JSAstTranslator.doArrayWrite() called!");
}
@Override
protected void doFieldRead(
WalkContext context, int result, int receiver, CAstNode elt, CAstNode readNode) {
this.visit(elt, context, this);
int x = context.currentScope().allocateTempValue();
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(context.cfg().getCurrentInstruction(), x, receiver));
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.PrototypeLookup(context.cfg().getCurrentInstruction(), x, x));
if (elt.getKind() == CAstNode.CONSTANT && elt.getValue() instanceof String) {
String field = (String) elt.getValue();
// symtab needs to have this value
context.currentScope().getConstantValue(field);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.GetInstruction(context.cfg().getCurrentInstruction(), result, x, field));
} else {
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.PropertyRead(
context.cfg().getCurrentInstruction(), result, x, context.getValue(elt)));
}
// generate code to handle read of property from null or undefined
context.cfg().addPreNode(readNode, context.getUnwindState());
context.cfg().newBlock(true);
if (context.getControlFlow().getTarget(readNode, JavaScriptTypes.TypeError) != null)
context
.cfg()
.addPreEdge(
readNode,
context.getControlFlow().getTarget(readNode, JavaScriptTypes.TypeError),
true);
else context.cfg().addPreEdgeToExit(readNode, true);
}
@Override
protected void doFieldWrite(
WalkContext context, int receiver, CAstNode elt, CAstNode parent, int rval) {
this.visit(elt, context, this);
if (elt.getKind() == CAstNode.CONSTANT && elt.getValue() instanceof String) {
String field = (String) elt.getValue();
if (isPrologueScript(context) && "__proto__".equals(field)) {
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.SetPrototype(context.cfg().getCurrentInstruction(), receiver, rval));
return;
}
}
/*
} else {
context.currentScope().getConstantValue(field);
SSAPutInstruction put = ((JSInstructionFactory) insts).PutInstruction(context.cfg().getCurrentInstruction(), receiver, rval, field);
try {
assert field.equals(put.getDeclaredField().getName().toUnicodeString());
} catch (UTFDataFormatException e) {
Assertions.UNREACHABLE();
}
context.cfg().addInstruction(put);
}
} else {
*/
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.PropertyWrite(
context.cfg().getCurrentInstruction(), receiver, context.getValue(elt), rval));
context.cfg().addPreNode(parent, context.getUnwindState());
// generate code to handle read of property from null or undefined
context.cfg().newBlock(true);
if (context.getControlFlow().getTarget(parent, JavaScriptTypes.TypeError) != null)
context
.cfg()
.addPreEdge(
parent, context.getControlFlow().getTarget(parent, JavaScriptTypes.TypeError), true);
else context.cfg().addPreEdgeToExit(parent, true);
// }
}
private void doPrimitiveNew(WalkContext context, int resultVal, String typeName) {
doNewObject(context, null, resultVal, typeName + "Object", null);
// set the class property of the new object
int rval = context.currentScope().getConstantValue(typeName);
context.currentScope().getConstantValue("class");
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.PutInstruction(context.cfg().getCurrentInstruction(), resultVal, rval, "class"));
}
@Override
protected void doPrimitive(int resultVal, WalkContext context, CAstNode primitiveCall) {
try {
String name = (String) primitiveCall.getChild(0).getValue();
switch (name) {
case "GlobalNaN":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Float.NaN)));
break;
case "GlobalInfinity":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Float.POSITIVE_INFINITY)));
break;
case "MathE":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Math.E)));
break;
case "MathPI":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Math.PI)));
break;
case "MathSQRT1_2":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Math.sqrt(.5))));
break;
case "MathSQRT2":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Math.sqrt(2))));
break;
case "MathLN2":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Math.log(2))));
break;
case "MathLN10":
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(Math.log(10))));
break;
case "NewObject":
doNewObject(context, null, resultVal, "Object", null);
break;
case "NewArray":
doNewObject(context, null, resultVal, "Array", null);
break;
case "NewString":
doPrimitiveNew(context, resultVal, "String");
break;
case "NewNumber":
doPrimitiveNew(context, resultVal, "Number");
break;
case "NewRegExp":
doPrimitiveNew(context, resultVal, "RegExp");
break;
case "NewFunction":
doNewObject(context, null, resultVal, "Function", null);
break;
case "NewUndefined":
doNewObject(context, null, resultVal, "Undefined", null);
break;
default:
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(
context.cfg().getCurrentInstruction(),
resultVal,
context.currentScope().getConstantValue(null)));
break;
}
} catch (ClassCastException e) {
throw new RuntimeException(
"Cannot translate primitive " + primitiveCall.getChild(0).getValue(), e);
}
}
@Override
protected boolean visitInstanceOf(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) {
WalkContext context = c;
int result = context.currentScope().allocateTempValue();
context.setValue(n, result);
return false;
}
@Override
protected void leaveInstanceOf(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) {
WalkContext context = c;
int result = context.getValue(n);
visit(n.getChild(0), context, visitor);
int value = context.getValue(n.getChild(0));
visit(n.getChild(1), context, visitor);
int type = context.getValue(n.getChild(1));
context
.cfg()
.addInstruction(
new JavaScriptInstanceOf(context.cfg().getCurrentInstruction(), result, value, type));
}
@Override
protected void doPrologue(WalkContext context) {
super.doPrologue(context);
int tempVal = context.currentScope().allocateTempValue();
doNewObject(context, null, tempVal, "Array", null);
CAstSymbol args = new CAstSymbolImpl("arguments", Any);
context.currentScope().declare(args, tempVal);
// context.cfg().addInstruction(((JSInstructionFactory)insts).PutInstruction(context.cfg().getCurrentInstruction(), 1, tempVal, "arguments"));
}
@Override
protected boolean doVisit(CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) {
switch (n.getKind()) {
case CAstNode.TYPE_OF:
{
int result = context.currentScope().allocateTempValue();
this.visit(n.getChild(0), context, this);
int ref = context.getValue(n.getChild(0));
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.TypeOfInstruction(context.cfg().getCurrentInstruction(), result, ref));
context.setValue(n, result);
return true;
}
case JavaScriptCAstNode.ENTER_WITH:
case JavaScriptCAstNode.EXIT_WITH:
{
this.visit(n.getChild(0), context, this);
int ref = context.getValue(n.getChild(0));
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.WithRegion(
context.cfg().getCurrentInstruction(),
ref,
n.getKind() == JavaScriptCAstNode.ENTER_WITH));
return true;
}
default:
{
return false;
}
}
}
public static final CAstType Any =
new CAstType() {
@Override
public String getName() {
return "Any";
}
@Override
public Collection<CAstType> getSupertypes() {
return Collections.emptySet();
}
};
@Override
protected CAstType topType() {
return Any;
}
@Override
protected CAstType exceptionType() {
return Any;
}
@Override
protected Position[] getParameterPositions(CAstEntity e) {
if (e.getKind() == CAstEntity.SCRIPT_ENTITY) {
return new Position[0];
} else {
Position[] ps = new Position[e.getArgumentCount()];
for (int i = 2; i < e.getArgumentCount(); i++) {
ps[i] = e.getPosition(i - 2);
}
return ps;
}
}
}
| 22,387
| 33.180153
| 146
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/JSConstantFoldingRewriter.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.ConstantFoldingRewriter;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.impl.CAstOperator;
public class JSConstantFoldingRewriter extends ConstantFoldingRewriter {
public JSConstantFoldingRewriter(CAst Ast) {
super(Ast);
}
@Override
protected Object eval(CAstOperator op, Object lhs, Object rhs) {
if (op == CAstOperator.OP_ADD) {
if (lhs instanceof String || rhs instanceof String) {
return String.valueOf(lhs) + rhs;
} else if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() + ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_BIT_AND) {
} else if (op == CAstOperator.OP_BIT_OR) {
} else if (op == CAstOperator.OP_BIT_XOR) {
} else if (op == CAstOperator.OP_BITNOT) {
} else if (op == CAstOperator.OP_CONCAT) {
if (lhs instanceof String || rhs instanceof String) {
return String.valueOf(lhs) + rhs;
}
} else if (op == CAstOperator.OP_DIV) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() / ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_EQ) {
} else if (op == CAstOperator.OP_GE) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() >= ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_GT) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() > ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_LE) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() <= ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_LSH) {
} else if (op == CAstOperator.OP_LT) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() < ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_MOD) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() % ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_MUL) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() * ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_NE) {
} else if (op == CAstOperator.OP_NOT) {
} else if (op == CAstOperator.OP_REL_AND) {
} else if (op == CAstOperator.OP_REL_OR) {
} else if (op == CAstOperator.OP_REL_XOR) {
} else if (op == CAstOperator.OP_RSH) {
} else if (op == CAstOperator.OP_STRICT_EQ) {
} else if (op == CAstOperator.OP_STRICT_NE) {
} else if (op == CAstOperator.OP_SUB) {
if (lhs instanceof Number && rhs instanceof Number) {
return ((Number) lhs).doubleValue() - ((Number) rhs).doubleValue();
}
} else if (op == CAstOperator.OP_URSH) {
}
// no constant value
return null;
}
}
| 3,505
| 30.303571
| 76
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/JavaScriptCAstNode.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.tree.CAstNode;
public interface JavaScriptCAstNode extends CAstNode {
int ENTER_WITH = SUB_LANGUAGE_BASE + 1;
int EXIT_WITH = SUB_LANGUAGE_BASE + 2;
}
| 593
| 27.285714
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/JavaScriptLoopUnwindingTranslatorFactory.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.rewrite.AstLoopUnwinder;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.classLoader.SourceModule;
public abstract class JavaScriptLoopUnwindingTranslatorFactory
implements JavaScriptTranslatorFactory {
private final int unwindFactor;
protected JavaScriptLoopUnwindingTranslatorFactory(int unwindFactor) {
this.unwindFactor = unwindFactor;
}
JavaScriptLoopUnwindingTranslatorFactory() {
this(3);
}
protected abstract TranslatorToCAst translateInternal(CAst Ast, SourceModule M, String N);
@Override
public TranslatorToCAst make(CAst ast, final ModuleEntry M) {
String N;
if (M instanceof SourceFileModule) {
N = ((SourceFileModule) M).getClassName();
} else {
N = M.getName();
}
TranslatorToCAst xlator = translateInternal(ast, (SourceModule) M, N);
xlator.addRewriter(ast1 -> new AstLoopUnwinder(ast1, true, unwindFactor), false);
return xlator;
}
}
| 1,528
| 30.204082
| 92
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/JavaScriptTranslatorFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.classLoader.ModuleEntry;
/**
* Factory interface for creating translators that generate the CAst for some JavaScript source
* file. Used to abstract which JavaScript parser is being used.
*/
public interface JavaScriptTranslatorFactory {
TranslatorToCAst make(CAst ast, ModuleEntry M);
}
| 825
| 32.04
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/JavaScriptTranslatorToCAst.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.util.debug.Assertions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
interface WalkContext<C extends WalkContext<C, T>, T> extends TranslatorToCAst.WalkContext<C, T> {
@Override
WalkContext<C, T> getParent();
default String script() {
return getParent().script();
}
default int setOperation(T node) {
return getParent().setOperation(node);
}
default boolean foundMemberOperation(T node) {
return getParent().foundMemberOperation(node);
}
default void copyOperation(T from, T to) {
getParent().copyOperation(from, to);
}
}
class RootContext<C extends WalkContext<C, T>, T> extends TranslatorToCAst.RootContext<C, T>
implements WalkContext<C, T> {
@Override
public WalkContext<C, T> getParent() {
assert false;
return null;
}
@Override
public String script() {
return null;
}
@Override
public T top() {
Assertions.UNREACHABLE();
return null;
}
@Override
public void addNameDecl(CAstNode v) {
Assertions.UNREACHABLE();
}
@Override
public List<CAstNode> getNameDecls() {
Assertions.UNREACHABLE();
return null;
}
@Override
public CAstNode getCatchTarget() {
Assertions.UNREACHABLE();
return null;
}
@Override
public int setOperation(T node) {
return -1;
}
@Override
public boolean foundMemberOperation(T node) {
return false;
}
@Override
public void copyOperation(T from, T to) {
Assertions.UNREACHABLE();
}
}
class FunctionContext<C extends WalkContext<C, T>, T>
extends TranslatorToCAst.FunctionContext<C, T> implements WalkContext<C, T> {
private final List<CAstNode> initializers = new ArrayList<>();
@Override
public WalkContext<C, T> getParent() {
return (WalkContext<C, T>) super.getParent();
}
protected FunctionContext(C parent, T s) {
super(parent, s);
}
@Override
public void addNameDecl(CAstNode v) {
initializers.add(v);
}
@Override
public List<CAstNode> getNameDecls() {
return initializers;
}
@Override
public String script() {
return parent.script();
}
@Override
public CAstNode getCatchTarget() {
return CAstControlFlowMap.EXCEPTION_TO_EXIT;
}
@Override
public int setOperation(T node) {
return parent.setOperation(node);
}
@Override
public boolean foundMemberOperation(T node) {
return parent.foundMemberOperation(node);
}
@Override
public void copyOperation(T from, T to) {
parent.copyOperation(from, to);
}
}
class ScriptContext<C extends WalkContext<C, T>, T> extends FunctionContext<C, T> {
private final String script;
ScriptContext(C parent, T s, String script) {
super(parent, s);
this.script = script;
}
@Override
public String script() {
return script;
}
}
/**
* Used to determine the value to be passed as the 'this' argument for a function call. This is
* needed since in JavaScript, you can write a call e(...) where e is some arbitrary expression,
* and in the case where e is a property access like e'.f, we must discover that the value of
* expression e' is passed as the 'this' parameter.
*
* <p>The general strategy is to store the value of the expression passed as the 'this' parameter
* in baseVar, and then to use baseVar as the actual argument sub-node for the CAst call node
*/
class MemberDestructuringContext<C extends WalkContext<C, T>, T> implements WalkContext<C, T> {
private final WalkContext<C, T> parent;
/**
* node for which we actually care about what the base pointer is. this helps to handle cases
* like x.y.f(), where we would like to store x.y in baseVar, but not x when we recurse.
*/
private final Set<T> baseFor = new HashSet<>();
private final int operationIndex;
/** have we discovered a value to be passed as the 'this' parameter? */
private boolean foundBase = false;
protected MemberDestructuringContext(C parent, T initialBaseFor, int operationIndex) {
this.parent = parent;
baseFor.add(initialBaseFor);
this.operationIndex = operationIndex;
}
@Override
public int setOperation(T node) {
if (baseFor.contains(node)) {
foundBase = true;
return operationIndex;
} else {
return -1;
}
}
@Override
public boolean foundMemberOperation(T node) {
return foundBase;
}
@Override
public void copyOperation(T from, T to) {
if (baseFor.contains(from)) baseFor.add(to);
}
@Override
public WalkContext<C, T> getParent() {
return parent;
}
}
}
| 5,514
| 24.298165
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/translator/PropertyReadExpander.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.AstTranslator.InternalCAstSymbol;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import java.util.List;
import java.util.Map;
/**
* Transforms property reads to make prototype chain operations explicit. Each read is converted to
* a do loop that walks up the prototype chain until the property is found or the chain has ended.
*/
public class PropertyReadExpander
extends CAstRewriter<PropertyReadExpander.RewriteContext, PropertyReadExpander.ExpanderKey> {
enum ExpanderKey implements com.ibm.wala.cast.tree.rewrite.CAstRewriter.CopyKey<ExpanderKey> {
EVERYWHERE,
EXTRA {
@Override
public ExpanderKey parent() {
return EVERYWHERE;
}
};
@Override
public ExpanderKey parent() {
return null;
}
}
private int readTempCounter = 0;
private static final String TEMP_NAME = "readTemp";
abstract static class RewriteContext implements CAstRewriter.RewriteContext<ExpanderKey> {
@Override
public ExpanderKey key() {
return ExpanderKey.EVERYWHERE;
}
/**
* are we in a context where a property access should be treated as a read? e.g., should return
* false if we are handling the LHS of an assignment
*/
abstract boolean inRead();
/** are we handling a sub-node of an assignment? */
abstract boolean inAssignment();
/** @see AssignPreOrPostOpContext */
abstract void setAssign(CAstNode receiverTemp, CAstNode elementTemp);
}
/** for handling property reads within assignments with pre or post-ops, e.g., x.f++ */
private static final class AssignPreOrPostOpContext extends RewriteContext {
private CAstNode receiverTemp;
private CAstNode elementTemp;
@Override
public boolean inAssignment() {
return true;
}
@Override
public boolean inRead() {
return true;
}
/**
* store the CAstNodes used to represent the loop variable for the prototype-chain traversal
* (receiverTemp) and the desired property (elementTemp)
*/
@Override
public void setAssign(CAstNode receiverTemp, CAstNode elementTemp) {
this.receiverTemp = receiverTemp;
this.elementTemp = elementTemp;
}
}
private static final RewriteContext READ =
new RewriteContext() {
@Override
public boolean inAssignment() {
return false;
}
@Override
public boolean inRead() {
return true;
}
@Override
public void setAssign(CAstNode receiverTemp, CAstNode elementTemp) {
Assertions.UNREACHABLE();
}
};
private static final RewriteContext ASSIGN =
new RewriteContext() {
@Override
public boolean inAssignment() {
return true;
}
@Override
public boolean inRead() {
return false;
}
@Override
public void setAssign(CAstNode receiverTemp, CAstNode elementTemp) {
Assertions.UNREACHABLE();
}
};
public PropertyReadExpander(CAst Ast) {
super(Ast, true, READ);
}
/**
* create a CAstNode l representing a loop that traverses the prototype chain from receiver
* searching for the constant property element. update nodeMap to map root to an expression that
* reads the property from the right node.
*/
private CAstNode makeConstRead(
CAstNode root,
CAstNode receiver,
CAstNode element,
RewriteContext context,
Map<Pair<CAstNode, ExpanderKey>, CAstNode> nodeMap) {
CAstNode get, result;
String receiverTemp = TEMP_NAME + readTempCounter++;
String elt = (String) element.getValue();
if (elt.equals("prototype") || elt.equals("__proto__")) {
result =
Ast.makeNode(
CAstNode.BLOCK_EXPR,
get = Ast.makeNode(CAstNode.OBJECT_REF, receiver, Ast.makeConstant(elt)));
} else {
if (context.inAssignment()) {
context.setAssign(
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)), Ast.makeConstant(elt));
}
result =
Ast.makeNode(
CAstNode.BLOCK_EXPR,
// declare loop variable and initialize to the receiver
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new InternalCAstSymbol(receiverTemp, JSAstTranslator.Any, false, false)),
receiver),
Ast.makeNode(
CAstNode.LOOP,
// while the desired property of the loop variable is not
// defined...
Ast.makeNode(
CAstNode.UNARY_EXPR,
CAstOperator.OP_NOT,
Ast.makeNode(
CAstNode.IS_DEFINED_EXPR,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeConstant(elt))),
// set the loop variable to be its prototype
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeNode(
CAstNode.OBJECT_REF,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeConstant("__proto__")))),
get =
Ast.makeNode(
CAstNode.OBJECT_REF,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeConstant(elt)));
}
nodeMap.put(Pair.make(root, context.key()), result);
nodeMap.put(Pair.make(root, ExpanderKey.EXTRA), get);
return result;
}
/**
* similar to makeConstRead(), but desired property is some expression instead of a constant
*
* @see #makeConstRead(CAstNode, CAstNode, CAstNode, RewriteContext, Map)
*/
private CAstNode makeVarRead(
CAstNode root,
CAstNode receiver,
CAstNode element,
RewriteContext context,
Map<Pair<CAstNode, ExpanderKey>, CAstNode> nodeMap) {
String receiverTemp = TEMP_NAME + readTempCounter++;
String elementTemp = TEMP_NAME + readTempCounter++;
if (context.inAssignment()) {
context.setAssign(
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(elementTemp)));
}
CAstNode get;
CAstNode result =
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new InternalCAstSymbol(receiverTemp, JSAstTranslator.Any, false, false)),
receiver),
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new InternalCAstSymbol(elementTemp, JSAstTranslator.Any, false, false)),
element),
Ast.makeNode(
CAstNode.LOOP,
Ast.makeNode(
CAstNode.UNARY_EXPR,
CAstOperator.OP_NOT,
Ast.makeNode(
CAstNode.IS_DEFINED_EXPR,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(elementTemp)))),
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeNode(
CAstNode.OBJECT_REF,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeConstant("__proto__")))),
get =
Ast.makeNode(
CAstNode.OBJECT_REF,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(receiverTemp)),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(elementTemp))));
nodeMap.put(Pair.make(root, context.key()), get);
return result;
}
@Override
protected CAstNode copyNodes(
CAstNode root,
final CAstControlFlowMap cfg,
RewriteContext context,
Map<Pair<CAstNode, ExpanderKey>, CAstNode> nodeMap) {
int kind = root.getKind();
if (kind == CAstNode.OBJECT_REF && context.inRead()) {
// if we see a property access (OBJECT_REF) in a read context, transform
// to a loop traversing the prototype chain
CAstNode readLoop;
CAstNode receiver = copyNodes(root.getChild(0), cfg, READ, nodeMap);
CAstNode element = copyNodes(root.getChild(1), cfg, READ, nodeMap);
if (element.getKind() == CAstNode.CONSTANT && element.getValue() instanceof String) {
readLoop = makeConstRead(root, receiver, element, context, nodeMap);
} else {
readLoop = makeVarRead(root, receiver, element, context, nodeMap);
}
return readLoop;
} else if (kind == CAstNode.ASSIGN_PRE_OP || kind == CAstNode.ASSIGN_POST_OP) {
// handle cases like x.f++, represented as ASSIGN_POST_OP(x.f,1,+)
AssignPreOrPostOpContext ctxt = new AssignPreOrPostOpContext();
// generate loop for the first child (x.f for example), keeping the loop var and element var
// in ctxt
CAstNode lval = copyNodes(root.getChild(0), cfg, ctxt, nodeMap);
CAstNode rval = copyNodes(root.getChild(1), cfg, READ, nodeMap);
CAstNode op = copyNodes(root.getChild(2), cfg, READ, nodeMap);
if (ctxt.receiverTemp != null) { // if we found a nested property access
String temp1 = TEMP_NAME + readTempCounter++;
String temp2 = TEMP_NAME + readTempCounter++;
CAstNode copy =
Ast.makeNode(
CAstNode.BLOCK_EXPR,
// assign lval to temp1 (where lval is a block that includes the prototype chain
// loop)
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new InternalCAstSymbol(temp1, JSAstTranslator.Any, true, false)),
lval),
// ? --MS
// rval,
// assign temp2 the new value to be assigned
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new InternalCAstSymbol(temp2, JSAstTranslator.Any, true, false)),
Ast.makeNode(
CAstNode.BINARY_EXPR,
op,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(temp1)),
rval)),
// write temp2 into the property
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.OBJECT_REF, ctxt.receiverTemp, ctxt.elementTemp),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(temp2))),
// final value depends on whether we had a pre op or post op
Ast.makeNode(
CAstNode.VAR,
Ast.makeConstant((kind == CAstNode.ASSIGN_PRE_OP) ? temp2 : temp1)));
nodeMap.put(Pair.make(root, context.key()), copy);
return copy;
} else {
CAstNode copy = Ast.makeNode(kind, lval, rval, op);
nodeMap.put(Pair.make(root, context.key()), copy);
return copy;
}
} else if (kind == CAstNode.ASSIGN) {
// use ASSIGN context for LHS so we don't translate property accesses there
CAstNode copy =
Ast.makeNode(
CAstNode.ASSIGN,
copyNodes(root.getChild(0), cfg, ASSIGN, nodeMap),
copyNodes(root.getChild(1), cfg, READ, nodeMap));
nodeMap.put(Pair.make(root, context.key()), copy);
return copy;
} else if (kind == CAstNode.BLOCK_EXPR) {
CAstNode children[] = new CAstNode[root.getChildCount()];
int last = (children.length - 1);
for (int i = 0; i < last; i++) {
children[i] = copyNodes(root.getChild(i), cfg, READ, nodeMap);
}
children[last] = copyNodes(root.getChild(last), cfg, context, nodeMap);
CAstNode copy = Ast.makeNode(CAstNode.BLOCK_EXPR, children);
nodeMap.put(Pair.make(root, context.key()), copy);
return copy;
} else if (root.getKind() == CAstNode.CONSTANT) {
CAstNode copy = Ast.makeConstant(root.getValue());
nodeMap.put(Pair.make(root, context.key()), copy);
return copy;
} else if (root.getKind() == CAstNode.OPERATOR) {
nodeMap.put(Pair.make(root, context.key()), root);
return root;
} else {
final List<CAstNode> children = copyChildrenArrayAndTargets(root, cfg, READ, nodeMap);
CAstNode copy = Ast.makeNode(kind, children);
nodeMap.put(Pair.make(root, context.key()), copy);
return copy;
}
}
}
| 13,618
| 35.317333
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/types/JavaScriptMethods.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.types;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
public class JavaScriptMethods extends AstMethodReference {
public static final String ctorAtomStr = "ctor";
public static final Atom ctorAtom = Atom.findOrCreateUnicodeAtom(ctorAtomStr);
public static final String ctorDescStr = "()LRoot;";
public static final Descriptor ctorDesc =
Descriptor.findOrCreateUTF8(JavaScriptLoader.JS, ctorDescStr);
public static final MethodReference ctorReference =
MethodReference.findOrCreate(JavaScriptTypes.CodeBody, ctorAtom, ctorDesc);
public static MethodReference makeCtorReference(TypeReference cls) {
return MethodReference.findOrCreate(cls, ctorAtom, ctorDesc);
}
public static final String dispatchAtomStr = "dispatch";
public static final Atom dispatchAtom = Atom.findOrCreateUnicodeAtom(dispatchAtomStr);
public static final String dispatchDescStr = "()LRoot;";
public static final Descriptor dispatchDesc =
Descriptor.findOrCreateUTF8(JavaScriptLoader.JS, dispatchDescStr);
public static final MethodReference dispatchReference =
MethodReference.findOrCreate(JavaScriptTypes.CodeBody, dispatchAtom, dispatchDesc);
}
| 1,801
| 41.904762
| 89
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/types/JavaScriptTypes.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.types;
import com.ibm.wala.cast.types.AstTypeReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeReference;
public class JavaScriptTypes extends AstTypeReference {
public static final String jsNameStr = "JavaScript";
public static final String jsLoaderNameStr = "JavaScriptLoader";
public static final Atom jsName = Atom.findOrCreateUnicodeAtom(jsNameStr);
public static final Atom jsLoaderName = Atom.findOrCreateUnicodeAtom(jsLoaderNameStr);
public static final ClassLoaderReference jsLoader =
new ClassLoaderReference(jsLoaderName, jsName, null);
public static final TypeReference Root = TypeReference.findOrCreate(jsLoader, rootTypeName);
public static final TypeReference Undefined = TypeReference.findOrCreate(jsLoader, "LUndefined");
public static final TypeReference Null = TypeReference.findOrCreate(jsLoader, "LNull");
public static final TypeReference Array = TypeReference.findOrCreate(jsLoader, "LArray");
public static final TypeReference Object = TypeReference.findOrCreate(jsLoader, "LObject");
public static final TypeReference CodeBody =
TypeReference.findOrCreate(jsLoader, functionTypeName);
public static final TypeReference Function = TypeReference.findOrCreate(jsLoader, "LFunction");
public static final TypeReference Script = TypeReference.findOrCreate(jsLoader, "LScript");
public static final TypeReference ReferenceError =
TypeReference.findOrCreate(jsLoader, "LReferenceError");
public static final TypeReference TypeError = TypeReference.findOrCreate(jsLoader, "LTypeError");
public static final TypeReference Primitives =
TypeReference.findOrCreate(jsLoader, "LPrimitives");
public static final TypeReference FakeRoot = TypeReference.findOrCreate(jsLoader, "LFakeRoot");
public static final TypeReference Boolean = TypeReference.findOrCreate(jsLoader, "LBoolean");
public static final TypeReference String = TypeReference.findOrCreate(jsLoader, "LString");
public static final TypeReference Number = TypeReference.findOrCreate(jsLoader, "LNumber");
public static final TypeReference Date = TypeReference.findOrCreate(jsLoader, "LDate");
public static final TypeReference RegExp = TypeReference.findOrCreate(jsLoader, "LRegExp");
public static final TypeReference BooleanObject =
TypeReference.findOrCreate(jsLoader, "LBooleanObject");
public static final TypeReference StringObject =
TypeReference.findOrCreate(jsLoader, "LStringObject");
public static final TypeReference NumberObject =
TypeReference.findOrCreate(jsLoader, "LNumberObject");
public static final TypeReference DateObject =
TypeReference.findOrCreate(jsLoader, "LDateObject");
public static final TypeReference RegExpObject =
TypeReference.findOrCreate(jsLoader, "LRegExpObject");
}
| 3,302
| 38.795181
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/util/CallGraph2JSON.java
|
/*
* Copyright (c) 2002 - 2012 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallString;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallStringContext;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallStringContextSelector;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.MapUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Utility class to serialize call graphs as JSON objects.
*
* <p>The serialised objects have the form
*
* <pre>
* {
* "<callsite1>": [ "<callee1>", "<callee2>", ... ],
* "<callsite2>": ...
* }
* </pre>
*
* where both call sites and callees are encoded as strings of the form
*
* <pre>
* "<filename>@<lineno>:<beginoff>-<endoff>"
* </pre>
*
* Here, {@code filename} is the name of the containing JavaScript file (not including its
* directory), and {@code lineno}, {@code beginoff} and {@code endoff} encode the source position of
* the call expression (for call sites) or the function declaration/expression (for callees) inside
* the file in terms of its starting line, its starting offset (in characters from the beginning of
* the file), and its end offset.
*
* @author mschaefer
*/
public class CallGraph2JSON {
/** ignore any calls to, from, or within WALA's harness containing models of natives methods */
private final boolean ignoreHarness;
/**
* if true, output JSON that keeps distinct method clones in the underlying call graph separate
*/
private final boolean exposeContexts;
public CallGraph2JSON() {
this(true);
}
public CallGraph2JSON(boolean ignoreHarness) {
this(ignoreHarness, false);
}
public CallGraph2JSON(boolean ignoreHarness, boolean exposeContexts) {
this.ignoreHarness = ignoreHarness;
this.exposeContexts = exposeContexts;
}
public String serialize(CallGraph cg) {
Map<String, Map<String, Set<String>>> edges = extractEdges(cg);
return toJSON(edges);
}
/**
* Extract the edges of the given callgraph as a map over strings that is easy to serialize. The
* map keys are locations of methods. The map values are themselves maps, from call site locations
* within a method to the (locations of) potential target methods for the call sites.
*/
public Map<String, Map<String, Set<String>>> extractEdges(CallGraph cg) {
Map<String, Map<String, Set<String>>> edges = HashMapFactory.make();
for (CGNode nd : cg) {
if (!isValidFunctionFromSource(nd.getMethod())) {
continue;
}
IMethod method = nd.getMethod();
if (ignoreHarness && isHarnessMethod(method)) {
continue;
}
Map<String, Set<String>> edgesForMethod =
MapUtil.findOrCreateMap(edges, getJSONRepForNode(nd.getMethod(), nd.getContext()));
for (CallSiteReference callsite : Iterator2Iterable.make(nd.iterateCallSites())) {
serializeCallSite(nd, callsite, cg.getPossibleTargets(nd, callsite), edgesForMethod);
}
}
return edges;
}
public void serializeCallSite(
CGNode nd, CallSiteReference callsite, Set<CGNode> targets, Map<String, Set<String>> edges) {
Set<String> targetNames =
MapUtil.findOrCreateSet(
edges, getJSONRepForCallSite(nd.getMethod(), nd.getContext(), callsite));
for (CGNode target : targets) {
IMethod trueTarget = getCallTargetMethod(target.getMethod());
if (trueTarget == null
|| !isValidFunctionFromSource(trueTarget)
|| (ignoreHarness && isHarnessMethod(trueTarget))) {
continue;
}
targetNames.add(getJSONRepForNode(trueTarget, target.getContext()));
}
}
private String getJSONRepForNode(IMethod method, Context context) {
String result;
if (isHarnessMethod(method) || isFunctionPrototypeCallOrApply(method)) {
// just use the method name; position is meaningless
result = getNativeMethodName(method);
} else {
AstMethod astMethod = (AstMethod) method;
result = astMethod.getSourcePosition().prettyPrint();
}
if (exposeContexts) {
result += getContextString(context);
}
return result;
}
private String getContextString(Context context) {
if (context.equals(Everywhere.EVERYWHERE)) {
return "";
} else if (context instanceof CallStringContext) {
CallStringContext cs = (CallStringContext) context;
CallString callString = (CallString) cs.get(CallStringContextSelector.CALL_STRING);
CallSiteReference csRef = callString.getCallSiteRefs()[0];
IMethod callerMethod = callString.getMethods()[0];
return " [" + getJSONRepForCallSite(callerMethod, Everywhere.EVERYWHERE, csRef) + "]";
} else {
throw new RuntimeException(context.toString());
}
}
private static String getNativeMethodName(IMethod method) {
String typeName = method.getDeclaringClass().getName().toString();
return typeName.substring(typeName.lastIndexOf('/') + 1) + " (Native)";
}
private String getJSONRepForCallSite(IMethod method, Context context, CallSiteReference site) {
String result;
if (isHarnessMethod(method) || isFunctionPrototypeCallOrApply(method)) {
result = getNativeMethodName(method);
} else {
AstMethod astMethod = (AstMethod) method;
result = astMethod.getSourcePosition(site.getProgramCounter()).prettyPrint();
}
if (exposeContexts) {
result += getContextString(context);
}
return result;
}
private static IMethod getCallTargetMethod(IMethod method) {
if (method.getName().equals(JavaScriptMethods.ctorAtom)) {
method = method.getDeclaringClass().getMethod(AstMethodReference.fnSelector);
if (method != null) return method;
}
return method;
}
private static boolean isValidFunctionFromSource(IMethod method) {
if (method instanceof AstMethod) {
String methodName = method.getDeclaringClass().getName().toString();
// exclude synthetic DOM modelling functions
if (methodName.contains("/make_node")) return false;
return method.getName().equals(AstMethodReference.fnAtom);
} else if (method.isWalaSynthetic()) {
if (isFunctionPrototypeCallOrApply(method)) {
return true;
}
}
return false;
}
private static boolean isFunctionPrototypeCallOrApply(IMethod method) {
String methodName = method.getDeclaringClass().getName().toString();
return methodName.equals("Lprologue.js/Function_prototype_call")
|| methodName.equals("Lprologue.js/Function_prototype_apply");
}
private static boolean isHarnessMethod(IMethod method) {
String methodName = method.getDeclaringClass().getName().toString();
for (String bootstrapFile : JavaScriptLoader.bootstrapFileNames) {
if (methodName.startsWith('L' + bootstrapFile + '/')) {
return true;
}
}
return false;
}
/**
* Converts a call graph map produced by {@link #extractEdges(CallGraph)} to JSON, eliding call
* sites with no targets.
*/
public static String toJSON(Map<String, Map<String, Set<String>>> map) {
// strip out call sites with no targets
Map<String, Map<String, Set<String>>> filtered = new HashMap<>();
for (Map.Entry<String, Map<String, Set<String>>> entry : map.entrySet()) {
String methodLoc = entry.getKey();
Map<String, Set<String>> callSites = entry.getValue();
Map<String, Set<String>> filteredSites =
callSites.entrySet().stream()
.filter(e -> !e.getValue().isEmpty())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (!filteredSites.isEmpty()) {
filtered.put(methodLoc, filteredSites);
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(filtered);
}
}
| 8,877
| 35.991667
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/util/FieldBasedCGUtil.java
|
/*
* Copyright (c) 2002 - 2012 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.util;
import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.js.callgraph.fieldbased.FieldBasedCallGraphBuilder;
import com.ibm.wala.cast.js.callgraph.fieldbased.FieldBasedCallGraphBuilder.CallGraphResult;
import com.ibm.wala.cast.js.callgraph.fieldbased.OptimisticCallgraphBuilder;
import com.ibm.wala.cast.js.callgraph.fieldbased.PessimisticCallGraphBuilder;
import com.ibm.wala.cast.js.callgraph.fieldbased.WorklistBasedOptimisticCallgraphBuilder;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.html.WebPageLoaderFactory;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.classLoader.SourceURLModule;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.NullProgressMonitor;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* Utility class for building call graphs.
*
* @author mschaefer
*/
public class FieldBasedCGUtil {
public enum BuilderType {
PESSIMISTIC {
@Override
protected FieldBasedCallGraphBuilder fieldBasedCallGraphBuilderFactory(
IClassHierarchy cha,
final JSAnalysisOptions makeOptions,
IAnalysisCacheView cache,
boolean supportFullPointerAnalysis) {
return new PessimisticCallGraphBuilder(cha, makeOptions, cache, supportFullPointerAnalysis);
}
},
OPTIMISTIC {
@Override
protected FieldBasedCallGraphBuilder fieldBasedCallGraphBuilderFactory(
IClassHierarchy cha,
JSAnalysisOptions makeOptions,
IAnalysisCacheView cache,
boolean supportFullPointerAnalysis) {
return new OptimisticCallgraphBuilder(cha, makeOptions, cache, supportFullPointerAnalysis);
}
},
OPTIMISTIC_WORKLIST {
@Override
protected FieldBasedCallGraphBuilder fieldBasedCallGraphBuilderFactory(
IClassHierarchy cha,
JSAnalysisOptions makeOptions,
IAnalysisCacheView cache,
boolean supportFullPointerAnalysis) {
return new WorklistBasedOptimisticCallgraphBuilder(
cha, makeOptions, cache, supportFullPointerAnalysis, -1);
}
};
protected abstract FieldBasedCallGraphBuilder fieldBasedCallGraphBuilderFactory(
IClassHierarchy cha,
JSAnalysisOptions makeOptions,
IAnalysisCacheView cache,
boolean supportFullPointerAnalysis);
}
private final JavaScriptTranslatorFactory translatorFactory;
public FieldBasedCGUtil(JavaScriptTranslatorFactory translatorFactory) {
this.translatorFactory = translatorFactory;
}
public CallGraphResult buildCG(
URL url,
BuilderType builderType,
boolean supportFullPointerAnalysis,
Supplier<JSSourceExtractor> fExtractor)
throws WalaException, CancelException {
return buildCG(
url, builderType, new NullProgressMonitor(), supportFullPointerAnalysis, fExtractor);
}
public CallGraphResult buildCG(
URL url,
BuilderType builderType,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis,
Supplier<JSSourceExtractor> fExtractor)
throws WalaException, CancelException {
if (url.getFile().endsWith(".js")) {
return buildScriptCG(url, builderType, monitor, supportFullPointerAnalysis);
} else {
return buildPageCG(url, builderType, monitor, supportFullPointerAnalysis, fExtractor);
}
}
public CallGraphResult buildScriptCG(
URL url,
BuilderType builderType,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis)
throws WalaException, CancelException {
JavaScriptLoaderFactory loaders = new JavaScriptLoaderFactory(translatorFactory);
Module[] scripts =
new Module[] {new SourceURLModule(url), JSCallGraphUtil.getPrologueFile("prologue.js")};
return buildCG(loaders, scripts, builderType, monitor, supportFullPointerAnalysis);
}
/**
* Construct a field-based call graph using all the {@code .js} files appearing in scriptDir or
* any of its sub-directories
*/
public CallGraphResult buildScriptDirCG(
Path scriptDir,
BuilderType builderType,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis)
throws WalaException, CancelException, IOException {
JavaScriptLoaderFactory loaders = new JavaScriptLoaderFactory(translatorFactory);
List<Module> scripts = findScriptsInDir(scriptDir);
return buildCG(
loaders, scripts.toArray(new Module[0]), builderType, monitor, supportFullPointerAnalysis);
}
/**
* Construct a bounded field-based call graph using all the {@code .js} files appearing in
* scriptDir or any of its sub-directories
*/
public CallGraphResult buildScriptDirBoundedCG(
Path scriptDir, IProgressMonitor monitor, boolean supportFullPointerAnalysis, Integer bound)
throws WalaException, CancelException, IOException {
JavaScriptLoaderFactory loaders = new JavaScriptLoaderFactory(translatorFactory);
List<Module> scripts = findScriptsInDir(scriptDir);
return buildBoundedCG(
loaders, scripts.toArray(new Module[0]), monitor, supportFullPointerAnalysis, bound);
}
public List<Module> findScriptsInDir(Path scriptDir) throws IOException {
final List<Path> jsFiles;
try (var walk = Files.walk(scriptDir)) {
jsFiles =
walk.filter(p -> p.toString().toLowerCase().endsWith(".js")).collect(Collectors.toList());
}
List<Module> scripts = new ArrayList<>();
// we can't do this loop as a map() operation on the previous stream because toURL() throws
// a checked exception
for (Path p : jsFiles) {
scripts.add(new SourceURLModule(p.toUri().toURL()));
}
scripts.add(JSCallGraphUtil.getPrologueFile("prologue.js"));
return scripts;
}
public CallGraphResult buildTestCG(
String dir,
String name,
BuilderType builderType,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis)
throws IOException, WalaException, CancelException {
JavaScriptLoaderFactory loaders = new JavaScriptLoaderFactory(translatorFactory);
Module[] scripts = JSCallGraphBuilderUtil.makeSourceModules(dir, name);
return buildCG(loaders, scripts, builderType, monitor, supportFullPointerAnalysis);
}
public CallGraphResult buildPageCG(
URL url,
BuilderType builderType,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis,
Supplier<JSSourceExtractor> fExtractor)
throws WalaException, CancelException {
JavaScriptLoaderFactory loaders = new WebPageLoaderFactory(translatorFactory);
SourceModule[] scripts = JSCallGraphBuilderUtil.makeHtmlScope(url, loaders, fExtractor);
return buildCG(loaders, scripts, builderType, monitor, supportFullPointerAnalysis);
}
public CallGraphResult buildCG(
JavaScriptLoaderFactory loaders,
Module[] scripts,
BuilderType builderType,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis)
throws WalaException, CancelException {
CAstAnalysisScope scope =
new CAstAnalysisScope(scripts, loaders, Collections.singleton(JavaScriptLoader.JS));
IClassHierarchy cha = ClassHierarchyFactory.make(scope, loaders, JavaScriptLoader.JS);
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
Iterable<Entrypoint> roots = JSCallGraphUtil.makeScriptRoots(cha);
IAnalysisCacheView cache = new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory());
final FieldBasedCallGraphBuilder builder =
builderType.fieldBasedCallGraphBuilderFactory(
cha, JSCallGraphUtil.makeOptions(scope, cha, roots), cache, supportFullPointerAnalysis);
return builder.buildCallGraph(roots, monitor);
}
public CallGraphResult buildBoundedCG(
JavaScriptLoaderFactory loaders,
Module[] scripts,
IProgressMonitor monitor,
boolean supportFullPointerAnalysis,
Integer bound)
throws WalaException, CancelException {
CAstAnalysisScope scope =
new CAstAnalysisScope(scripts, loaders, Collections.singleton(JavaScriptLoader.JS));
IClassHierarchy cha = ClassHierarchyFactory.make(scope, loaders, JavaScriptLoader.JS);
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
Iterable<Entrypoint> roots = JSCallGraphUtil.makeScriptRoots(cha);
IAnalysisCacheView cache = new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory());
final FieldBasedCallGraphBuilder builder =
new WorklistBasedOptimisticCallgraphBuilder(
cha,
JSCallGraphUtil.makeOptions(scope, cha, roots),
cache,
supportFullPointerAnalysis,
bound);
return builder.buildCallGraph(roots, monitor);
}
/*
private JavaScriptLoaderFactory makeLoaderFactory(URL url) {
return url.getFile().endsWith(".js") ? new JavaScriptLoaderFactory(translatorFactory) : new WebPageLoaderFactory(translatorFactory);
}
*/
@SuppressWarnings("unused")
private static void compareCGs(Map<String, Set<String>> cg1, Map<String, Set<String>> cg2) {
boolean diff = false;
for (Map.Entry<String, Set<String>> entry : cg1.entrySet()) {
final String key = entry.getKey();
Set<String> targets1 = entry.getValue(), targets2 = cg2.get(key);
if (targets2 == null) {
diff = true;
System.err.println("CG2 doesn't have call site" + key);
} else {
for (String target : targets1)
if (!targets2.contains(target)) {
diff = true;
System.err.println("CG2 doesn't have edge " + key + " -> " + target);
}
for (String target : targets2)
if (!targets1.contains(target)) {
diff = true;
System.err.println("CG1 doesn't have edge " + key + " -> " + target);
}
}
}
for (String key : cg2.keySet()) {
if (!cg1.containsKey(key)) {
diff = true;
System.err.println("CG1 doesn't have call site " + key);
}
}
if (!diff) System.err.println("call graphs are identical");
}
}
| 11,465
| 38.67474
| 135
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/util/JSCallGraphBuilderUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.util;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.html.WebPageLoaderFactory;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSZeroOrOneXCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.PropertyNameContextSelector;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.CorrelatedPairExtractorFactory;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.loader.CAstAbstractLoader;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.classLoader.SourceURLModule;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Set;
import java.util.function.Supplier;
/** TODO this class is a mess. rewrite. */
public class JSCallGraphBuilderUtil extends com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil {
public enum CGBuilderType {
ZERO_ONE_CFA(false, true, true),
ZERO_ONE_CFA_WITHOUT_CORRELATION_TRACKING(false, true, false),
ZERO_ONE_CFA_NO_CALL_APPLY(false, false, true),
ONE_CFA(true, true, true);
private final boolean useOneCFA;
private final boolean handleCallApply;
private final boolean extractCorrelatedPairs;
CGBuilderType(boolean useOneCFA, boolean handleCallApply, boolean extractCorrelatedPairs) {
this.useOneCFA = useOneCFA;
this.handleCallApply = handleCallApply;
this.extractCorrelatedPairs = extractCorrelatedPairs;
}
public boolean useOneCFA() {
return useOneCFA;
}
public boolean handleCallApply() {
return handleCallApply;
}
public boolean extractCorrelatedPairs() {
return extractCorrelatedPairs;
}
}
/**
* create a CG builder for script. Note that the script at dir/name is loaded via the classloader,
* not from the filesystem.
*/
public static JSCFABuilder makeScriptCGBuilder(
String dir, String name, CGBuilderType builderType, ClassLoader loader)
throws IOException, WalaException {
URL script = getURLforFile(dir, name, loader);
CAstRewriterFactory<?, ?> preprocessor =
builderType.extractCorrelatedPairs
? new CorrelatedPairExtractorFactory(translatorFactory, script)
: null;
JavaScriptLoaderFactory loaders = JSCallGraphUtil.makeLoaders(preprocessor);
AnalysisScope scope = makeScriptScope(dir, name, loaders, loader);
return makeCG(loaders, scope, builderType, AstIRFactory.makeDefaultFactory());
}
public static URL getURLforFile(String dir, String name, ClassLoader loader) throws IOException {
File f = null;
FileProvider provider = new FileProvider();
if (dir.startsWith(File.separator)) {
f = new File(dir + File.separator + name);
} else {
try {
f = provider.getFile(dir + File.separator + name, loader);
} catch (FileNotFoundException e) {
// I guess we need to do this on Windows sometimes? --MS
// if this fails, we won't catch the exception
}
}
return f.toURI().toURL();
}
public static AnalysisScope makeScriptScope(
String dir, String name, JavaScriptLoaderFactory loaders, ClassLoader loader)
throws IOException {
return makeScope(makeSourceModules(dir, name, loader), loaders, JavaScriptLoader.JS);
}
public static AnalysisScope makeScriptScope(
String dir, String name, JavaScriptLoaderFactory loaders) throws IOException {
return makeScope(
makeSourceModules(dir, name, JSCallGraphBuilderUtil.class.getClassLoader()),
loaders,
JavaScriptLoader.JS);
}
public static Module[] makeSourceModules(String dir, String name) throws IOException {
return makeSourceModules(dir, name, JSCallGraphBuilderUtil.class.getClassLoader());
}
public static Module[] makeSourceModules(String dir, String name, ClassLoader loader)
throws IOException {
URL script = getURLforFile(dir, name, loader);
Module[] modules =
new Module[] {
(script.openConnection() instanceof JarURLConnection)
? new SourceURLModule(script)
: makeSourceModule(script, dir, name),
getPrologueFile("prologue.js")
};
return modules;
}
public static JSCFABuilder makeScriptCGBuilder(String dir, String name, ClassLoader loader)
throws IOException, WalaException {
return makeScriptCGBuilder(dir, name, CGBuilderType.ZERO_ONE_CFA, loader);
}
public static JSCFABuilder makeScriptCGBuilder(String dir, String name)
throws IOException, WalaException {
return makeScriptCGBuilder(
dir, name, CGBuilderType.ZERO_ONE_CFA, JSCallGraphBuilderUtil.class.getClassLoader());
}
public static CallGraph makeScriptCG(String dir, String name)
throws IOException, IllegalArgumentException, CancelException, WalaException {
return makeScriptCG(
dir, name, CGBuilderType.ZERO_ONE_CFA, JSCallGraphBuilderUtil.class.getClassLoader());
}
public static CallGraph makeScriptCG(String dir, String name, ClassLoader loader)
throws IOException, IllegalArgumentException, CancelException, WalaException {
return makeScriptCG(dir, name, CGBuilderType.ZERO_ONE_CFA, loader);
}
public static JSCFABuilder makeScriptCGBuilderWithoutCorrelationTracking(
String dir, String name, ClassLoader loader) throws IOException, WalaException {
return makeScriptCGBuilder(
dir, name, CGBuilderType.ZERO_ONE_CFA_WITHOUT_CORRELATION_TRACKING, loader);
}
public static JSCFABuilder makeScriptCGBuilderWithoutCorrelationTracking(String dir, String name)
throws IOException, WalaException {
return makeScriptCGBuilder(
dir,
name,
CGBuilderType.ZERO_ONE_CFA_WITHOUT_CORRELATION_TRACKING,
JSCallGraphBuilderUtil.class.getClassLoader());
}
public static CallGraph makeScriptCG(
String dir, String name, CGBuilderType builderType, ClassLoader loader)
throws IOException, IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder b = makeScriptCGBuilder(dir, name, builderType, loader);
CallGraph CG = b.makeCallGraph(b.getOptions());
// dumpCG(b.getPointerAnalysis(), CG);
return CG;
}
public static CallGraph makeScriptCG(
SourceModule[] scripts, CGBuilderType builderType, IRFactory<IMethod> irFactory)
throws IllegalArgumentException, CancelException, WalaException {
CAstRewriterFactory<?, ?> preprocessor =
builderType.extractCorrelatedPairs
? new CorrelatedPairExtractorFactory(translatorFactory, scripts)
: null;
PropagationCallGraphBuilder b =
makeCGBuilder(makeLoaders(preprocessor), scripts, builderType, irFactory);
CallGraph CG = b.makeCallGraph(b.getOptions());
// dumpCG(b.getPointerAnalysis(), CG);
return CG;
}
public static JSCFABuilder makeHTMLCGBuilder(URL url, Supplier<JSSourceExtractor> fExtractor)
throws WalaException {
return makeHTMLCGBuilder(url, CGBuilderType.ZERO_ONE_CFA, fExtractor);
}
public static JSCFABuilder makeHTMLCGBuilder(
URL url, Supplier<JSSourceExtractor> fExtractor, Reader r) throws WalaException {
return makeHTMLCGBuilder(url, CGBuilderType.ZERO_ONE_CFA, fExtractor, r);
}
public static JSCFABuilder makeHTMLCGBuilder(
URL url, CGBuilderType builderType, Supplier<JSSourceExtractor> fExtractor)
throws WalaException {
try (Reader r = WebUtil.getStream(url)) {
return makeHTMLCGBuilder(url, builderType, fExtractor, r);
} catch (IOException e) {
throw new WalaException("failed to read " + url, e);
}
}
public static JSCFABuilder makeHTMLCGBuilder(
URL url, CGBuilderType builderType, Supplier<JSSourceExtractor> fExtractor, Reader r)
throws WalaException {
IRFactory<IMethod> irFactory = AstIRFactory.makeDefaultFactory();
CAstRewriterFactory<?, ?> preprocessor =
builderType.extractCorrelatedPairs
? new CorrelatedPairExtractorFactory(translatorFactory, url)
: null;
JavaScriptLoaderFactory loaders = new WebPageLoaderFactory(translatorFactory, preprocessor);
SourceModule[] scriptsArray = makeHtmlScope(url, loaders, fExtractor, r);
JSCFABuilder builder = makeCGBuilder(loaders, scriptsArray, builderType, irFactory);
if (builderType.extractCorrelatedPairs)
builder.setContextSelector(
new PropertyNameContextSelector(
builder.getAnalysisCache(), 2, builder.getContextSelector()));
builder.setBaseURL(url);
return builder;
}
public static SourceModule[] makeHtmlScope(
URL url, JavaScriptLoaderFactory loaders, Supplier<JSSourceExtractor> fExtractor) {
try (Reader r = WebUtil.getStream(url)) {
return makeHtmlScope(url, loaders, fExtractor, r);
} catch (IOException e) {
assert false : e;
return null;
}
}
public static SourceModule[] makeHtmlScope(
URL url, JavaScriptLoaderFactory loaders, Supplier<JSSourceExtractor> fExtractor, Reader r) {
Set<Module> scripts = HashSetFactory.make();
JavaScriptLoader.addBootstrapFile(WebUtil.preamble);
scripts.add(getPrologueFile("prologue.js"));
scripts.add(getPrologueFile("preamble.js"));
try {
scripts.addAll(WebUtil.extractScriptFromHTML(url, fExtractor, r).fst);
} catch (Error e) {
SourceModule dummy = new SourceURLModule(url);
scripts.add(dummy);
((CAstAbstractLoader) loaders.getTheLoader()).addMessages(dummy, e.warning);
}
SourceModule[] scriptsArray = scripts.toArray(new SourceModule[0]);
return scriptsArray;
}
public static CallGraph makeHTMLCG(URL url, Supplier<JSSourceExtractor> fExtractor)
throws IllegalArgumentException, CancelException, WalaException {
SSAPropagationCallGraphBuilder b = makeHTMLCGBuilder(url, fExtractor);
CallGraph CG = b.makeCallGraph(b.getOptions());
dumpCG(b.getCFAContextInterpreter(), b.getPointerAnalysis(), CG);
return CG;
}
public static CallGraph makeHTMLCG(
URL url, CGBuilderType builderType, Supplier<JSSourceExtractor> fExtractor)
throws IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder b = makeHTMLCGBuilder(url, builderType, fExtractor);
CallGraph CG = b.makeCallGraph(b.getOptions());
return CG;
}
public static JSCFABuilder makeCGBuilder(
JavaScriptLoaderFactory loaders,
Module[] scripts,
CGBuilderType builderType,
IRFactory<IMethod> irFactory)
throws WalaException {
AnalysisScope scope = makeScope(scripts, loaders, JavaScriptLoader.JS);
return makeCG(loaders, scope, builderType, irFactory);
}
protected static JSCFABuilder makeCG(
JavaScriptLoaderFactory loaders,
AnalysisScope scope,
CGBuilderType builderType,
IRFactory<IMethod> irFactory)
throws WalaException {
try {
IClassHierarchy cha = makeHierarchy(scope, loaders);
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
Iterable<Entrypoint> roots = makeScriptRoots(cha);
JSAnalysisOptions options = makeOptions(scope, cha, roots);
options.setHandleCallApply(builderType.handleCallApply());
IAnalysisCacheView cache = makeCache(irFactory);
JSCFABuilder builder =
new JSZeroOrOneXCFABuilder(
cha,
options,
cache,
null,
null,
ZeroXInstanceKeys.ALLOCATIONS,
builderType.useOneCFA());
if (builderType.extractCorrelatedPairs())
builder.setContextSelector(
new PropertyNameContextSelector(
builder.getAnalysisCache(), 2, builder.getContextSelector()));
return builder;
} catch (ClassHierarchyException e) {
throw new RuntimeException("internal error building class hierarchy", e);
}
}
public static CallGraph makeHTMLCG(URL url, CGBuilderType zeroOneCfaNoCallApply)
throws IllegalArgumentException, CancelException, WalaException {
return makeHTMLCG(url, zeroOneCfaNoCallApply, DefaultSourceExtractor.factory);
}
public static CallGraph makeHTMLCG(URL url)
throws IllegalArgumentException, CancelException, WalaException {
return makeHTMLCG(url, DefaultSourceExtractor.factory);
}
public static JSCFABuilder makeHTMLCGBuilder(URL url, CGBuilderType type, Reader r)
throws WalaException {
return makeHTMLCGBuilder(url, type, DefaultSourceExtractor.factory, r);
}
public static JSCFABuilder makeHTMLCGBuilder(URL url) throws WalaException {
return makeHTMLCGBuilder(url, DefaultSourceExtractor.factory);
}
}
| 14,443
| 38.681319
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/util/Util.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.util;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
public class Util {
public static IntSet getArgumentsArrayVns(IR ir, final DefUse du) {
int originalArgsVn = getArgumentsArrayVn(ir);
final MutableIntSet result = IntSetUtil.make();
if (originalArgsVn == -1) {
return result;
}
result.add(originalArgsVn);
int size;
do {
size = result.size();
result.foreach(
vn -> {
for (SSAInstruction inst : Iterator2Iterable.make(du.getUses(vn))) {
if (inst instanceof PrototypeLookup || inst instanceof SSAPhiInstruction) {
result.add(inst.getDef());
}
}
});
} while (size != result.size());
return result;
}
public static int getArgumentsArrayVn(IR ir) {
for (int i = 0; i < ir.getInstructions().length; i++) {
SSAInstruction inst = ir.getInstructions()[i];
if (inst != null) {
for (int v = 0; v < inst.getNumberOfUses(); v++) {
String[] names = ir.getLocalNames(i, inst.getUse(v));
if (names != null && names.length == 1 && "arguments".equals(names[0])) {
return inst.getUse(v);
}
}
}
}
return -1;
}
}
| 1,968
| 29.292308
| 89
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/vis/JsPaPanel.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.vis;
import com.ibm.wala.analysis.pointers.HeapGraph;
import com.ibm.wala.cast.ipa.callgraph.AstGlobalPointerKey;
import com.ibm.wala.cast.ipa.callgraph.ObjectPropertyCatalogKey;
import com.ibm.wala.core.viz.viewer.PaPanel;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.ArrayList;
import java.util.List;
/**
* Augments the PaPanel with: 1) global pointer keys at the root level. 2) property catalog key for
* instance keys.
*
* @author yinnonh
*/
public class JsPaPanel extends PaPanel {
private static final long serialVersionUID = 1L;
private final MutableMapping<List<ObjectPropertyCatalogKey>>
instanceKeyIdToObjectPropertyCatalogKey =
MutableMapping.<List<ObjectPropertyCatalogKey>>make();
private final List<AstGlobalPointerKey> globalsPointerKeys = new ArrayList<>();
public JsPaPanel(CallGraph cg, PointerAnalysis<InstanceKey> pa) {
super(cg, pa);
initDataStructures(pa);
}
private void initDataStructures(PointerAnalysis<InstanceKey> pa) {
HeapGraph<InstanceKey> heapGraph = pa.getHeapGraph();
OrdinalSetMapping<InstanceKey> instanceKeyMapping = pa.getInstanceKeyMapping();
for (Object n : heapGraph) {
if (heapGraph.getPredNodeCount(n) == 0) {
if (n instanceof PointerKey) {
if (n instanceof ObjectPropertyCatalogKey) {
ObjectPropertyCatalogKey opck = (ObjectPropertyCatalogKey) n;
InstanceKey instanceKey = opck.getObject();
int instanceKeyId = instanceKeyMapping.getMappedIndex(instanceKey);
mapUsingMutableMapping(instanceKeyIdToObjectPropertyCatalogKey, instanceKeyId, opck);
} else if (n instanceof AstGlobalPointerKey) {
globalsPointerKeys.add((AstGlobalPointerKey) n);
}
} else {
System.err.println("Non Pointer key root: " + n);
}
}
}
}
@Override
protected List<PointerKey> getPointerKeysUnderInstanceKey(InstanceKey ik) {
List<PointerKey> ret = new ArrayList<>(super.getPointerKeysUnderInstanceKey(ik));
int ikIndex = pa.getInstanceKeyMapping().getMappedIndex(ik);
ret.addAll(nonNullList(instanceKeyIdToObjectPropertyCatalogKey.getMappedObject(ikIndex)));
return ret;
}
private final String cgNodesRoot = "CGNodes";
private final String globalsRoot = "Globals";
@Override
protected List<Object> getRootNodes() {
List<Object> ret = new ArrayList<>(2);
ret.add(cgNodesRoot);
ret.add(globalsRoot);
return ret;
}
@Override
protected List<Object> getChildrenFor(Object node) {
List<Object> ret = new ArrayList<>();
if (node == cgNodesRoot) {
for (int nodeId = 0; nodeId < cg.getNumberOfNodes(); nodeId++) {
CGNode cgNode = cg.getNode(nodeId);
ret.add(cgNode);
}
} else if (node == globalsRoot) {
ret.addAll(globalsPointerKeys);
} else {
ret.addAll(super.getChildrenFor(node));
}
return ret;
}
}
| 3,666
| 34.601942
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/vis/JsViewer.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.vis;
import com.ibm.wala.core.viz.viewer.PaPanel;
import com.ibm.wala.core.viz.viewer.WalaViewer;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
public class JsViewer extends WalaViewer {
private static final long serialVersionUID = 1L;
public JsViewer(CallGraph cg, PointerAnalysis<InstanceKey> pa) {
super(cg, pa);
}
@Override
protected PaPanel createPaPanel(CallGraph cg, PointerAnalysis<InstanceKey> pa) {
return new JsPaPanel(cg, pa);
}
}
| 986
| 29.84375
| 82
|
java
|
WALA
|
WALA-master/cast/js/src/test/java/com/ibm/wala/cast/js/test/TestWebUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.MappedSourceModule;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.core.tests.util.WalaTestCase;
import java.net.URL;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
public class TestWebUtil extends WalaTestCase {
@Test
public void testAjaxslt() throws Error {
URL url = getClass().getClassLoader().getResource("ajaxslt/test/xslt.html");
Assert.assertNotNull(url);
Set<MappedSourceModule> mod =
WebUtil.extractScriptFromHTML(url, DefaultSourceExtractor.factory).fst;
Assert.assertNotNull(mod);
}
@Test
public void testAjaxpath() throws Error {
URL url = getClass().getClassLoader().getResource("ajaxslt/test/xpath.html");
Assert.assertNotNull(url);
Set<MappedSourceModule> mod =
WebUtil.extractScriptFromHTML(url, DefaultSourceExtractor.factory).fst;
Assert.assertNotNull(mod);
}
}
| 1,446
| 32.651163
| 81
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/CAstDumper.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import static com.ibm.wala.cast.tree.CAstNode.ASSIGN;
import static com.ibm.wala.cast.tree.CAstNode.BLOCK_EXPR;
import static com.ibm.wala.cast.tree.CAstNode.BLOCK_STMT;
import static com.ibm.wala.cast.tree.CAstNode.EMPTY;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.NodeLabeller;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.util.CAstPrinter;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
/**
* A class for dumping a textual representation of a CAst syntax tree.
*
* <p>Similar to {@link CAstPrinter}, but additionally prints control flow information.
*
* <p>It also suppresses certain kinds of spurious nodes such as empty statements within a block or
* block expressions with a single child, which are simply artifacts of the translation process.
* This is not nice, but needed for our tests.
*
* @author mschaefer
*/
public class CAstDumper {
private static final boolean NORMALISE = false;
private final NodeLabeller labeller;
public CAstDumper() {
labeller = new NodeLabeller();
}
public CAstDumper(NodeLabeller labeller) {
this.labeller = labeller;
}
private static String indent(int indent) {
return " ".repeat(indent);
}
public String dump(CAstEntity entity) {
StringBuilder buf = new StringBuilder();
dump(entity, 0, buf);
return buf.toString();
}
private void dump(CAstEntity entity, int indent, StringBuilder buf) {
Collection<CAstEntity> scopedEntities = Collections.emptySet();
if (entity.getKind() == CAstEntity.SCRIPT_ENTITY) {
buf.append(indent(indent)).append(entity.getName()).append(":\n");
scopedEntities = dumpScopedEntities(entity, indent + 2, buf);
dump(entity.getAST(), indent, buf, entity.getControlFlow());
} else if (entity.getKind() == CAstEntity.FUNCTION_ENTITY) {
buf.append(indent(indent)).append("function ").append(entity.getName()).append('(');
for (int i = 0; i < entity.getArgumentCount(); ++i) {
if (i > 0) buf.append(", ");
buf.append(entity.getArgumentNames()[i]);
}
buf.append(") {\n");
scopedEntities = dumpScopedEntities(entity, indent + 2, buf);
dump(entity.getAST(), indent + 2, buf, entity.getControlFlow());
buf.append(indent(indent)).append("}\n\n");
} else {
throw new Error("Unknown entity kind " + entity.getKind());
}
for (CAstEntity scopedEntity : scopedEntities) dump(scopedEntity, indent, buf);
}
private Collection<CAstEntity> dumpScopedEntities(
CAstEntity entity, int indent, StringBuilder buf) {
ArrayList<CAstEntity> scopedEntities = new ArrayList<>();
Map<CAstEntity, CAstNode> m = HashMapFactory.make();
for (Entry<CAstNode, Collection<CAstEntity>> e : entity.getAllScopedEntities().entrySet())
for (CAstEntity scopedEntity : e.getValue()) {
scopedEntities.add(scopedEntity);
m.put(scopedEntity, e.getKey());
}
scopedEntities.sort(Comparator.comparing(CAstEntity::getName));
buf.append(indent(indent)).append("> ");
boolean first = true;
for (CAstEntity scopedEntity : scopedEntities) {
if (first) first = false;
else buf.append(", ");
buf.append(scopedEntity.getName()).append('@').append(labeller.addNode(m.get(scopedEntity)));
}
buf.append('\n');
return scopedEntities;
}
private boolean isTrivial(CAstNode node) {
switch (node.getKind()) {
case ASSIGN:
return node.getChild(0).getKind() == CAstNode.VAR && isTrivial(node.getChild(1));
case EMPTY:
return true;
case BLOCK_EXPR:
case BLOCK_STMT:
return getNonTrivialChildCount(node) == 0;
default:
return false;
}
}
private int getNonTrivialChildCount(CAstNode node) {
int cnt = 0;
for (CAstNode child : node.getChildren()) if (!isTrivial(child)) ++cnt;
return cnt;
}
@SuppressWarnings("unused")
private void dump(CAstNode node, int indent, StringBuilder buf, CAstControlFlowMap cfg) {
if (isTrivial(node)) return;
// normalise away single-child block expressions
if (NORMALISE && node.getKind() == CAstNode.BLOCK_EXPR && getNonTrivialChildCount(node) == 1) {
for (CAstNode child : node.getChildren())
if (!isTrivial(child)) dump(child, indent, buf, cfg);
} else {
buf.append(indent(indent)).append(labeller.addNode(node)).append(": ");
if (node.getKind() == CAstNode.CONSTANT) {
if (node.getValue() == null) buf.append("null");
else if (node.getValue() instanceof Integer) buf.append(String.valueOf(node.getValue()));
else buf.append("\"").append(node.getValue()).append("\"");
} else if (node.getKind() == CAstNode.OPERATOR) {
buf.append(node.getValue().toString());
} else {
buf.append(CAstPrinter.kindAsString(node.getKind()));
}
Collection<Object> labels = cfg.getTargetLabels(node);
if (!labels.isEmpty()) {
buf.append(" [");
boolean first = true;
for (Object label : labels) {
CAstNode target = cfg.getTarget(node, label);
if (first) {
first = false;
} else {
buf.append(", ");
}
if (label instanceof CAstNode)
buf.append("CAstNode@").append(labeller.addNode((CAstNode) label)).append(": ");
else buf.append(label).append(": ");
buf.append(labeller.addNode(target));
}
buf.append(']');
}
buf.append('\n');
for (CAstNode child : node.getChildren()) {
// omit empty statements in a block
if (NORMALISE
&& node.getKind() == CAstNode.BLOCK_STMT
&& child != null
&& child.getKind() == CAstNode.EMPTY) continue;
dump(child, indent + 2, buf, cfg);
}
}
}
}
| 6,496
| 35.706215
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/ExtractingToPredictableFileNames.java
|
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.html.DomLessSourceExtractor;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Temporarily configures JavaScript source extractors to use predictable HTML file names and
* locations.
*
* <p>Predictable names are good for use in automated regression tests that expect to match specific
* file names in analyses results. This class implements {@link AutoCloseable}, making it suitable
* for use in {@code try}-with-resources statements: the original settings for HTML file names and
* locations will be restored when the {@code try}-with-resources statement concludes.
*/
public class ExtractingToPredictableFileNames implements AutoCloseable {
/** Original {@link JSSourceExtractor#USE_TEMP_NAME} setting to be restored later */
private final boolean savedUseTempName = JSSourceExtractor.USE_TEMP_NAME;
/** Original {@link DomLessSourceExtractor#OUTPUT_FILE_DIRECTORY} setting to be restored later */
private final Path savedOutputFileDirectory = DomLessSourceExtractor.OUTPUT_FILE_DIRECTORY;
/**
* Reconfigures {@link JSSourceExtractor} to not use temporary file names, and reconfigures {@link
* DomLessSourceExtractor} to place HTML files in the {@code build} subdirectory of the current
* working directory.
*/
public ExtractingToPredictableFileNames() {
configure(false, Paths.get("build"));
}
/**
* Restores {@link JSSourceExtractor} and {@link DomLessSourceExtractor} settings for generated
* HTML file names to those that were in place when this instance was created.
*/
@Override
public void close() {
configure(savedUseTempName, savedOutputFileDirectory);
}
/**
* Changes the current {@link JSSourceExtractor#USE_TEMP_NAME} and {@link
* DomLessSourceExtractor#OUTPUT_FILE_DIRECTORY}.
*
* @param useTempName the new value for {@link JSSourceExtractor#USE_TEMP_NAME}
* @param outputFileDirectory the new value for {@link
* DomLessSourceExtractor#OUTPUT_FILE_DIRECTORY}
*/
private static void configure(boolean useTempName, Path outputFileDirectory) {
JSSourceExtractor.USE_TEMP_NAME = useTempName;
DomLessSourceExtractor.OUTPUT_FILE_DIRECTORY = outputFileDirectory;
}
}
| 2,307
| 40.214286
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestAjaxsltCallGraphShape.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import static org.junit.Assert.assertNotNull;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil.CGBuilderType;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.net.URL;
import org.junit.Test;
public abstract class TestAjaxsltCallGraphShape extends TestJSCallGraphShape {
private static final Object[][] assertionsForAjaxslt = new Object[][] {};
@Test
public void testAjaxslt() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("ajaxslt/test/xslt.html");
assertNotNull("cannot find resource \"ajaxslt/test/xslt.html\"", url);
// need to turn off call/apply handling for this to scale; alternatively use 1-CFA
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url, CGBuilderType.ZERO_ONE_CFA_NO_CALL_APPLY);
verifyGraphAssertions(CG, assertionsForAjaxslt);
}
private static final Object[][] assertionsForAjaxpath = new Object[][] {};
@Test
public void testAjaxpath() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("ajaxslt/test/xpath.html");
assertNotNull("cannot find resource \"ajaxslt/test/xpath.html\"", url);
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForAjaxpath);
}
}
| 1,878
| 38.978723
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestArgumentSensitivity.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.ArgumentSpecialization;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSZeroOrOneXCFABuilder;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import org.junit.Test;
public abstract class TestArgumentSensitivity extends TestJSCallGraphShape {
protected static final Object[][] assertionsForArgs =
new Object[][] {
new Object[] {ROOT, new String[] {"args.js"}},
new Object[] {"args.js", new String[] {"args.js/a"}},
new Object[] {"args.js/a", new String[] {"args.js/x"}},
new Object[] {"args.js/a", new String[] {"args.js/y", "args.js/z", "!args.js/wrong"}}
};
@Test
public void testArgs()
throws IOException, IllegalArgumentException, CancelException, ClassHierarchyException,
WalaException {
JavaScriptLoaderFactory loaders = JSCallGraphUtil.makeLoaders(null);
AnalysisScope scope = JSCallGraphBuilderUtil.makeScriptScope("tests", "args.js", loaders);
IClassHierarchy cha = JSCallGraphUtil.makeHierarchy(scope, loaders);
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
Iterable<Entrypoint> roots = JSCallGraphUtil.makeScriptRoots(cha);
JSAnalysisOptions options = JSCallGraphUtil.makeOptions(scope, cha, roots);
IAnalysisCacheView cache =
CAstCallGraphUtil.makeCache(
new ArgumentSpecialization.ArgumentCountIRFactory(options.getSSAOptions()));
JSCFABuilder builder =
new JSZeroOrOneXCFABuilder(
cha, options, cache, null, null, ZeroXInstanceKeys.ALLOCATIONS, false);
builder.setContextSelector(
new ArgumentSpecialization.ArgumentCountContextSelector(builder.getContextSelector()));
builder.setContextInterpreter(
new ArgumentSpecialization.ArgumentSpecializationContextIntepreter(options, cache));
CallGraph CG = builder.makeCallGraph(options);
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForArgs);
}
}
| 3,250
| 42.932432
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestCorrelatedPairExtraction.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationFinder;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationSummary;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.ClosureExtractor;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.CorrelatedPairExtractionPolicy;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.ExtractionPolicy;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.ExtractionPolicyFactory;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.classLoader.SourceURLModule;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.util.io.FileUtil;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
public abstract class TestCorrelatedPairExtraction {
// set to "true" to use JUnit's assertEquals to check whether a test case passed;
// if it is set to "false", expected and actual output are instead written to files expected.dump
// and actual.dump
// this is useful if the outputs are too big/too different for Eclipse's diff view to handle
private static final boolean ASSERT_EQUALS = true;
public void testRewriter(String in, String out) {
testRewriter(null, in, out);
}
public void testRewriter(String testName, String in, String out) {
File tmp = null;
try {
tmp = File.createTempFile("test", ".js");
FileUtil.writeFile(tmp, in);
final Map<IMethod, CorrelationSummary> summaries =
makeCorrelationFinder()
.findCorrelatedAccesses(
Collections.singleton(new SourceURLModule(tmp.toURI().toURL())));
CAstImpl ast = new CAstImpl();
CAstEntity inEntity = parseJS(tmp, ast);
ExtractionPolicyFactory policyFactory =
new ExtractionPolicyFactory() {
@Override
public ExtractionPolicy createPolicy(CAstEntity entity) {
CorrelatedPairExtractionPolicy policy =
CorrelatedPairExtractionPolicy.make(entity, summaries);
Assert.assertNotNull(policy);
return policy;
}
};
String actual =
new CAstDumper().dump(new ClosureExtractor(ast, policyFactory).rewrite(inEntity));
actual = TestForInBodyExtraction.eraseGeneratedNames(actual);
FileUtil.writeFile(tmp, out);
String expected = new CAstDumper().dump(parseJS(tmp, ast));
expected = TestForInBodyExtraction.eraseGeneratedNames(expected);
FileUtil.writeFile(new File("build/expected.dump"), expected);
FileUtil.writeFile(new File("build/actual.dump"), actual);
if (ASSERT_EQUALS) {
Assert.assertEquals(testName, expected, actual);
}
} catch (IOException | ClassHierarchyException e) {
e.printStackTrace();
} finally {
if (tmp != null && tmp.exists()) tmp.delete();
}
}
protected CAstEntity parseJS(File tmp, CAstImpl ast) throws IOException {
String moduleName = tmp.getName();
SourceFileModule module = new SourceFileModule(tmp, moduleName, null);
return parseJS(ast, module);
}
protected abstract CAstEntity parseJS(CAstImpl ast, SourceModule module) throws IOException;
protected abstract CorrelationFinder makeCorrelationFinder();
// example from the paper
@Test
public void test1() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " dest[p] = src[p];\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// example from the paper, but with single-statement loop body
@Test
public void test2() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src)\n"
+ " dest[p] = src[p];\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(var p in src)\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ "}");
}
// example from the paper, but without var decl
// currently fails because the loop index is a global variable
@Test
@Ignore
public void test3() {
testRewriter(
"function extend(dest, src) {\n" + " for(p in src)\n" + " dest[p] = src[p];\n" + "}",
"function extend(dest, src) {\n"
+ " for(p in src)\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ "}");
}
// example from the paper, but with separate var decl
@Test
public void test4() {
testRewriter(
"function extend(dest, src) {\n"
+ " var p;\n"
+ " for(p in src)\n"
+ " dest[p] = src[p];\n"
+ "}",
"function extend(dest, src) {\n"
+ " var p;\n"
+ " for(p in src)\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ "}");
}
// example from the paper, but with weirdly placed var decl
@Test
public void test5() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(p in src) {\n"
+ " var p;\n"
+ " dest[p] = src[p];\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(p in src) {\n"
+ " var p;\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// example from the paper, but with weirdly placed var decl in a different place
@Test
public void test6() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(p in src) {\n"
+ " dest[p] = src[p];\n"
+ " var p;\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(p in src) {\n"
+ " var p;\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// example where loop variable is referenced after the loop
// currently fails because the check is not implemented yet
@Test
@Ignore
public void test7() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " dest[p] = src[p];\n"
+ " p = true;\n"
+ " }\n"
+ " return p;\n"
+ "}",
null);
}
// example with "this"
@Test
public void test8() {
testRewriter(
"Object.prototype.extend = function(src) {\n"
+ " for(var p in src)\n"
+ " this[p] = src[p];\n"
+ "}",
"Object.prototype.extend = function(src) {\n"
+ " for(var p in src)\n"
+ " (function _forin_body_0(p, thi$) {\n"
+ " thi$[p] = src[p];\n"
+ " })(p, this);\n"
+ "}");
}
// another example with "this"
// fails since variables from enclosing functions are no longer in SSA form, hence no correlation
// is found
@Test
@Ignore
public void test9() {
testRewriter(
"function defglobals(globals) {\n"
+ " for(var p in globals) {\n"
+ " (function() {\n"
+ " this[p] = globals[p];\n"
+ " })();\n"
+ " }\n"
+ "}",
"function defglobals(globals) {\n"
+ " for(var p in globals) {\n"
+ " (function() {\n"
+ " (function _forin_body_0(p, thi$) {\n"
+ " thi$[p] = globals[p];\n"
+ " })(p, this)\n"
+ " })();\n"
+ " }\n"
+ "}");
}
// an example with "break"
@Test
public void test10() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " if(p == \"stop\")\n"
+ " break;\n"
+ " dest[p] = src[p];\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " if(p == \"stop\")\n"
+ " break;"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// another example with "break"
@Test
public void test11() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " while(true) {\n"
+ " dest[p] = src[p];\n"
+ " break;\n"
+ " }\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " while(true) {\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " break;\n"
+ " }\n"
+ " }\n"
+ "}");
}
// an example with labelled "break"
@Test
public void test12() {
testRewriter(
"function extend(dest, src) {\n"
+ " outer: for(var p in src) {\n"
+ " while(true) {\n"
+ " dest[p] = src[p];\n"
+ " break outer;\n"
+ " }\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " outer: for(var p in src) {\n"
+ " while(true) {\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);"
+ " break outer;\n"
+ " }\n"
+ " }\n"
+ "}");
}
// an example with exceptions
@Test
public void test13() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " if(p == '__proto__')\n"
+ " throw new Exception('huh?');\n"
+ " dest[p] = src[p];\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " for(var p in src) {\n"
+ " if(p == '__proto__')\n"
+ " throw new Exception('huh?');\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// an example with a "with" block
@Test
public void test14() {
testRewriter(
"function extend(dest, src) {\n"
+ " var o = { dest: dest };\n"
+ " with(o) {\n"
+ " for(var p in src) {\n"
+ " dest[p] = src[p];\n"
+ " }\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " var o = { dest: dest };\n"
+ " with(o) {\n"
+ " for(var p in src) {\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ " }\n"
+ "}");
}
// example with two functions
@Test
public void test15() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src)\n"
+ " dest[p] = src[p];\n"
+ "}\n"
+ "function foo() {\n"
+ " extend({}, {});\n"
+ "}\n"
+ "foo();",
"function extend(dest, src) {\n"
+ " for(var p in src)\n"
+ " (function _forin_body_0(p) {\n"
+ " dest[p] = src[p];\n"
+ " })(p);\n"
+ "}\n"
+ "function foo() {\n"
+ " extend({}, {});\n"
+ "}\n"
+ "foo();");
}
@Test
public void test16() {
testRewriter(
"function ext(dest, src) {\n"
+ " for(var p in src)\n"
+ " do_ext(dest, p, src);\n"
+ "}\n"
+ "function do_ext(x, p, y) { x[p] = y[p]; }",
"function ext(dest, src) {\n"
+ " for(var p in src)\n"
+ " do_ext(dest, p, src);\n"
+ "}\n"
+ "function do_ext(x, p, y) { x[p] = y[p]; }");
}
@Test
public void test17() {
testRewriter(
"function implement(dest, src) {\n"
+ " for(var p in src) {\n"
+ " dest.prototype[p] = src[p];\n"
+ " }\n"
+ "}",
"function implement(dest, src) {\n"
+ " for(var p in src) {\n"
+ " (function _forin_body_0(p) {\n"
+ " dest.prototype[p] = src[p];\n"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// fails since the assignment to "value" in the extracted version gets a (spurious) reference
// error CFG edge
@Test
public void test18() {
testRewriter(
"function addMethods(source) {\n"
+ " var properties = Object.keys(source);\n"
+ " for (var i = 0, length = properties.length; i < length; i++) {\n"
+ " var property = properties[i], value = source[property];\n"
+ " this.prototype[property] = value;\n"
+ " }\n"
+ " return this;\n"
+ "}",
"function addMethods(source) {\n"
+ " var properties = Object.keys(source);\n"
+ " for (var i = 0, length = properties.length; i < length; i++) {\n"
+ " var property, value; property = properties[i]; value = (function _forin_body_0(property, thi$) { var value = source[property]; \n"
+ " thi$.prototype[property] = value; return value; })(property, this);\n"
+ " }\n"
+ " return this;\n"
+ "}");
}
// slight variation of test18
@Test
public void test18_b() {
testRewriter(
"function addMethods(source) {\n"
+ " var properties = Object.keys(source);\n"
+ " for (var i = 0, length = properties.length; i < length; i++) {\n"
+ " var property = properties[i], foo = 23, value = source[property];\n"
+ " this.prototype[property] = value;\n"
+ " }\n"
+ " return this;\n"
+ "}",
"function addMethods(source) {\n"
+ " var properties = Object.keys(source);\n"
+ " for (var i = 0, length = properties.length; i < length; i++) {\n"
+ " var property, foo, value; property = properties[i]; foo = 23; value = (function _forin_body_0(property, thi$) { var value = source[property];\n"
+ " thi$.prototype[property] = value; return value; })(property, this);\n"
+ " }\n"
+ " return this;\n"
+ "}");
}
// fails since the assignment to "value" in the extracted version gets a (spurious) reference
// error CFG edge
@Test
public void test18_c() {
testRewriter(
"function addMethods(source) {\n"
+ " var properties = Object.keys(source);\n"
+ " for (var i = 0, length = properties.length; i < length; i++) {\n"
+ " var property = properties[i], foo = 23, value = source[property], bar = 42;\n"
+ " this.prototype[property] = value;\n"
+ " }\n"
+ " return this;\n"
+ "}",
"function addMethods(source) {\n"
+ " var properties = Object.keys(source);\n"
+ " for (var i = 0, length = properties.length; i < length; i++) {\n"
+ " var property, foo, value, bar; property = properties[i]; foo = 23; value = function _forin_body_0(property, thi$) { var value = source[property]; bar = 42;\n"
+ " thi$.prototype[property] = value; return value; }(property, this);\n"
+ " }\n"
+ " return this;\n"
+ "}");
}
@Test
public void test19() {
testRewriter(
"function extend(dest, src) {\n"
+ " for(var p in src)\n"
+ " if(foo(p)) write.call(dest, p, src[p]);\n"
+ "}\n"
+ "function write(p, v) { this[p] = v; }",
"function extend(dest, src) {\n"
+ " for(var p in src)\n"
+ " (function _forin_body_0(p) { if(foo(p)) write.call(dest, p, src[p]); })(p);\n"
+ "}\n"
+ "function write(p, v) { this[p] = v; }");
}
// fails due to a missing LOCAL_SCOPE node
@Test
@Ignore
public void test20() {
testRewriter(
"function every(object, fn, bind) {\n"
+ " for(var key in object)\n"
+ " if(hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;\n"
+ "}",
"function every(object, fn, bind) {\n"
+ " for(var key in object) {\n"
+ " re$ = (function _forin_body_0(key) {\n"
+ " if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return { type: 'return', value: false };\n"
+ " })(key);\n"
+ " if(re$) { if(re$.type == 'return') return re$.value; }\n"
+ " }\n"
+ "}");
}
@Test
public void test21() {
testRewriter(
"function extend(dest, src) {\n"
+ " var x, y;\n"
+ " for(var name in src) {\n"
+ " x = dest[name];\n"
+ " y = src[name];\n"
+ " dest[name] = join(x,y);\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " var x, y;\n"
+ " for(var name in src) {\n"
+ " (function _forin_body_0(name) { x = dest[name];\n"
+ " y = src[name];\n"
+ " dest[name] = join(x,y); })(name);\n"
+ " }\n"
+ "}");
}
@Test
public void test22() {
testRewriter(
"function(object, keys){\n"
+ " var results = {};\n"
+ " for (var i = 0, l = keys.length; i < l; i++){\n"
+ " var k = keys[i];\n"
+ " if (k in object) results[k] = object[k];\n"
+ " }\n"
+ " return results;\n"
+ "}",
"function(object, keys){\n"
+ " var results = {};\n"
+ " for (var i = 0, l = keys.length; i < l; i++){\n"
+ " var k = keys[i];\n"
+ " (function _forin_body_0(k) { if (k in object) results[k] = object[k]; })(k);\n"
+ " }\n"
+ " return results;\n"
+ "}");
}
// variant of test1
@Test
public void test23() {
testRewriter(
"function extend(dest, src) {\n"
+ " var s;\n"
+ " for(var p in src) {\n"
+ " s = src[p];\n"
+ " dest[p] = s;\n"
+ " }\n"
+ "}",
"function extend(dest, src) {\n"
+ " var s;\n"
+ " for(var p in src) {\n"
+ " s = (function _forin_body_0(p) {\n"
+ " var s;"
+ " s = src[p];\n"
+ " dest[p] = s;\n"
+ " return s;"
+ " })(p);\n"
+ " }\n"
+ "}");
}
// cannot extract for-in body referring to "arguments"
@Test
public void test24() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " arguments[0][p] = src[p];"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " arguments[0][p] = src[p];"
+ " }"
+ "}");
}
@Test
public void test25() {
testRewriter(
"function eachProp(obj, func) {"
+ " var prop;"
+ " for (prop in obj) {"
+ " if (hasProp(obj, prop)) {"
+ " if (func(obj[prop], prop)) {"
+ " break;"
+ " }"
+ " }"
+ " }"
+ "}",
"function eachProp(obj, func) {"
+ " var prop;"
+ " for (prop in obj) {"
+ " if (hasProp(obj, prop)) {"
+ " re$ = (function _forin_body_0 (prop) { if (func(obj[prop], prop)) { return { type: \"goto\", target: 0 }; } })(prop);"
+ " if (re$) {"
+ " if (re$.type == \"goto\") {"
+ " if (re$.target == 0)"
+ " break;"
+ " }"
+ " }"
+ " }"
+ " }"
+ "}");
}
}
| 21,800
| 32.488479
| 177
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestForInBodyExtraction.java
|
/*
* Copyright (c) 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.ClosureExtractor;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.extraction.ForInBodyExtractionPolicy;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.util.io.FileUtil;
import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
import org.junit.Assert;
import org.junit.ComparisonFailure;
import org.junit.Ignore;
import org.junit.Test;
public abstract class TestForInBodyExtraction {
public void testRewriter(String in, String out) {
testRewriter(null, in, out);
}
/* The translation to CAst introduces temporary names based on certain characteristics of the translation
* process. This sometimes makes it impossible to precisely match up the results of first translating to
* CAst and then transforming, and first transforming the JavaScript and then translating to CAst.
*
* As a heuristic, we replace some generated names with placeholders, which will be the same in both
* versions. This could in principle mask genuine errors.
*/
public static String eraseGeneratedNames(String str) {
Pattern generatedNamePattern = Pattern.compile("\\$\\$destructure\\$(rcvr|elt)\\d+");
str = generatedNamePattern.matcher(str).replaceAll("\\$\\$destructure\\$$1xxx");
Pattern generatedFunNamePattern = Pattern.compile("\\.js(@\\d+)+");
str = generatedFunNamePattern.matcher(str).replaceAll(".js@xxx");
return str;
}
public void testRewriter(String testName, String in, String out) {
File tmp = null;
String expected = null;
String actual = null;
try {
tmp = File.createTempFile("test", ".js");
FileUtil.writeFile(tmp, in);
CAstImpl ast = new CAstImpl();
actual =
new CAstDumper()
.dump(
new ClosureExtractor(ast, ForInBodyExtractionPolicy.FACTORY)
.rewrite(parseJS(tmp, ast)));
actual = eraseGeneratedNames(actual);
FileUtil.writeFile(tmp, out);
expected = new CAstDumper().dump(parseJS(tmp, ast));
expected = eraseGeneratedNames(expected);
Assert.assertEquals(testName, expected, actual);
} catch (IOException e) {
e.printStackTrace();
} catch (ComparisonFailure e) {
System.err.println("Comparison Failure in " + testName + "!");
System.err.println(expected);
System.err.println(actual);
throw e;
} finally {
if (tmp != null && tmp.exists()) tmp.delete();
}
}
protected CAstEntity parseJS(File tmp, CAstImpl ast) throws IOException {
String moduleName = tmp.getName();
SourceFileModule module = new SourceFileModule(tmp, moduleName, null);
return parseJS(ast, module);
}
protected abstract CAstEntity parseJS(CAstImpl ast, SourceModule module) throws IOException;
// example from the paper
@Test
public void test1() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " dest[p] = src[p];"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ " }"
+ "}");
}
// example from the paper, but with single-statement loop body
@Test
public void test2() {
testRewriter(
"function extend(dest, src) {" + " for(var p in src)" + " dest[p] = src[p];" + "}",
"function extend(dest, src) {"
+ " for(var p in src)"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ "}");
}
// example from the paper, but without var decl
@Test
public void test3() {
testRewriter(
"function extend(dest, src) {" + " for(p in src)" + " dest[p] = src[p];" + "}",
"function extend(dest, src) {"
+ " for(p in src)"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ "}");
}
// example from the paper, but with separate var decl
@Test
public void test4() {
testRewriter(
"function extend(dest, src) {"
+ " var p;"
+ " for(p in src)"
+ " dest[p] = src[p];"
+ "}",
"function extend(dest, src) {"
+ " var p;"
+ " for(p in src)"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ "}");
}
// example from the paper, but with weirdly placed var decl
@Test
public void test5() {
testRewriter(
"function extend(dest, src) {"
+ " for(p in src) {"
+ " var p;"
+ " dest[p] = src[p];"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(p in src) {"
+ " var p;"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ " }"
+ "}");
}
// example from the paper, but with weirdly placed var decl in a different place
@Test
public void test6() {
testRewriter(
"function extend(dest, src) {"
+ " for(p in src) {"
+ " dest[p] = src[p];"
+ " var p;"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(p in src) {"
+ " var p;"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ " }"
+ "}");
}
// example where loop variable is referenced after the loop
// this isn't currently handled, hence the test fails
@Test
@Ignore
public void test7() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " dest[p] = src[p];"
+ " p = true;"
+ " }"
+ " return p;"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src)"
+ " (function _let_0(_let_parm_0) {"
+ " (function _forin_body_0(p) {"
+ " try {"
+ " dest[p] = src[p];"
+ " p = true;"
+ " } finally {"
+ " _let_parm_0 = p;"
+ " }"
+ " })(p);"
+ " p = _let_parm_0;"
+ " })(p);"
+ " return p;"
+ "}");
}
// example with "this"
@Test
public void test8() {
testRewriter(
"Object.prototype.extend = function(src) {"
+ " for(var p in src)"
+ " this[p] = src[p];"
+ "}",
"Object.prototype.extend = function(src) {"
+ " for(var p in src)"
+ " (function _forin_body_0(p, thi$) {"
+ " thi$[p] = src[p];"
+ " })(p, this);"
+ "}");
}
// another example with "this"
@Test
public void test9() {
testRewriter(
"function defglobals(globals) {"
+ " for(var p in globals) {"
+ " (function inner() {"
+ " this[p] = globals[p];"
+ " })();"
+ " }"
+ "}",
"function defglobals(globals) {"
+ " for(var p in globals) {"
+ " (function _forin_body_0(p) {"
+ " (function inner() {"
+ " this[p] = globals[p];"
+ " })()"
+ " })(p);"
+ " }"
+ "}");
}
// an example with "break"
@Test
public void test10() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " if(p == \"stop\")"
+ " break;"
+ " dest[p] = src[p];"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " re$ = (function _forin_body_0(p) {"
+ " if(p == \"stop\")"
+ " return {type: 'goto', target: 0};"
+ " dest[p] = src[p];"
+ " })(p);"
+ " if(re$) {"
+ " if(re$.type == 'goto') {"
+ " if(re$.target == 0)"
+ " break;"
+ " }"
+ " }"
+ " }"
+ "}");
}
// another example with "break"
@Test
public void test11() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " while(true) {"
+ " dest[p] = src[p];"
+ " break;"
+ " }"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " (function _forin_body_0(p) {"
+ " while(true) {"
+ " dest[p] = src[p];"
+ " break;"
+ " }"
+ " })(p);"
+ " }"
+ "}");
}
// an example with labelled "break"
@Test
public void test12() {
testRewriter(
"function extend(dest, src) {"
+ " outer: for(var p in src) {"
+ " while(true) {"
+ " dest[p] = src[p];"
+ " break outer;"
+ " }"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " outer: for(var p in src) {"
+ " re$ = (function _forin_body_0(p) {"
+ " while(true) {"
+ " dest[p] = src[p];"
+ " return {type: 'goto', target: 0};"
+ " }"
+ " })(p);"
+ " if(re$) {"
+ " if(re$.type == 'goto') {"
+ " if(re$.target == 0)"
+ " break outer;"
+ " }"
+ " }"
+ " }"
+ "}");
}
// an example with exceptions
@Test
public void test13() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " if(p == '__proto__')"
+ " throw new Exception('huh?');"
+ " dest[p] = src[p];"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " (function _forin_body_0(p) {"
+ " if(p == '__proto__')"
+ " throw new Exception('huh?');"
+ " dest[p] = src[p];"
+ " })(p);"
+ " }"
+ "}");
}
// an example with a var decl
// this test fails due to a trivial difference between transformed and expected CAst that isn't
// semantically relevant
@Test
@Ignore
public void test14() {
testRewriter(
"x = 23;"
+ "function foo() {"
+ " x = 42;"
+ " for(var p in {toString : 23}) {"
+ " var x = 56;"
+ " alert(x);"
+ " }"
+ " alert(x);"
+ "}"
+ "foo();"
+ "alert(x);",
"x = 23;"
+ "function foo() {"
+ " x = 42;"
+ " for(var p in {toString : 23}) {"
+ " var x;"
+ " (function _forin_body_0(p) {"
+ " x = 56;"
+ " alert(x);"
+ " })(p);"
+ " }"
+ " alert(x);"
+ "}"
+ "foo();"
+ "alert(x);");
}
// another example with a var decl
@Test
public void test15() {
testRewriter(
"x = 23;"
+ "function foo() {"
+ " x = 42;"
+ " for(var p in {toString : 23}) {"
+ " (function inner() {"
+ " var x = 56;"
+ " alert(x);"
+ " })();"
+ " }"
+ " alert(x);"
+ "}"
+ "foo();"
+ "alert(x);",
"x = 23;"
+ "function foo() {"
+ " x = 42;"
+ " for(var p in {toString : 23}) {"
+ " (function _forin_body_0(p) {"
+ " (function inner() {"
+ " var x = 56;"
+ " alert(x);"
+ " })();"
+ " })(p);"
+ " }"
+ " alert(x);"
+ "}"
+ "foo();"
+ "alert(x);");
}
// an example with a "with" block
@Test
public void test16() {
testRewriter(
"function extend(dest, src) {"
+ " var o = { dest: dest };"
+ " with(o) {"
+ " for(var p in src) {"
+ " dest[p] = src[p];"
+ " }"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " var o = { dest: dest };"
+ " with(o) {"
+ " for(var p in src) {"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ " }"
+ " }"
+ "}");
}
// top-level for-in loop
@Test
public void test17() {
testRewriter(
"var o = {x:23};" + "for(x in o) {" + " o[x] += 19;" + "}",
"var o = {x:23};"
+ "for(x in o) {"
+ " (function _forin_body_0(x) {"
+ " o[x] += 19;"
+ " })(x);"
+ "}");
}
// nested for-in loops
@Test
public void test18() {
testRewriter(
"var o = {x:{y:23}};"
+ "for(x in o) {"
+ " for(y in o[x]) {"
+ " o[x][y] += 19;"
+ " }"
+ "}",
"var o = {x:{y:23}};"
+ "for(x in o) {"
+ " (function _forin_body_0(x) {"
+ " for(y in o[x]) {"
+ " (function _forin_body_1(y) {"
+ " o[x][y] += 19;"
+ " })(y);"
+ " }"
+ " })(x);"
+ "}");
}
// return in loop body
@Test
public void test19() {
testRewriter(
"function foo(x) {"
+ " for(var p in x) {"
+ " if(p == 'ret')"
+ " return x[p];"
+ " x[p]++;"
+ " }"
+ "}",
"function foo(x) {"
+ " for(var p in x) {"
+ " re$ = (function _forin_body_0(p) {"
+ " if(p == 'ret')"
+ " return {type: 'return', value: x[p]};"
+ " x[p]++;"
+ " })(p);"
+ " if(re$) {"
+ " if(re$.type == 'return')"
+ " return re$.value;"
+ " }"
+ " }"
+ "}");
}
// example with two functions
@Test
public void test20() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src)"
+ " dest[p] = src[p];"
+ "}"
+ "function foo() {"
+ " extend({}, {});"
+ "}"
+ "foo();",
"function extend(dest, src) {"
+ " for(var p in src)"
+ " (function _forin_body_0(p) {"
+ " dest[p] = src[p];"
+ " })(p);"
+ "}"
+ "function foo() {"
+ " extend({}, {});"
+ "}"
+ "foo();");
}
// example with nested for-in loops and this (adapted from MooTools)
// currently fails because generated names look different
@Test
public void test21() {
testRewriter(
"function foo() {"
+ " var result = [];"
+ " for(var style in Element.ShortStyles) {"
+ " for(var s in Element.ShortStyles[style]) {"
+ " result.push(this.getStyle(s));"
+ " }"
+ " }"
+ "}",
"function foo() {"
+ " var result = [];"
+ " for(var style in Element.ShortStyles) {"
+ " var s;"
+ " (function _forin_body_0(style, thi$) {"
+ " for(s in Element.ShortStyles[style]) {"
+ " (function _forin_body_1(s) {"
+ " result.push(thi$.getStyle(s));"
+ " })(s);"
+ " }"
+ " })(style, this);"
+ " }"
+ "}");
}
// example with nested for-in loops and continue (adapted from MooTools)
@Test
public void test22() {
testRewriter(
"function foo(property) {"
+ " var result = [];"
+ " for(var style in Element.ShortStyles) {"
+ " if(property != style) continue; "
+ " for(var s in Element.ShortStyles[style]) {"
+ " ;"
+ " }"
+ " }"
+ "}",
"function foo(property) {"
+ " var result = [];"
+ " for(var style in Element.ShortStyles) {"
+ " var s;"
+ " re$ = (function _forin_body_0(style) {"
+ " if(property != style) return {type:'goto', target:0}; "
+ " for(s in Element.ShortStyles[style]) {"
+ " (function _forin_body_1(s) {"
+ " ;"
+ " })(s);"
+ " }"
+ " })(style);"
+ " if(re$) {"
+ " if(re$.type == 'goto') {"
+ " if(re$.target == 0)"
+ " continue;"
+ " }"
+ " }"
+ " }"
+ "}");
}
@Test
public void test23() {
testRewriter(
"function foo(obj) {"
+ " for(var p in obj) {"
+ " if(p != 'bar')"
+ " continue;"
+ " return obj[p];"
+ " }"
+ "}",
"function foo(obj) {"
+ " for(var p in obj) {"
+ " re$ = (function _forin_body_0(p) {"
+ " if(p != 'bar')"
+ " return {type:'goto', target:0};"
+ " return {type:'return', value:obj[p]};"
+ " })(p);"
+ " if(re$) {"
+ " if(re$.type == 'return')"
+ " return re$.value;"
+ " if(re$.type == 'goto') {"
+ " if(re$.target == 0)"
+ " continue;"
+ " }"
+ " }"
+ " }"
+ "}");
}
// currently fails because generated names look different
@Test
public void test24() {
testRewriter(
"var addSlickPseudos = function() {"
+ " for(var name in pseudos)"
+ " if(pseudos.hasOwnProperty(name)) {"
+ " ;"
+ " }"
+ "}",
"var addSlickPseudos = function() {"
+ " for(var name in pseudos)"
+ " (function _forin_body_0(name) {"
+ " if(pseudos.hasOwnProperty(name)) {"
+ " ;"
+ " }"
+ " })(name);"
+ "}");
}
@Test
public void test25() {
testRewriter(
"function ext(dest, src) {"
+ " for(var p in src)"
+ " do_ext(dest, p, src);"
+ "}"
+ "function do_ext(x, p, y) { x[p] = y[p]; }",
"function ext(dest, src) {"
+ " for(var p in src)"
+ " (function _forin_body_0(p) {"
+ " do_ext(dest, p, src);"
+ " })(p);"
+ "}"
+ "function do_ext(x, p, y) { x[p] = y[p]; }");
}
@Test
public void test26() {
testRewriter(
"function foo(x) {"
+ " for(p in x) {"
+ " for(q in p[x]) {"
+ " if(b)"
+ " return 23;"
+ " }"
+ " }"
+ "}",
"function foo(x) {"
+ " for(p in x) {"
+ " re$ = (function _forin_body_0(p) {"
+ " for(q in p[x]) {"
+ " re$ = (function _forin_body_1(q) {"
+ " if(b)"
+ " return { type: 'return', value: 23 };"
+ " })(q);"
+ " if(re$) {"
+ " return re$;"
+ " }"
+ " }"
+ " })(p);"
+ " if(re$) {"
+ " if(re$.type == 'return')"
+ " return re$.value;"
+ " }"
+ " }"
+ "}");
}
// variation of test22
@Test
public void test27() {
testRewriter(
"function foo(property) {"
+ " var result = [];"
+ " outer: for(var style in Element.ShortStyles) {"
+ " for(var s in Element.ShortStyles[style]) {"
+ " if(s != style) continue outer;"
+ " }"
+ " }"
+ "}",
"function foo(property) {"
+ " var result = [];"
+ " outer: for(var style in Element.ShortStyles) {"
+ " var s;"
+ " re$ = (function _forin_body_0(style) {"
+ " for(s in Element.ShortStyles[style]) {"
+ " re$ = (function _forin_body_1(s) {"
+ " if(s != style) return {type:'goto', target:0};"
+ " })(s);"
+ " if(re$) {"
+ " return re$;"
+ " }"
+ " }"
+ " })(style);"
+ " if(re$) {"
+ " if(re$.type == 'goto') {"
+ " if(re$.target == 0)"
+ " continue outer;"
+ " }"
+ " }"
+ " }"
+ "}");
}
// another variation of test22
@Test
public void test28() {
testRewriter(
"function foo(property) {"
+ " var result = [];"
+ " outer: for(var style in Element.ShortStyles) {"
+ " for(var s in Element.ShortStyles[style]) {"
+ " if(s != style) continue;"
+ " }"
+ " }"
+ "}",
"function foo(property) {"
+ " var result = [];"
+ " outer: for(var style in Element.ShortStyles) {"
+ " var s;"
+ " (function _forin_body_0(style) {"
+ " for(s in Element.ShortStyles[style]) {"
+ " re$ = (function _forin_body_1(s) {"
+ " if(s != style) return {type:'goto', target:0};"
+ " })(s);"
+ " if(re$) {"
+ " if(re$.type == 'goto') {"
+ " if(re$.target == 0)"
+ " continue;"
+ " }"
+ " }"
+ " }"
+ " })(style);"
+ " }"
+ "}");
}
// test where the same entity (namely the inner function "copy") is rewritten more than once
// this probably shouldn't happen
@Test
public void test29() {
testRewriter(
"Element.addMethods = function(methods) {"
+ " function copy() {"
+ " for (var property in methods) {"
+ " }"
+ " }"
+ " for (var tag in methods) {"
+ " }"
+ "};",
"Element.addMethods = function(methods) {"
+ " function copy() {"
+ " for (var property in methods) {"
+ " (function _forin_body_1(property) {"
+ " })(property);"
+ " }"
+ " }"
+ " for (var tag in methods) {"
+ " (function _forin_body_0(tag){ })(tag);"
+ " }"
+ "};");
}
@Test
public void test30() {
testRewriter(
"try {" + " for(var i in {}) {" + " f();" + " }" + "} catch(_) {}",
"try {"
+ " for(var i in {}) {"
+ " (function _forin_body_0(i) {"
+ " f();"
+ " })(i);"
+ " }"
+ "} catch(_) {}");
}
// cannot extract for-in body referring to "arguments"
@Test
public void test31() {
testRewriter(
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " arguments[0][p] = src[p];"
+ " }"
+ "}",
"function extend(dest, src) {"
+ " for(var p in src) {"
+ " arguments[0][p] = src[p];"
+ " }"
+ "}");
}
}
| 25,510
| 29.884988
| 107
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestForInLoopHack.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.PropertyNameContextSelector;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import java.net.URL;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public abstract class TestForInLoopHack extends TestJSCallGraphShape {
@Before
public void config() {
JSSourceExtractor.USE_TEMP_NAME = true;
JSSourceExtractor.DELETE_UPON_EXIT = false;
}
@Test
public void testPage3WithoutHack()
throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/page3.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
}
@Test
public void testPage3WithHack() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/page3.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
addHackedForInLoopSensitivity(builder);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
}
@Ignore(
"This test now blows up due to proper handling of the || construct, used in extend(). Should handle this eventually.")
@Test
public void testJQueryWithHack() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/jquery_hacked.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
addHackedForInLoopSensitivity(builder);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
}
/*
@Test public void testJQueryEx1WithHack() throws IOException, IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/jquery/ex1.html");
JSCFABuilder builder = Util.makeHTMLCGBuilder(url);
addHackedForInLoopSensitivity(builder);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
Util.dumpCG(builder.getPointerAnalysis(), CG);
}
*/
private static final Object[][] assertionsForBadForin =
new Object[][] {
new Object[] {ROOT, new String[] {"badforin.js"}},
new Object[] {
"badforin.js",
new String[] {
"badforin.js/testForIn",
"badforin.js/_check_obj_foo",
"badforin.js/_check_obj_bar",
"badforin.js/_check_copy_foo",
"badforin.js/_check_copy_bar"
}
},
new Object[] {
"badforin.js/testForIn", new String[] {"badforin.js/testForIn1", "badforin.js/testForIn2"}
},
new Object[] {"badforin.js/_check_obj_foo", new String[] {"badforin.js/testForIn1"}},
new Object[] {"badforin.js/_check_copy_foo", new String[] {"badforin.js/testForIn1"}},
new Object[] {"badforin.js/_check_obj_bar", new String[] {"badforin.js/testForIn2"}},
new Object[] {"badforin.js/_check_copy_bar", new String[] {"badforin.js/testForIn2"}}
};
@Test
public void testBadForInWithoutHack()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "badforin.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForBadForin);
}
private static final Object[][] assertionsForBadForinHackPrecision =
new Object[][] {
new Object[] {"badforin.js/_check_obj_foo", new String[] {"!badforin.js/testForIn2"}},
new Object[] {"badforin.js/_check_copy_foo", new String[] {"!badforin.js/testForIn2"}},
new Object[] {"badforin.js/_check_obj_bar", new String[] {"!badforin.js/testForIn1"}},
new Object[] {"badforin.js/_check_copy_bar", new String[] {"!badforin.js/testForIn1"}}
};
@Test
public void testBadForInWithHack()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "badforin.js");
addHackedForInLoopSensitivity(B);
CallGraph CG = B.makeCallGraph(B.getOptions());
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForBadForin);
verifyGraphAssertions(CG, assertionsForBadForinHackPrecision);
}
private static final Object[][] assertionsForbadforin2 =
new Object[][] {
new Object[] {ROOT, new String[] {"badforin2.js"}},
new Object[] {
"badforin2.js",
new String[] {
"badforin2.js/testForIn",
"badforin2.js/_check_obj_foo",
"badforin2.js/_check_obj_bar",
"badforin2.js/_check_copy_foo",
"badforin2.js/_check_copy_bar"
}
},
new Object[] {
"badforin2.js/testForIn",
new String[] {"badforin2.js/testForIn1", "badforin2.js/testForIn2"}
},
new Object[] {"badforin2.js/_check_obj_foo", new String[] {"badforin2.js/testForIn1"}},
new Object[] {"badforin2.js/_check_copy_foo", new String[] {"badforin2.js/testForIn1"}},
new Object[] {"badforin2.js/_check_obj_bar", new String[] {"badforin2.js/testForIn2"}},
new Object[] {"badforin2.js/_check_copy_bar", new String[] {"badforin2.js/testForIn2"}}
};
@Test
public void testbadforin2WithoutHack()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "badforin2.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForbadforin2);
}
private static final Object[][] assertionsForbadforin2HackPrecision =
new Object[][] {
new Object[] {"badforin2.js/_check_obj_foo", new String[] {"!badforin2.js/testForIn2"}},
new Object[] {"badforin2.js/_check_copy_foo", new String[] {"!badforin2.js/testForIn2"}},
new Object[] {"badforin2.js/_check_obj_bar", new String[] {"!badforin2.js/testForIn1"}},
new Object[] {"badforin2.js/_check_copy_bar", new String[] {"!badforin2.js/testForIn1"}}
};
@Test
public void testbadforin2WithHack()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "badforin2.js");
addHackedForInLoopSensitivity(B);
CallGraph CG = B.makeCallGraph(B.getOptions());
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForbadforin2);
verifyGraphAssertions(CG, assertionsForbadforin2HackPrecision);
}
@Test
public void testForInRecursion()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "badforin3.js");
addHackedForInLoopSensitivity(B);
CallGraph CG = B.makeCallGraph(B.getOptions());
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
}
/*
@Test public void testYahooWithoutHack() throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = Util.makeScriptCGBuilder("frameworks", "yahoo.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
Util.dumpCG(B.getPointerAnalysis(), CG);
}
*/
private static void addHackedForInLoopSensitivity(JSCFABuilder builder) {
final ContextSelector orig = builder.getContextSelector();
builder.setContextSelector(new PropertyNameContextSelector(builder.getAnalysisCache(), orig));
}
}
| 8,940
| 44.156566
| 125
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestJQueryExamples.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.net.URL;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class TestJQueryExamples extends TestJSCallGraphShape {
@Before
public void config() {
JSSourceExtractor.USE_TEMP_NAME = false;
JSSourceExtractor.DELETE_UPON_EXIT = false;
}
@Ignore("This tries to analyze unmodified jquery, which we can't do yet")
@Test
public void testEx1() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/jquery/ex1.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
}
}
| 1,544
| 35.785714
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestJSCallGraphShape.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.util.test.TestCallGraphShape;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import java.util.Collection;
public abstract class TestJSCallGraphShape extends TestCallGraphShape {
@Override
public Collection<CGNode> getNodes(CallGraph CG, String functionIdentifier) {
return JSCallGraphUtil.getNodes(CG, functionIdentifier);
}
}
| 874
| 32.653846
| 79
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestJavaScriptSlicer.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.modref.JavaScriptModRef;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.slicer.NormalStatement;
import com.ibm.wala.ipa.slicer.SDG;
import com.ibm.wala.ipa.slicer.Slicer;
import com.ibm.wala.ipa.slicer.Slicer.ControlDependenceOptions;
import com.ibm.wala.ipa.slicer.Slicer.DataDependenceOptions;
import com.ibm.wala.ipa.slicer.SlicerUtil;
import com.ibm.wala.ipa.slicer.Statement;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.io.IOException;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Test;
public abstract class TestJavaScriptSlicer extends TestJSCallGraphShape {
@Test
public void testSimpleData()
throws IOException, WalaException, IllegalArgumentException, CancelException {
Collection<Statement> result =
slice("slice1.js", DataDependenceOptions.FULL, ControlDependenceOptions.NONE);
for (Statement r : result) {
System.err.println(r);
}
Assert.assertEquals(0, SlicerUtil.countConditionals(result));
}
@Test
public void testSimpleAll()
throws IOException, WalaException, IllegalArgumentException, CancelException {
Collection<Statement> result =
slice("slice1.js", DataDependenceOptions.FULL, ControlDependenceOptions.FULL);
for (Statement r : result) {
System.err.println(r);
}
Assert.assertEquals(2, SlicerUtil.countConditionals(result));
}
@Test
public void testSimpleControl()
throws IOException, WalaException, IllegalArgumentException, CancelException {
Collection<Statement> result =
slice("slice1.js", DataDependenceOptions.NONE, ControlDependenceOptions.FULL);
for (Statement r : result) {
System.err.println(r);
}
Assert.assertEquals(1, SlicerUtil.countConditionals(result));
}
private Collection<Statement> slice(
String file, DataDependenceOptions data, ControlDependenceOptions ctrl)
throws IOException, WalaException, CancelException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", file);
CallGraph CG = B.makeCallGraph(B.getOptions());
SDG<InstanceKey> sdg =
new SDG<>(CG, B.getPointerAnalysis(), new JavaScriptModRef<>(), data, ctrl);
final Collection<Statement> ss = findTargetStatement(CG);
Collection<Statement> result = Slicer.computeBackwardSlice(sdg, ss);
return result;
}
private Collection<Statement> findTargetStatement(CallGraph CG) {
final Collection<Statement> ss = HashSetFactory.make();
for (CGNode n : getNodes(CG, "suffix:_slice_target_fn")) {
for (CGNode caller : Iterator2Iterable.make(CG.getPredNodes(n))) {
for (CallSiteReference site : Iterator2Iterable.make(CG.getPossibleSites(caller, n))) {
caller
.getIR()
.getCallInstructionIndices(site)
.foreach(x -> ss.add(new NormalStatement(caller, x)));
}
}
}
return ss;
}
}
| 3,781
| 34.679245
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestLexicalModRef.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ipa.lexical.LexicalModRef;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public abstract class TestLexicalModRef {
@Test
public void testSimpleLexical()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder b = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "simple-lexical.js");
CallGraph CG = b.makeCallGraph(b.getOptions());
LexicalModRef lexAccesses = LexicalModRef.make(CG, b.getPointerAnalysis());
Map<CGNode, OrdinalSet<Pair<CGNode, String>>> readResult = lexAccesses.computeLexicalRef();
Map<CGNode, OrdinalSet<Pair<CGNode, String>>> writeResult = lexAccesses.computeLexicalMod();
for (Map.Entry<CGNode, OrdinalSet<Pair<CGNode, String>>> entry : readResult.entrySet()) {
final CGNode n = entry.getKey();
if (n.toString()
.contains("Node: <Code body of function Ltests/simple-lexical.js/outer/inner>")) {
// function "inner" reads exactly x and z
OrdinalSet<Pair<CGNode, String>> readVars = entry.getValue();
Assert.assertEquals(2, readVars.size());
Assert.assertEquals(
"[[Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,x], [Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,z]]",
readVars.toString());
// writes x and z as well
OrdinalSet<Pair<CGNode, String>> writtenVars = writeResult.get(n);
Assert.assertEquals(2, writtenVars.size());
Assert.assertEquals(
"[[Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,x], [Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,z]]",
writtenVars.toString());
}
if (n.toString()
.contains("Node: <Code body of function Ltests/simple-lexical.js/outer/inner2>")) {
// function "inner3" reads exactly innerName, inner3, and x and z via callees
OrdinalSet<Pair<CGNode, String>> readVars = entry.getValue();
Assert.assertEquals(4, readVars.size());
for (Pair<CGNode, String> rv : readVars) {
Assert.assertTrue(
rv.toString(),
"[Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,x]"
.equals(rv.toString())
|| "[Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,inner3]"
.equals(rv.toString())
|| "[Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,innerName]"
.equals(rv.toString())
|| "[Node: <Code body of function Ltests/simple-lexical.js/outer> Context: Everywhere,z]"
.equals(rv.toString()));
}
}
}
}
}
| 3,687
| 48.173333
| 187
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestMediawikiCallGraphShape.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import java.net.URL;
import org.junit.Ignore;
import org.junit.Test;
public abstract class TestMediawikiCallGraphShape extends TestJSCallGraphShape {
private static final Object[][] assertionsForSwineFlu = new Object[][] {};
@Ignore("not terminating; Julian, take a look?")
@Test
public void testSwineFlu()
throws IOException, IllegalArgumentException, CancelException, WalaException {
URL url = new URL("http://en.wikipedia.org/wiki/2009_swine_flu_outbreak");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForSwineFlu);
}
}
| 1,224
| 34
| 84
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestPointerAnalyses.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.analysis.pointers.HeapGraph;
import com.ibm.wala.cast.ipa.callgraph.GlobalObjectKey;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
import com.ibm.wala.cast.js.callgraph.fieldbased.FieldBasedCallGraphBuilder.CallGraphResult;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.GlobalVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.ObjectVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.PrototypeFieldVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.PrototypeFieldVertex.PrototypeField;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.TransitivePrototypeKey;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions.JavaScriptConstructor;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.ssa.JavaScriptPropertyWrite;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.cast.loader.AstDynamicField;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.NullProgressMonitor;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.MapIterator;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import org.junit.Assert;
import org.junit.Test;
public abstract class TestPointerAnalyses {
private static final class CheckPointers
implements Predicate<
Pair<Set<Pair<CGNode, NewSiteReference>>, Set<Pair<CGNode, NewSiteReference>>>> {
private static Set<Pair<String, Integer>> map(Set<Pair<CGNode, NewSiteReference>> sites) {
Set<Pair<String, Integer>> result = HashSetFactory.make();
for (Pair<CGNode, NewSiteReference> s : sites) {
result.add(Pair.make(s.fst.getMethod().toString(), s.snd.getProgramCounter()));
}
return result;
}
@Override
public boolean test(
Pair<Set<Pair<CGNode, NewSiteReference>>, Set<Pair<CGNode, NewSiteReference>>> t) {
if (t.snd.isEmpty()) {
return true;
}
Set<Pair<String, Integer>> x = HashSetFactory.make(map(t.fst));
x.retainAll(map(t.snd));
return !x.isEmpty();
}
}
private final JavaScriptTranslatorFactory factory;
protected TestPointerAnalyses(JavaScriptTranslatorFactory factory) {
this.factory = factory;
JSCallGraphUtil.setTranslatorFactory(factory);
}
private static Pair<CGNode, NewSiteReference> map(
CallGraph CG, Pair<CGNode, NewSiteReference> ptr) {
CGNode n = ptr.fst;
if (!(n.getMethod() instanceof JavaScriptConstructor)) {
return ptr;
}
Iterator<CGNode> preds = CG.getPredNodes(n);
if (!preds.hasNext()) {
return ptr;
}
CGNode caller = preds.next();
assert !preds.hasNext() : n;
Iterator<CallSiteReference> sites = CG.getPossibleSites(caller, n);
CallSiteReference site = sites.next();
assert !sites.hasNext();
return Pair.make(
caller, new NewSiteReference(site.getProgramCounter(), ptr.snd.getDeclaredType()));
}
private static Set<Pair<CGNode, NewSiteReference>> map(
CallGraph CG, Set<Pair<CGNode, NewSiteReference>> ptrs) {
Set<Pair<CGNode, NewSiteReference>> result = HashSetFactory.make();
for (Pair<CGNode, NewSiteReference> ptr : ptrs) {
result.add(map(CG, ptr));
}
return result;
}
private static Set<Pair<CGNode, NewSiteReference>> ptrs(
Set<CGNode> functions, int local, CallGraph CG, PointerAnalysis<? extends InstanceKey> pa) {
Set<Pair<CGNode, NewSiteReference>> result = HashSetFactory.make();
for (CGNode n : functions) {
PointerKey l = pa.getHeapModel().getPointerKeyForLocal(n, local);
if (l != null) {
OrdinalSet<? extends InstanceKey> pointers = pa.getPointsToSet(l);
if (pointers != null) {
for (InstanceKey k : pointers) {
for (Pair<CGNode, NewSiteReference> cs :
Iterator2Iterable.make(k.getCreationSites(CG))) {
result.add(cs);
}
}
}
}
}
return result;
}
private static boolean isGlobal(
Set<CGNode> functions, int local, PointerAnalysis<? extends InstanceKey> pa) {
for (CGNode n : functions) {
PointerKey l = pa.getHeapModel().getPointerKeyForLocal(n, local);
if (l != null) {
OrdinalSet<? extends InstanceKey> pointers = pa.getPointsToSet(l);
if (pointers != null) {
for (InstanceKey k : pointers) {
if (k instanceof GlobalObjectKey || k instanceof GlobalVertex) {
return true;
}
}
}
}
}
return false;
}
private void testPage(
URL page,
Predicate<MethodReference> filter,
Predicate<Pair<Set<Pair<CGNode, NewSiteReference>>, Set<Pair<CGNode, NewSiteReference>>>>
test)
throws WalaException, CancelException {
try (ExtractingToPredictableFileNames predictable = new ExtractingToPredictableFileNames()) {
FieldBasedCGUtil fb = new FieldBasedCGUtil(factory);
CallGraphResult fbResult =
fb.buildCG(page, BuilderType.OPTIMISTIC, true, DefaultSourceExtractor.factory);
JSCFABuilder propagationBuilder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(page);
CallGraph propCG = propagationBuilder.makeCallGraph(propagationBuilder.getOptions());
PointerAnalysis<InstanceKey> propPA = propagationBuilder.getPointerAnalysis();
test(filter, test, fbResult.getCallGraph(), fbResult.getPointerAnalysis(), propCG, propPA);
}
}
private void testTestScript(
String dir,
String name,
Predicate<MethodReference> filter,
Predicate<Pair<Set<Pair<CGNode, NewSiteReference>>, Set<Pair<CGNode, NewSiteReference>>>>
test)
throws IOException, WalaException, CancelException {
boolean save = JSSourceExtractor.USE_TEMP_NAME;
try {
JSSourceExtractor.USE_TEMP_NAME = false;
FieldBasedCGUtil fb = new FieldBasedCGUtil(factory);
CallGraphResult fbResult =
fb.buildTestCG(dir, name, BuilderType.OPTIMISTIC, new NullProgressMonitor(), true);
JSCFABuilder propagationBuilder = JSCallGraphBuilderUtil.makeScriptCGBuilder(dir, name);
CallGraph propCG = propagationBuilder.makeCallGraph(propagationBuilder.getOptions());
PointerAnalysis<InstanceKey> propPA = propagationBuilder.getPointerAnalysis();
test(filter, test, fbResult.getCallGraph(), fbResult.getPointerAnalysis(), propCG, propPA);
} finally {
JSSourceExtractor.USE_TEMP_NAME = save;
}
}
protected void test(
Predicate<MethodReference> filter,
Predicate<Pair<Set<Pair<CGNode, NewSiteReference>>, Set<Pair<CGNode, NewSiteReference>>>>
test,
CallGraph fbCG,
PointerAnalysis<ObjectVertex> fbPA,
CallGraph propCG,
PointerAnalysis<InstanceKey> propPA) {
HeapGraph<ObjectVertex> hg = fbPA.getHeapGraph();
Set<MethodReference> functionsToCompare = HashSetFactory.make();
for (CGNode n : fbCG) {
MethodReference ref = n.getMethod().getReference();
if (filter.test(ref) && !propCG.getNodes(ref).isEmpty()) {
functionsToCompare.add(ref);
}
}
System.err.println(fbCG);
for (MethodReference function : functionsToCompare) {
System.err.println("testing " + function);
Set<CGNode> fbNodes = fbCG.getNodes(function);
Set<CGNode> propNodes = propCG.getNodes(function);
CGNode node = fbNodes.iterator().next();
IR ir = node.getIR();
System.err.println(ir);
int maxVn = -1;
for (CallGraph cg : new CallGraph[] {fbCG, propCG}) {
for (CGNode n : cg) {
IR nir = n.getIR();
if (nir != null && nir.getSymbolTable().getMaxValueNumber() > maxVn) {
maxVn = nir.getSymbolTable().getMaxValueNumber();
}
}
}
for (int i = 1; i <= maxVn; i++) {
Set<Pair<CGNode, NewSiteReference>> fbPtrs = ptrs(fbNodes, i, fbCG, fbPA);
Set<Pair<CGNode, NewSiteReference>> propPtrs =
map(propCG, ptrs(propNodes, i, propCG, propPA));
Assert.assertEquals(
"analysis should agree on global object for " + i + " of " + ir,
isGlobal(fbNodes, i, fbPA),
isGlobal(propNodes, i, propPA));
if (!fbPtrs.isEmpty() || !propPtrs.isEmpty()) {
System.err.println(
"checking local " + i + " of " + function + ": " + fbPtrs + " vs " + propPtrs);
}
Assert.assertTrue(
fbPtrs + " should intersect " + propPtrs + " for " + i + " of " + ir,
test.test(Pair.make(fbPtrs, propPtrs)));
}
SymbolTable symtab = ir.getSymbolTable();
for (SSAInstruction inst : ir.getInstructions()) {
if (inst instanceof JavaScriptPropertyWrite) {
int property = ((AstPropertyWrite) inst).getMemberRef();
if (symtab.isConstant(property)) {
String p =
JSCallGraphUtil.simulateToStringForPropertyNames(symtab.getConstantValue(property));
int obj = ((AstPropertyWrite) inst).getObjectRef();
PointerKey objKey = fbPA.getHeapModel().getPointerKeyForLocal(node, obj);
OrdinalSet<ObjectVertex> objPtrs = fbPA.getPointsToSet(objKey);
for (ObjectVertex o : objPtrs) {
PointerKey propKey =
fbPA.getHeapModel()
.getPointerKeyForInstanceField(
o,
new AstDynamicField(
false,
o.getConcreteType(),
Atom.findOrCreateUnicodeAtom(p),
JavaScriptTypes.Root));
Assert.assertTrue(
"object " + o + " should have field " + propKey, hg.hasEdge(o, propKey));
int val = ((AstPropertyWrite) inst).getValue();
PointerKey valKey = fbPA.getHeapModel().getPointerKeyForLocal(node, val);
OrdinalSet<ObjectVertex> valPtrs = fbPA.getPointsToSet(valKey);
for (ObjectVertex v : valPtrs) {
Assert.assertTrue(
"field " + propKey + " should point to object " + valKey + "(" + v + ")",
hg.hasEdge(propKey, v));
}
}
System.err.println("heap graph models instruction " + inst);
}
} else if (inst instanceof AstGlobalWrite) {
String propName = ((AstGlobalWrite) inst).getGlobalName();
propName = propName.substring("global ".length());
PointerKey propKey =
fbPA.getHeapModel()
.getPointerKeyForInstanceField(
null,
new AstDynamicField(
false,
null,
Atom.findOrCreateUnicodeAtom(propName),
JavaScriptTypes.Root));
Assert.assertTrue(
"global " + propName + " should exist", hg.hasEdge(GlobalVertex.instance(), propKey));
System.err.println("heap graph models instruction " + inst);
} else if (inst instanceof JavaScriptInvoke) {
int vn = ((JavaScriptInvoke) inst).getReceiver();
Set<Pair<CGNode, NewSiteReference>> fbPrototypes =
getFbPrototypes(fbPA, hg, fbCG, node, vn);
Set<Pair<CGNode, NewSiteReference>> propPrototypes =
getPropPrototypes(propPA, propCG, node, vn);
Assert.assertTrue(
"should have prototype overlap for "
+ fbPrototypes
+ " and "
+ propPrototypes
+ " at "
+ inst,
(fbPrototypes.isEmpty() && propPrototypes.isEmpty())
|| !Collections.disjoint(fbPrototypes, propPrototypes));
}
}
}
for (InstanceKey k : fbPA.getInstanceKeys()) {
k.getCreationSites(fbCG);
for (String f : new String[] {"__proto__", "prototype"}) {
boolean dump = false;
PointerKey pointerKeyForInstanceField =
fbPA.getHeapModel()
.getPointerKeyForInstanceField(
k,
new AstDynamicField(
false,
k.getConcreteType(),
Atom.findOrCreateUnicodeAtom(f),
JavaScriptTypes.Root));
if (!hg.containsNode(pointerKeyForInstanceField)) {
dump = true;
System.err.println("no " + f + " for " + k + "(" + k.getConcreteType() + ")");
} else if (!hg.getSuccNodes(pointerKeyForInstanceField).hasNext()) {
dump = true;
System.err.println("empty " + f + " for " + k + "(" + k.getConcreteType() + ")");
}
if (dump) {
for (Pair<CGNode, NewSiteReference> cs :
Iterator2Iterable.make(k.getCreationSites(fbCG))) {
System.err.println(cs);
}
}
}
}
}
private static <T extends InstanceKey> Set<Pair<CGNode, NewSiteReference>> getPrototypeSites(
PointerAnalysis<T> fbPA, CallGraph CG, Function<T, Iterator<T>> proto, CGNode node, int vn) {
Set<Pair<CGNode, NewSiteReference>> fbProtos = HashSetFactory.make();
PointerKey fbKey = fbPA.getHeapModel().getPointerKeyForLocal(node, vn);
OrdinalSet<T> fbPointsTo = fbPA.getPointsToSet(fbKey);
for (T o : fbPointsTo) {
for (T p : Iterator2Iterable.make(proto.apply(o))) {
for (Pair<CGNode, NewSiteReference> cs : Iterator2Iterable.make(p.getCreationSites(CG))) {
fbProtos.add(cs);
}
}
}
return fbProtos;
}
private static Set<Pair<CGNode, NewSiteReference>> getFbPrototypes(
PointerAnalysis<ObjectVertex> fbPA,
final HeapGraph<ObjectVertex> hg,
CallGraph CG,
CGNode node,
int vn) {
return getPrototypeSites(
fbPA,
CG,
o -> {
PrototypeFieldVertex proto = new PrototypeFieldVertex(PrototypeField.__proto__, o);
if (hg.containsNode(proto)) {
return new MapIterator<>(hg.getSuccNodes(proto), ObjectVertex.class::cast);
} else {
return EmptyIterator.instance();
}
},
node,
vn);
}
private static Set<Pair<CGNode, NewSiteReference>> getPropPrototypes(
final PointerAnalysis<InstanceKey> fbPA, CallGraph CG, CGNode node, int vn) {
return getPrototypeSites(
fbPA, CG, o -> fbPA.getPointsToSet(new TransitivePrototypeKey(o)).iterator(), node, vn);
}
private void testPageUserCodeEquivalent(URL page) throws WalaException, CancelException {
final String name =
page.getFile()
.substring(page.getFile().lastIndexOf('/') + 1, page.getFile().lastIndexOf('.'));
testPage(page, nameFilter(name), new CheckPointers());
}
protected Predicate<MethodReference> nameFilter(final String name) {
return t -> {
System.err.println(t + " " + name);
return t.getSelector().equals(AstMethodReference.fnSelector)
&& t.getDeclaringClass().getName().toString().startsWith('L' + name);
};
}
@Test
public void testWindowOnload() throws WalaException, CancelException {
testPageUserCodeEquivalent(getClass().getClassLoader().getResource("pages/windowonload.html"));
}
@Test
public void testObjects() throws IOException, WalaException, CancelException {
testTestScript("tests", "objects.js", nameFilter("tests/objects.js"), new CheckPointers());
}
@Test
public void testInherit() throws IOException, WalaException, CancelException {
testTestScript("tests", "inherit.js", nameFilter("tests/inherit.js"), new CheckPointers());
}
}
| 17,703
| 37.90989
| 104
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestPrototypeCallGraphShape.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.net.URL;
import org.junit.Ignore;
import org.junit.Test;
public abstract class TestPrototypeCallGraphShape extends TestJSCallGraphShape {
private static final Object[][] assertionsForPrototype = new Object[][] {};
@Ignore("reminder that this no longer works with correlation tracking")
@Test
public void testPrototype() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/prototype.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPrototype);
}
}
| 1,203
| 35.484848
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestSimpleCallGraphShape.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.PropertyNameContextSelector;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.core.util.ProgressMaster;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.tests.util.SlowTests;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.NullProgressMonitor;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.Iterator2Collection;
import java.io.IOException;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
public abstract class TestSimpleCallGraphShape extends TestJSCallGraphShape {
protected static final Object[][] assertionsForArgs =
new Object[][] {
new Object[] {ROOT, new String[] {"args.js"}},
new Object[] {"args.js", new String[] {"args.js/a"}},
new Object[] {"args.js/a", new String[] {"args.js/x", "args.js/y"}}
};
@Test
public void testArgs()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "args.js");
verifyGraphAssertions(CG, assertionsForArgs);
}
protected static final Object[][] assertionsForSimple =
new Object[][] {
new Object[] {ROOT, new String[] {"simple.js"}},
new Object[] {
"simple.js",
new String[] {
"simple.js/bad",
"simple.js/silly",
"simple.js/fib",
"simple.js/stranger",
"simple.js/trivial",
"simple.js/rubbish",
"simple.js/weirder"
}
},
new Object[] {"simple.js/trivial", new String[] {"simple.js/trivial/inc"}},
new Object[] {
"simple.js/rubbish",
new String[] {"simple.js/weirder", "simple.js/stranger", "simple.js/rubbish"}
},
new Object[] {"simple.js/fib", new String[] {"simple.js/fib"}},
new Object[] {"simple.js/weirder", new String[] {"prologue.js/Math_abs"}}
};
@Test
public void testSimple()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "simple.js");
verifyGraphAssertions(CG, assertionsForSimple);
}
private static final Object[][] assertionsForObjects =
new Object[][] {
new Object[] {ROOT, new String[] {"objects.js"}},
new Object[] {
"objects.js",
new String[] {"objects.js/objects_are_fun", "objects.js/other", "objects.js/something"}
},
new Object[] {
"objects.js/other",
new String[] {"objects.js/something", "objects.js/objects_are_fun/nothing"}
},
new Object[] {
"objects.js/objects_are_fun", new String[] {"objects.js/other", "objects.js/whatever"}
}
};
@Test
public void testObjects()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "objects.js");
verifyGraphAssertions(CG, assertionsForObjects);
}
private static final Object[][] cfgAssertionsForInherit =
new Object[][] {
new Object[] {
"ctor:inherit.js/objectMasquerading/Rectangle",
new int[][] {{1, 7}, {2}, {3, 7}, {4, 7}, {5, 6}, {7}, {7}}
},
new Object[] {
"ctor:inherit.js/sharedClassObject/Rectangle",
new int[][] {{1, 7}, {2}, {3, 7}, {4, 7}, {5, 6}, {7}, {7}}
}
};
private static final Object[][] assertionsForInherit =
new Object[][] {
new Object[] {ROOT, new String[] {"inherit.js"}},
new Object[] {
"inherit.js",
new String[] {
"inherit.js/objectMasquerading",
"inherit.js/objectMasquerading/Rectangle/area",
"inherit.js/Polygon/shape",
"inherit.js/sharedClassObject",
"inherit.js/sharedClassObject/Rectangle/area"
}
},
new Object[] {
"inherit.js/objectMasquerading",
new String[] {"ctor:inherit.js/objectMasquerading/Rectangle"}
},
new Object[] {
"ctor:inherit.js/objectMasquerading/Rectangle",
new String[] {"inherit.js/objectMasquerading/Rectangle"}
},
new Object[] {
"inherit.js/objectMasquerading/Rectangle", new String[] {"inherit.js/Polygon"}
},
new Object[] {
"inherit.js/sharedClassObject",
new String[] {"ctor:inherit.js/sharedClassObject/Rectangle"}
},
new Object[] {
"ctor:inherit.js/sharedClassObject/Rectangle",
new String[] {"inherit.js/sharedClassObject/Rectangle"}
}
};
@Test
public void testInherit()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "inherit.js");
verifyGraphAssertions(CG, assertionsForInherit);
verifyCFGAssertions(CG, cfgAssertionsForInherit);
}
private static final Object[][] assertionsForNewfn =
new Object[][] {
new Object[] {ROOT, new String[] {"newfn.js"}},
new Object[] {
"newfn.js",
new String[] {
"suffix:ctor$1/_fromctor", "suffix:ctor$2/_fromctor", "suffix:ctor$3/_fromctor"
}
}
};
@Test
public void testNewfn()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "newfn.js");
verifyGraphAssertions(CG, assertionsForNewfn);
}
private static final Object[][] assertionsForControlflow =
new Object[][] {
new Object[] {ROOT, new String[] {"control-flow.js"}},
new Object[] {
"control-flow.js",
new String[] {
"control-flow.js/testSwitch",
"control-flow.js/testDoWhile",
"control-flow.js/testWhile",
"control-flow.js/testFor",
"control-flow.js/testReturn"
}
}
};
@Test
public void testControlflow()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "control-flow.js");
verifyGraphAssertions(CG, assertionsForControlflow);
}
private static final Object[][] assertionsForMoreControlflow =
new Object[][] {
new Object[] {ROOT, new String[] {"more-control-flow.js"}},
new Object[] {
"more-control-flow.js",
new String[] {
"more-control-flow.js/testSwitch",
"more-control-flow.js/testIfConvertedSwitch",
"more-control-flow.js/testDoWhile",
"more-control-flow.js/testWhile",
"more-control-flow.js/testFor",
"more-control-flow.js/testReturn"
}
}
};
@Test
public void testMoreControlflow()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "more-control-flow.js");
verifyGraphAssertions(CG, assertionsForMoreControlflow);
}
private static final Object[][] assertionsForForin =
new Object[][] {
new Object[] {ROOT, new String[] {"forin.js"}},
new Object[] {"forin.js", new String[] {"forin.js/testForIn"}},
new Object[] {
"forin.js/testForIn", new String[] {"forin.js/testForIn1", "forin.js/testForIn2"}
}
};
@Test
public void testForin()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "forin.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForForin);
}
private static final Object[][] assertionsForSimpleLexical =
new Object[][] {
new Object[] {ROOT, new String[] {"simple-lexical.js"}},
new Object[] {"simple-lexical.js", new String[] {"simple-lexical.js/outer"}},
new Object[] {
"simple-lexical.js/outer",
new String[] {
"simple-lexical.js/outer/indirect",
"simple-lexical.js/outer/inner",
"simple-lexical.js/outer/inner2",
"simple-lexical.js/outer/inner3"
}
},
new Object[] {
"simple-lexical.js/outer/inner2",
new String[] {"simple-lexical.js/outer/inner", "simple-lexical.js/outer/inner3"}
},
new Object[] {
"simple-lexical.js/outer/indirect",
new String[] {"simple-lexical.js/outer/inner", "simple-lexical.js/outer/inner3"}
}
};
@Test
public void testSimpleLexical()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "simple-lexical.js");
verifyGraphAssertions(CG, assertionsForSimpleLexical);
}
@Test
public void testRecursiveLexical()
throws IOException, IllegalArgumentException, CancelException, WalaException {
// just checking that we have a sufficient bailout to ensure termination
JSCallGraphBuilderUtil.makeScriptCG("tests", "recursive_lexical.js");
}
private static final Object[][] assertionsForLexicalMultiple =
new Object[][] {
new Object[] {ROOT, new String[] {"lexical_multiple_calls.js"}},
new Object[] {"suffix:lexical_multiple_calls.js", new String[] {"suffix:reachable1"}},
new Object[] {"suffix:lexical_multiple_calls.js", new String[] {"suffix:reachable2"}}
};
@Test
public void testLexicalMultiple()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "lexical_multiple_calls.js");
verifyGraphAssertions(CG, assertionsForLexicalMultiple);
}
private static final Object[][] assertionsForTry =
new Object[][] {
new Object[] {ROOT, new String[] {"try.js"}},
new Object[] {
"try.js", new String[] {"try.js/tryCatch", "try.js/tryFinally", "try.js/tryCatchFinally"}
},
new Object[] {
"try.js/tryCatch", new String[] {"try.js/targetOne", "try.js/targetTwo", "try.js/two"}
},
new Object[] {
"try.js/tryFinally", new String[] {"try.js/targetOne", "try.js/targetTwo", "try.js/two"}
},
new Object[] {
"try.js/tryCatchFinally",
new String[] {"try.js/targetOne", "try.js/targetTwo", "try.js/three", "try.js/two"}
},
new Object[] {
"try.js/tryCatchTwice",
new String[] {"try.js/targetOne", "try.js/targetTwo", "try.js/three", "try.js/two"}
},
new Object[] {"try.js/testRet", new String[] {"try.js/three", "try.js/two"}}
};
@Test
public void testTry()
throws IOException, IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "try.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean x = CAstCallGraphUtil.AVOID_DUMP;
CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(
(SSAContextInterpreter) B.getContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = x;
verifyGraphAssertions(CG, assertionsForTry);
}
private static final Object[][] assertionsForStringOp =
new Object[][] {
new Object[] {ROOT, new String[] {"string-op.js"}},
new Object[] {"string-op.js", new String[] {"string-op.js/getOp", "string-op.js/plusNum"}}
};
@Test
public void testStringOp()
throws IOException, IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "string-op.js");
B.getOptions().setTraceStringConstants(true);
CallGraph CG = B.makeCallGraph(B.getOptions());
verifyGraphAssertions(CG, assertionsForStringOp);
}
private static final Object[][] assertionsForUpward =
new Object[][] {
new Object[] {ROOT, new String[] {"upward.js"}},
new Object[] {
"upward.js",
new String[] {
"upward.js/Obj/setit", "upward.js/Obj/getit", "upward.js/tester1", "upward.js/tester2"
}
}
};
@Test
public void testUpward()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "upward.js");
verifyGraphAssertions(CG, assertionsForUpward);
}
private static final Object[][] assertionsForStringPrims =
new Object[][] {
new Object[] {ROOT, new String[] {"string-prims.js"}},
new Object[] {
"string-prims.js",
new String[] {
"prologue.js/String_prototype_split", "prologue.js/String_prototype_toUpperCase"
}
}
};
@Test
public void testStringPrims()
throws IOException, IllegalArgumentException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "string-prims.js");
B.getOptions().setTraceStringConstants(true);
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForStringPrims);
}
private static final Object[][] assertionsForNested =
new Object[][] {
new Object[] {ROOT, new String[] {"nested.js"}},
new Object[] {
"nested.js", new String[] {"nested.js/f", "nested.js/f/ff", "nested.js/f/ff/fff"}
}
};
@Test
public void testNested()
throws IOException, IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "nested.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
verifyGraphAssertions(CG, assertionsForNested);
}
private static final Object[][] assertionsForInstanceof =
new Object[][] {new Object[] {ROOT, new String[] {"instanceof.js"}}};
@Test
public void testInstanceof()
throws IOException, IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "instanceof.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
verifyGraphAssertions(CG, assertionsForInstanceof);
}
/*
* private static final Object[][] assertionsForWith = new Object[][] { new
* Object[] { ROOT, new String[] { "with.js" } } };
*
* @Test public void testWith() throws IOException, IllegalArgumentException,
* CancelException { PropagationCallGraphBuilder B =
* Util.makeScriptCGBuilder("tests", "with.js"); CallGraph CG =
* B.makeCallGraph(B.getOptions()); verifyGraphAssertions(CG,
* assertionsForWith); }
*/
@Test
public void testCrash1()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "crash1.js");
verifyGraphAssertions(CG, null);
}
@Test
public void testCrash2()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "crash2.js");
verifyGraphAssertions(CG, null);
}
@Test
public void testLexicalCtor()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "lexical-ctor.js");
verifyGraphAssertions(CG, null);
}
private static final Object[][] assertionsForMultivar =
new Object[][] {
new Object[] {ROOT, new String[] {"multivar.js"}},
new Object[] {
"multivar.js", new String[] {"multivar.js/a", "multivar.js/bf", "multivar.js/c"}
}
};
@Test
public void testMultivar()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "multivar.js");
verifyGraphAssertions(CG, assertionsForMultivar);
}
private static final Object[][] assertionsForPrototypeContamination =
new Object[][] {
new Object[] {ROOT, new String[] {"prototype_contamination_bug.js"}},
new Object[] {"suffix:test1", new String[] {"suffix:foo_of_A"}},
new Object[] {"suffix:test2", new String[] {"suffix:foo_of_B"}}
};
@Test
public void testProtoypeContamination()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "prototype_contamination_bug.js");
verifyGraphAssertions(CG, assertionsForPrototypeContamination);
verifyNoEdges(CG, "suffix:test1", "suffix:foo_of_B");
verifyNoEdges(CG, "suffix:test2", "suffix:foo_of_A");
}
@Test
@Category(SlowTests.class)
public void testStackOverflowOnSsaConversionBug()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "stack_overflow_on_ssa_conversion.js");
// all we need is for it to finish building CG successfully.
}
@Test
public void testExtJSSwitch()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "extjs_switch.js");
// all we need is for it to finish building CG successfully.
}
@Test
public void testFunctionDotCall()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph cg = JSCallGraphBuilderUtil.makeScriptCG("tests", "function_call.js");
for (CGNode n : cg) {
if (n.getMethod().getName().toString().equals("call4")) {
Assert.assertEquals(2, cg.getSuccNodeCount(n));
// ugh
List<CGNode> succs = Iterator2Collection.toList(cg.getSuccNodes(n));
Assert.assertEquals(
"[Node: <Code body of function Lfunction_call.js/foo> Context: Everywhere, Node: <Code body of function Lfunction_call.js/bar> Context: Everywhere]",
succs.toString());
}
}
}
private static final Object[][] assertionsForFunctionApply =
new Object[][] {
new Object[] {ROOT, new String[] {"function_apply.js"}},
new Object[] {"suffix:function_apply.js", new String[] {"suffix:theOne"}},
new Object[] {"suffix:function_apply.js", new String[] {"suffix:theTwo"}}
};
@Test
public void testFunctionDotApply()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "function_apply.js");
verifyGraphAssertions(CG, assertionsForFunctionApply);
}
private static final Object[][] assertionsForFunctionApply2 =
new Object[][] {
new Object[] {ROOT, new String[] {"function_apply2.js"}},
new Object[] {"suffix:function_apply2.js", new String[] {"suffix:theThree"}}
};
@Test
public void testFunctionDotApply2()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "function_apply2.js");
verifyGraphAssertions(CG, assertionsForFunctionApply2);
}
private static final Object[][] assertionsForFunctionApply3 =
new Object[][] {
new Object[] {ROOT, new String[] {"function_apply3.js"}},
new Object[] {"suffix:apply", new String[] {"suffix:foo"}}
};
@Test
public void testFunctionDotApply3()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "function_apply3.js");
verifyGraphAssertions(CG, assertionsForFunctionApply3);
}
private static final Object[][] assertionsForWrap1 =
new Object[][] {
new Object[] {ROOT, new String[] {"wrap1.js"}},
new Object[] {"suffix:wrap1.js", new String[] {"suffix:i_am_reachable"}}
};
@Test
public void testWrap1()
throws IllegalArgumentException, IOException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "wrap1.js");
verifyGraphAssertions(CG, assertionsForWrap1);
}
private static final Object[][] assertionsForWrap2 =
new Object[][] {
new Object[] {ROOT, new String[] {"wrap2.js"}},
new Object[] {"suffix:wrap2.js", new String[] {"suffix:i_am_reachable"}}
};
@Test
public void testWrap2()
throws IllegalArgumentException, IOException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "wrap2.js");
verifyGraphAssertions(CG, assertionsForWrap2);
}
private static final Object[][] assertionsForWrap3 =
new Object[][] {
new Object[] {ROOT, new String[] {"wrap3.js"}},
new Object[] {"suffix:wrap3.js", new String[] {"suffix:i_am_reachable"}}
};
@Test
public void testWrap3()
throws IllegalArgumentException, IOException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "wrap3.js");
verifyGraphAssertions(CG, assertionsForWrap3);
}
private static final Object[][] assertionsForComplexCall =
new Object[][] {
new Object[] {ROOT, new String[] {"complex_call.js"}},
new Object[] {"suffix:call.js", new String[] {"suffix:f3"}}
};
@Test
public void testComplexCall()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "complex_call.js");
for (CGNode nd : CG) System.out.println(nd);
verifyGraphAssertions(CG, assertionsForComplexCall);
}
private static final Object[][] assertionsForGlobalObj =
new Object[][] {
new Object[] {ROOT, new String[] {"global_object.js"}},
new Object[] {"suffix:global_object.js", new String[] {"suffix:biz"}}
};
@Test
public void testGlobalObjPassing()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "global_object.js");
verifyGraphAssertions(CG, assertionsForGlobalObj);
}
private static final Object[][] assertionsForGlobalObj2 =
new Object[][] {
new Object[] {ROOT, new String[] {"global_object2.js"}},
new Object[] {"suffix:global_object2.js", new String[] {"suffix:foo"}}
};
@Test
public void testGlobalObj2()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "global_object2.js");
verifyGraphAssertions(CG, assertionsForGlobalObj2);
}
private static final Object[][] assertionsForReturnThis =
new Object[][] {
new Object[] {ROOT, new String[] {"return_this.js"}},
new Object[] {"suffix:return_this.js", new String[] {"suffix:foo"}},
new Object[] {"suffix:return_this.js", new String[] {"suffix:bar"}}
};
@Test
public void testReturnThis()
throws IOException, IllegalArgumentException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "return_this.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForReturnThis);
}
private static final Object[][] assertionsForReturnThis2 =
new Object[][] {
new Object[] {ROOT, new String[] {"return_this2.js"}},
new Object[] {"suffix:return_this2.js", new String[] {"suffix:A"}},
new Object[] {"suffix:return_this2.js", new String[] {"suffix:foo"}},
new Object[] {"suffix:return_this2.js", new String[] {"suffix:test1"}},
new Object[] {"suffix:return_this2.js", new String[] {"suffix:test2"}},
new Object[] {"suffix:test1", new String[] {"suffix:bar1"}},
new Object[] {"suffix:test2", new String[] {"suffix:bar2"}}
};
// when using the ObjectSensitivityContextSelector, we additionally know that test1 does not call
// bar2,
// and test2 does not call bar1
@Test
public void testReturnThis2()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "return_this2.js");
verifyGraphAssertions(CG, assertionsForReturnThis2);
}
private static final Object[][] assertionsForArguments =
new Object[][] {
new Object[] {ROOT, new String[] {"arguments.js"}},
new Object[] {"suffix:arguments.js", new String[] {"suffix:f"}},
new Object[] {
"suffix:f",
new String[] {
"!suffix:g1", "!suffix:g2", "suffix:g3",
}
}
};
@Test
public void testArguments()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "arguments.js");
verifyGraphAssertions(CG, assertionsForArguments);
}
private static final Object[][] assertionsForFunctionIsAFunction =
new Object[][] {
new Object[] {ROOT, new String[] {"Function_is_a_function.js"}},
new Object[] {
"suffix:Function_is_a_function.js", new String[] {"suffix:Function_prototype_call"}
}
};
@Test
public void testFunctionIsAFunction()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "Function_is_a_function.js");
verifyGraphAssertions(CG, assertionsForFunctionIsAFunction);
}
private static final Object[][] assertionsForLexicalBroken =
new Object[][] {
new Object[] {ROOT, new String[] {"lexical_broken.js"}},
new Object[] {"suffix:lexical_broken.js", new String[] {"suffix:f"}},
new Object[] {"suffix:f", new String[] {"suffix:g"}}
};
@Test
public void testLexicalBroken()
throws IOException, IllegalArgumentException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "lexical_broken.js");
verifyGraphAssertions(CG, assertionsForLexicalBroken);
}
@Test
public void testDeadPhi()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "dead_phi.js");
}
private static final Object[][] assertionsForScopingOverwriteFunction =
new Object[][] {
new Object[] {ROOT, new String[] {"scoping_test.js"}},
new Object[] {"suffix:scoping_test.js", new String[] {"suffix:i_am_reachable"}}
};
@Test
public void testScopingOverwriteFunction()
throws IllegalArgumentException, IOException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "scoping_test.js");
verifyGraphAssertions(CG, assertionsForScopingOverwriteFunction);
}
private static final Object[][] assertionsForNestedParamAssign =
new Object[][] {
new Object[] {ROOT, new String[] {"nested_assign_to_param.js"}},
new Object[] {"suffix:nested_assign_to_param.js", new String[] {"suffix:i_am_reachable"}}
};
@Test
public void testNestedAssignToParam()
throws IllegalArgumentException, IOException, CancelException, WalaException {
CallGraph CG = JSCallGraphBuilderUtil.makeScriptCG("tests", "nested_assign_to_param.js");
verifyGraphAssertions(CG, assertionsForNestedParamAssign);
}
private static final Object[][] assertionsForDispatch =
new Object[][] {
new Object[] {ROOT, new String[] {"dispatch.js"}},
new Object[] {
"dispatch.js", new String[] {"dispatch.js/left_outer", "dispatch.js/right_outer"}
},
new Object[] {"dispatch.js/left_outer", new String[] {"dispatch.js/left_inner"}},
new Object[] {"dispatch.js/right_outer", new String[] {"dispatch.js/right_inner"}}
};
@Test
public void testDispatch()
throws IOException, IllegalArgumentException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "dispatch.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForDispatch);
}
private static final Object[][] assertionsForDispatchSameTarget =
new Object[][] {
new Object[] {ROOT, new String[] {"dispatch_same_target.js"}},
new Object[] {"dispatch_same_target.js/f3", new String[] {"dispatch_same_target.js/f4"}}
};
@Test
public void testDispatchSameTarget()
throws IOException, IllegalArgumentException, CancelException, WalaException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "dispatch_same_target.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
// JSCallGraphUtil.dumpCG(B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForDispatchSameTarget);
}
private static final Object[][] assertionsForForInPrototype =
new Object[][] {
new Object[] {ROOT, new String[] {"for_in_prototype.js"}},
new Object[] {
"for_in_prototype.js",
new String[] {"suffix:A", "suffix:reachable", "suffix:also_reachable"}
}
};
@Test
public void testForInPrototype()
throws IllegalArgumentException, IOException, CancelException, WalaException {
CallGraph cg = JSCallGraphBuilderUtil.makeScriptCG("tests", "for_in_prototype.js");
verifyGraphAssertions(cg, assertionsForForInPrototype);
}
private static final Object[][] assertionsForArrayIndexConv =
new Object[][] {
new Object[] {ROOT, new String[] {"array_index_conv.js"}},
new Object[] {
"array_index_conv.js",
new String[] {
"suffix:reachable1", "suffix:reachable2", "suffix:reachable3", "suffix:reachable4"
}
}
};
@Test
public void testArrayIndexConv()
throws IllegalArgumentException, IOException, CancelException, WalaException {
PropagationCallGraphBuilder b =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "array_index_conv.js");
CallGraph cg = b.makeCallGraph(b.getOptions());
verifyGraphAssertions(cg, assertionsForArrayIndexConv);
}
private static final Object[][] assertionsForArrayIndexConv2 =
new Object[][] {
new Object[] {ROOT, new String[] {"array_index_conv2.js"}},
new Object[] {"array_index_conv2.js", new String[] {"suffix:invokeOnA"}},
new Object[] {
"suffix:invokeOnA",
new String[] {"suffix:reachable", "suffix:also_reachable", "suffix:reachable_too"}
}
};
@Test
public void testArrayIndexConv2()
throws IllegalArgumentException, IOException, CancelException, WalaException {
PropagationCallGraphBuilder b =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "array_index_conv2.js");
b.setContextSelector(
new PropertyNameContextSelector(b.getAnalysisCache(), b.getContextSelector()));
CallGraph cg = b.makeCallGraph(b.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
// JSCallGraphUtil.dumpCG(b.getPointerAnalysis(), cg);
verifyGraphAssertions(cg, assertionsForArrayIndexConv2);
}
private static final Object[][] assertionsForDateProperty =
new Object[][] {
new Object[] {ROOT, new String[] {"date-property.js"}},
new Object[] {"date-property.js", new String[] {"suffix:_fun"}}
};
@Test
public void testDateAsProperty()
throws IllegalArgumentException, IOException, CancelException, WalaException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "date-property.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
// JSCallGraphUtil.dumpCG(B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForDateProperty);
}
private static final Object[][] assertionsForDeadCode =
new Object[][] {
new Object[] {ROOT, new String[] {"dead.js"}},
new Object[] {"dead.js", new String[] {"suffix:twoReturns"}}
};
@Test
public void testDeadCode()
throws IllegalArgumentException, IOException, CancelException, WalaException {
PropagationCallGraphBuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "dead.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
// JSCallGraphUtil.AVOID_DUMP = false;
// JSCallGraphUtil.dumpCG(B.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForDeadCode);
}
private static final Object[][] assertionsForShadow =
new Object[][] {
new Object[] {ROOT, new String[] {"shadow_test.js"}},
new Object[] {"shadow_test.js", new String[] {"shadow_test.js/test"}},
new Object[] {"shadow_test.js/test", new String[] {"shadow_test.js/bad"}},
new Object[] {"shadow_test.js/test", new String[] {"shadow_test.js/global_bad"}}
};
@Test
public void testShadow()
throws IOException, WalaException, IllegalArgumentException, CancelException {
JSCFABuilder builder = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "shadow_test.js");
CallGraph cg = builder.makeCallGraph(builder.getOptions());
verifyGraphAssertions(cg, assertionsForShadow);
}
private static final Object[][] assertionsForExtend =
new Object[][] {
new Object[] {ROOT, new String[] {"extend.js"}},
new Object[] {"extend.js", new String[] {"suffix:bar", "!suffix:foo"}}
};
@Test
public void testExtend()
throws IOException, WalaException, IllegalArgumentException, CancelException {
JSCFABuilder builder = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "extend.js");
CallGraph cg = builder.makeCallGraph(builder.getOptions());
verifyGraphAssertions(cg, assertionsForExtend);
}
@Test
public void testDeadCatch()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "dead_catch.js");
}
@Test
public void testUglyLoopCrash()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "ssa-crash.js");
}
@Test
public void testTryFinallyCrash()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "try-finally-crash.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean save = CAstCallGraphUtil.AVOID_DUMP;
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = save;
}
@Test(expected = CallGraphBuilderCancelException.class)
@Category(SlowTests.class)
public void testManyStrings()
throws IllegalArgumentException, IOException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "many-strings.js");
B.getOptions().setTraceStringConstants(true);
IProgressMonitor monitor = ProgressMaster.make(new NullProgressMonitor(), 10000, false);
monitor.beginTask("build CG", 1);
CallGraph CG = B.makeCallGraph(B.getOptions(), monitor);
monitor.done();
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
}
@Test
public void testTutorialExample()
throws IllegalArgumentException, IOException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "tutorial-example.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
// verifyGraphAssertions(CG, assertionsForDateProperty);
}
private static final Object[][] assertionsForLoops =
new Object[][] {
new Object[] {ROOT, new String[] {"loops.js"}},
new Object[] {"loops.js", new String[] {"loops.js/three", "loops.js/four"}}
};
@Ignore("need to fix this. bug from Sukyoung's group")
@Test
public void testLoops()
throws IllegalArgumentException, IOException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "loops.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean x = CAstCallGraphUtil.AVOID_DUMP;
CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = x;
verifyGraphAssertions(CG, assertionsForLoops);
}
private static final Object[][] assertionsForPrimitiveStrings =
new Object[][] {
new Object[] {ROOT, new String[] {"primitive_strings.js"}},
new Object[] {
"primitive_strings.js",
new String[] {"primitive_strings.js/f1", "primitive_strings.js/f1"}
},
new Object[] {
"primitive_strings.js/f2", new String[] {"prologue.js/String_prototype_concat"}
},
new Object[] {
"primitive_strings.js/f1", new String[] {"prologue.js/String_prototype_concat"}
},
};
@Ignore("need to fix this. bug from Sukyoung's group")
@Test
public void testPrimitiveStrings()
throws IllegalArgumentException, IOException, CancelException, WalaException {
SSAPropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "primitive_strings.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean x = CAstCallGraphUtil.AVOID_DUMP;
CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = x;
verifyGraphAssertions(CG, assertionsForPrimitiveStrings);
}
Object[][] renamingAssertions = {
{"rename-example.js/f", new Name[] {new Name(9, 7, "x"), new Name(9, 7, "y")}},
{
"rename-example.js/ff",
new Name[] {new Name(11, 10, "x"), new Name(11, 10, "y"), new Name(11, 10, "z")}
}
};
@Test
public void testRenaming()
throws IOException, WalaException, IllegalArgumentException, CancelException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "rename-example.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
verifyNameAssertions(CG, renamingAssertions);
}
@Test
public void testLexicalCatch()
throws IOException, WalaException, IllegalArgumentException, CancelException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "lexical_catch.js");
B.makeCallGraph(B.getOptions());
// test is just not to crash
}
@Test
public void testThrowCrash()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "badthrow.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean save = CAstCallGraphUtil.AVOID_DUMP;
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = save;
}
@Test
public void testNrWrapperCrash()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "nrwrapper.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean save = CAstCallGraphUtil.AVOID_DUMP;
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = save;
}
@Test
public void testFinallyCrash()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "finallycrash.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean save = CAstCallGraphUtil.AVOID_DUMP;
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = save;
}
@Test
public void testForInExpr()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "for_in_expr.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
boolean save = CAstCallGraphUtil.AVOID_DUMP;
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = save;
}
private static final Object[][] assertionsForComplexFinally =
new Object[][] {
new Object[] {ROOT, new String[] {"complex_finally.js"}},
new Object[] {"complex_finally.js", new String[] {"complex_finally.js/e"}},
new Object[] {
"complex_finally.js/e",
new String[] {
"complex_finally.js/base",
"complex_finally.js/bad",
"complex_finally.js/good",
"complex_finally.js/oo1",
"complex_finally.js/oo2",
}
}
};
@Test
public void testComplexFinally()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCFABuilder B = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "complex_finally.js");
CallGraph CG = B.makeCallGraph(B.getOptions());
verifyGraphAssertions(CG, assertionsForComplexFinally);
boolean save = CAstCallGraphUtil.AVOID_DUMP;
// CAstCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(B.getCFAContextInterpreter(), B.getPointerAnalysis(), CG);
CAstCallGraphUtil.AVOID_DUMP = save;
}
}
| 43,897
| 38.726697
| 161
|
java
|
WALA
|
WALA-master/cast/js/src/testFixtures/java/com/ibm/wala/cast/js/test/TestSimplePageCallGraphShape.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.net.URL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public abstract class TestSimplePageCallGraphShape extends TestJSCallGraphShape {
protected abstract IHtmlParser getParser();
private ExtractingToPredictableFileNames predictable;
@Before
public void setUp() {
predictable = new ExtractingToPredictableFileNames();
}
@After
public void tearDown() {
predictable.close();
}
private static final Object[][] assertionsForPage1 =
new Object[][] {
new Object[] {ROOT, new String[] {"page1.html"}},
new Object[] {"page1.html", new String[] {"page1.html/__WINDOW_MAIN__"}},
new Object[] {
"page1.html/__WINDOW_MAIN__",
new String[] {
"prologue.js/String_prototype_substring",
"prologue.js/String_prototype_indexOf",
"preamble.js/DOMDocument/Document_prototype_write",
"prologue.js/encodeURI"
}
}
};
@Test
public void testPage1() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/page1.html");
assert url != null;
System.err.println("url is " + url);
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage1);
}
private static final Object[][] assertionsForPage2 =
new Object[][] {
new Object[] {ROOT, new String[] {"page2.html"}},
new Object[] {"page2.html", new String[] {"page2.html/__WINDOW_MAIN__"}}
};
@Test
public void testPage2() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/page2.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage2);
}
private static final Object[][] assertionsForPage11 =
new Object[][] {
new Object[] {ROOT, new String[] {"page11.html"}},
new Object[] {"page11.html", new String[] {"page11.html/__WINDOW_MAIN__"}},
new Object[] {
"page11.html/__WINDOW_MAIN__",
new String[] {
"preamble.js/DOMDocument/Document_prototype_createElement",
"preamble.js/DOMNode/Node_prototype_appendChild",
"preamble.js/DOMElement/Element_prototype_setAttribute"
}
}
};
@Test
public void testCrawlPage11() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page11.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage11);
}
private static final Object[][] assertionsForPage11b =
new Object[][] {
new Object[] {ROOT, new String[] {"page11b.html"}},
new Object[] {"page11b.html", new String[] {"page11b.html/__WINDOW_MAIN__"}},
new Object[] {
"page11b.html/__WINDOW_MAIN__",
new String[] {
"preamble.js/DOMDocument/Document_prototype_createElement",
"preamble.js/DOMNode/Node_prototype_appendChild",
"preamble.js/DOMElement/Element_prototype_setAttribute"
}
}
};
@Test
public void testCrawlPage11b() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page11b.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage11b);
}
private static final Object[][] assertionsForPage12 =
new Object[][] {
new Object[] {ROOT, new String[] {"page12.html"}},
new Object[] {"page12.html", new String[] {"page12.html/__WINDOW_MAIN__"}},
new Object[] {
"page12.html/__WINDOW_MAIN__",
new String[] {
"page12.html/__WINDOW_MAIN__/make_node0/make_node3/make_node4/button_onclick"
}
},
new Object[] {
"page12.html/__WINDOW_MAIN__/make_node0/make_node3/make_node4/button_onclick",
new String[] {"page12.html/__WINDOW_MAIN__/callXHR"}
},
new Object[] {
"page12.html/__WINDOW_MAIN__/callXHR",
new String[] {
"preamble.js/DOMDocument/Document_prototype_getElementById",
"preamble.js/XMLHttpRequest/xhr_open",
"preamble.js/XMLHttpRequest/xhr_send"
}
},
new Object[] {
"preamble.js/XMLHttpRequest/xhr_open",
new String[] {"preamble.js/XMLHttpRequest/xhr_orsc_handler"}
},
new Object[] {
"preamble.js/XMLHttpRequest/xhr_send",
new String[] {"preamble.js/XMLHttpRequest/xhr_orsc_handler"}
},
new Object[] {
"preamble.js/XMLHttpRequest/xhr_orsc_handler",
new String[] {"page12.html/__WINDOW_MAIN__/handler"}
},
};
@Test
public void testCrawlPage12() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page12.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage12);
}
private static final Object[][] assertionsForPage13 =
new Object[][] {
new Object[] {ROOT, new String[] {"page13.html"}},
new Object[] {"page13.html", new String[] {"page13.html/__WINDOW_MAIN__"}},
new Object[] {
"page13.html/__WINDOW_MAIN__",
new String[] {
"page13.html/__WINDOW_MAIN__/make_node0/make_node3/make_node4/button_onclick"
}
},
new Object[] {
"page13.html/__WINDOW_MAIN__/make_node0/make_node3/make_node4/button_onclick",
new String[] {"page13.html/__WINDOW_MAIN__/callXHR"}
},
new Object[] {
"page13.html/__WINDOW_MAIN__/callXHR",
new String[] {
"preamble.js/DOMDocument/Document_prototype_getElementById",
"preamble.js/XMLHttpRequest/xhr_open",
"preamble.js/XMLHttpRequest/xhr_setRequestHeader",
"preamble.js/XMLHttpRequest/xhr_send"
}
},
new Object[] {
"preamble.js/XMLHttpRequest/xhr_open",
new String[] {"preamble.js/XMLHttpRequest/xhr_orsc_handler"}
},
new Object[] {
"preamble.js/XMLHttpRequest/xhr_send",
new String[] {"preamble.js/XMLHttpRequest/xhr_orsc_handler"}
},
new Object[] {
"preamble.js/XMLHttpRequest/xhr_orsc_handler",
new String[] {"page13.html/__WINDOW_MAIN__/handler"}
}
};
@Test
public void testCrawlPage13() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page13.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage13);
}
private static final Object[][] assertionsForPage15 =
new Object[][] {
new Object[] {ROOT, new String[] {"page15.html"}},
new Object[] {"page15.html", new String[] {"page15.html/__WINDOW_MAIN__"}},
new Object[] {
"page15.html/__WINDOW_MAIN__",
new String[] {"page15.html/__WINDOW_MAIN__/make_node0/make_node3/body_onload"}
},
new Object[] {
"page15.html/__WINDOW_MAIN__/make_node0/make_node3/body_onload",
new String[] {"page15.html/__WINDOW_MAIN__/changeUrls"}
}
};
@Test
public void testCrawlPage15() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page15.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage15);
}
private static final Object[][] assertionsForPage16 =
new Object[][] {
new Object[] {ROOT, new String[] {"page16.html"}},
new Object[] {"page16.html", new String[] {"page16.html/__WINDOW_MAIN__"}},
new Object[] {
"page16.html/__WINDOW_MAIN__",
new String[] {"page16.html/__WINDOW_MAIN__/make_node0/make_node3/make_node4/a_onclick"}
},
new Object[] {
"page16.html/__WINDOW_MAIN__/make_node0/make_node3/make_node4/a_onclick",
new String[] {"page16.html/__WINDOW_MAIN__/changeUrls"}
}
};
@Test
public void testCrawlPage16() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page16.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage16);
}
private static final Object[][] assertionsForPage17 =
new Object[][] {
new Object[] {ROOT, new String[] {"page17.html"}},
new Object[] {"page17.html", new String[] {"page17.html/__WINDOW_MAIN__"}},
new Object[] {
"page17.html/__WINDOW_MAIN__", new String[] {"page17.html/__WINDOW_MAIN__/loadScript"}
},
new Object[] {
"preamble.js", new String[] {"page17.html/__WINDOW_MAIN__/loadScript/_page17_handler"}
},
new Object[] {
"page17.html/__WINDOW_MAIN__/loadScript/_page17_handler",
new String[] {"page17.html/__WINDOW_MAIN__/callFunction"}
},
new Object[] {
"page17.html/__WINDOW_MAIN__/callFunction", new String[] {"suffix:changeUrls"}
}
};
@Test
public void testCrawlPage17() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl/page17.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForPage17);
}
private static final Object[][] assertionsForApolloExample =
new Object[][] {
new Object[] {ROOT, new String[] {"apollo-example.html"}},
new Object[] {"apollo-example.html", new String[] {"apollo-example.html/__WINDOW_MAIN__"}},
new Object[] {
"apollo-example.html/__WINDOW_MAIN__",
new String[] {"apollo-example.html/__WINDOW_MAIN__/signon"}
},
new Object[] {
"apollo-example.html/__WINDOW_MAIN__/signon",
new String[] {"preamble.js/DOMWindow/window_open"}
}
};
@Test
public void testApolloExample() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/apollo-example.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForApolloExample);
}
@Test
public void testNojs() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/nojs.html");
// all we need is for it to finish building CG successfully.
JSCallGraphBuilderUtil.makeHTMLCG(url);
}
@Test
public void testPage4() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/page4.html");
JSCallGraphBuilderUtil.makeHTMLCG(url);
}
private static final Object[][] sourceAssertionsForList =
new Object[][] {
new Object[] {"suffix:update_display", "list.html#2", 4, 13},
new Object[] {"suffix:update_with_item", "list.html#2", 9, 11},
new Object[] {"suffix:add_item", "list.html#2", 15, 20},
new Object[] {"suffix:collection", "pages/collection.js", 2, 14},
new Object[] {"suffix:collection_add", "pages/collection.js", 7, 13},
new Object[] {"suffix:forall_elt", "pages/collection.js", 9, 12},
new Object[] {"suffix:forall_base", "pages/collection.js", 4, 4}
};
@Test
public void testList() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/list.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
// JSCallGraphBuilderUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
verifySourceAssertions(CG, sourceAssertionsForList);
}
@Test
public void testIframeTest2() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/iframeTest2.html");
JSCallGraphBuilderUtil.makeHTMLCG(url);
}
private static final Object[][] assertionsForWindowx =
new Object[][] {
new Object[] {ROOT, new String[] {"windowx.html"}},
new Object[] {"windowx.html", new String[] {"windowx.html/__WINDOW_MAIN__"}},
new Object[] {
"windowx.html/__WINDOW_MAIN__",
new String[] {"windowx.html/__WINDOW_MAIN__/_f2", "windowx.html/__WINDOW_MAIN__/_f4"}
},
new Object[] {
"windowx.html/__WINDOW_MAIN__/_f2", new String[] {"windowx.html/__WINDOW_MAIN__/_f1"}
},
new Object[] {
"windowx.html/__WINDOW_MAIN__/_f4", new String[] {"windowx.html/__WINDOW_MAIN__/_f3"}
}
};
@Test
public void testWindowx() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/windowx.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForWindowx);
}
private static final Object[][] assertionsForWindowOnload =
new Object[][] {
new Object[] {ROOT, new String[] {"windowonload.html"}},
new Object[] {"windowonload.html", new String[] {"windowonload.html/__WINDOW_MAIN__"}},
new Object[] {
"windowonload.html/__WINDOW_MAIN__",
new String[] {"windowonload.html/__WINDOW_MAIN__/onload_handler"}
},
};
@Test
public void testWindowOnload() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/windowonload.html");
JSCFABuilder builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url);
CallGraph CG = builder.makeCallGraph(builder.getOptions());
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
verifyGraphAssertions(CG, assertionsForWindowOnload);
}
public static final Object[][] assertionsForSkeleton =
new Object[][] {
new Object[] {ROOT, new String[] {"skeleton.html"}},
new Object[] {"skeleton.html", new String[] {"skeleton.html/__WINDOW_MAIN__"}},
new Object[] {
"skeleton.html/__WINDOW_MAIN__", new String[] {"skeleton.html/__WINDOW_MAIN__/dollar"}
},
new Object[] {
"skeleton.html/__WINDOW_MAIN__/dollar",
new String[] {"skeleton.html/__WINDOW_MAIN__/bad_guy"}
},
new Object[] {
"skeleton.html/__WINDOW_MAIN__/bad_guy",
new String[] {"skeleton.html/__WINDOW_MAIN__/dollar"}
},
};
@Test
public void testSkeleton() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/skeleton.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
verifyGraphAssertions(CG, assertionsForSkeleton);
}
public static final Object[][] assertionsForSkeleton2 =
new Object[][] {
new Object[] {ROOT, new String[] {"skeleton2.html"}},
new Object[] {"skeleton2.html", new String[] {"skeleton2.html/__WINDOW_MAIN__"}},
new Object[] {
"skeleton2.html/__WINDOW_MAIN__", new String[] {"skeleton2.html/__WINDOW_MAIN__/dollar"}
},
new Object[] {
"skeleton2.html/__WINDOW_MAIN__/dollar",
new String[] {"ctor:skeleton2.html/__WINDOW_MAIN__/dollar_init"}
},
new Object[] {
"ctor:skeleton2.html/__WINDOW_MAIN__/dollar_init",
new String[] {"skeleton2.html/__WINDOW_MAIN__/dollar_init"}
},
new Object[] {
"skeleton2.html/__WINDOW_MAIN__/dollar_init",
new String[] {"skeleton2.html/__WINDOW_MAIN__/bad_guy"}
},
new Object[] {
"skeleton2.html/__WINDOW_MAIN__/bad_guy",
new String[] {"skeleton2.html/__WINDOW_MAIN__/dollar"}
},
};
@Test
public void testSkeleton2() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/skeleton2.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url);
System.err.println(CG);
verifyGraphAssertions(CG, assertionsForSkeleton2);
}
/*
@Test public void testJQuery() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/jquery.html");
CallGraph CG = Util.makeHTMLCG(url);
}
*/
/*
@Test public void testDojoTest() throws IllegalArgumentException, IOException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/dojo/test.html");
CallGraph CG = Util.makeHTMLCG(url);
verifyGraphAssertions(CG, null);
}
*/
}
| 18,221
| 39.225166
| 113
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/analysis/typeInference/AstTypeInference.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.analysis.typeInference;
import com.ibm.wala.analysis.typeInference.ConeType;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.analysis.typeInference.TypeInference;
import com.ibm.wala.cast.ir.ssa.AstAssertInstruction;
import com.ibm.wala.cast.ir.ssa.AstEchoInstruction;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstInstructionVisitor;
import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction;
import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cast.ir.ssa.AstLexicalWrite;
import com.ibm.wala.cast.ir.ssa.AstPropertyRead;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction;
import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction;
import com.ibm.wala.ssa.IR;
public abstract class AstTypeInference extends TypeInference {
private final TypeAbstraction booleanType;
protected class AstTypeOperatorFactory extends TypeOperatorFactory
implements AstInstructionVisitor {
@Override
public void visitPropertyRead(AstPropertyRead inst) {
result = new DeclaredTypeOperator(new ConeType(cha.getRootClass()));
}
@Override
public void visitPropertyWrite(AstPropertyWrite inst) {}
@Override
public void visitAstLexicalRead(AstLexicalRead inst) {
result = new DeclaredTypeOperator(new ConeType(cha.getRootClass()));
}
@Override
public void visitAstLexicalWrite(AstLexicalWrite inst) {}
@Override
public void visitAstGlobalRead(AstGlobalRead instruction) {
result = new DeclaredTypeOperator(new ConeType(cha.getRootClass()));
}
@Override
public void visitAstGlobalWrite(AstGlobalWrite instruction) {}
@Override
public void visitAssert(AstAssertInstruction instruction) {}
@Override
public void visitEachElementGet(EachElementGetInstruction inst) {
result = new DeclaredTypeOperator(new ConeType(cha.getRootClass()));
}
@Override
public void visitEachElementHasNext(EachElementHasNextInstruction inst) {}
@Override
public void visitIsDefined(AstIsDefinedInstruction inst) {
if (doPrimitives) {
result = new DeclaredTypeOperator(booleanType);
}
}
@Override
public void visitEcho(AstEchoInstruction inst) {}
}
public AstTypeInference(IR ir, TypeAbstraction booleanType, boolean doPrimitives) {
super(ir, doPrimitives);
this.booleanType = booleanType;
}
@Override
protected void initialize() {
init(ir, new TypeVarFactory(), new AstTypeOperatorFactory());
}
}
| 3,040
| 32.054348
| 85
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/ArgumentInstanceContext.java
|
/*
* Copyright (c) 2013 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
public class ArgumentInstanceContext implements Context {
private final Context base;
private final int index;
private final InstanceKey instanceKey;
// to easily identify when an ArgumentInstanceContext is present
public static final ContextKey ID_KEY = new ContextKey() {};
public ArgumentInstanceContext(Context base, int index, InstanceKey instanceKey) {
this.base = base;
this.index = index;
this.instanceKey = instanceKey;
}
@Override
public ContextItem get(ContextKey name) {
/*if(name == ContextKey.RECEIVER && index == 1)
return instanceKey;*/
if (name.equals(ContextKey.PARAMETERS[index]) || name.equals(ID_KEY))
return new FilteredPointerKey.SingleInstanceFilter(instanceKey);
return base.get(name);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + index;
result = prime * result + ((instanceKey == null) ? 0 : instanceKey.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ArgumentInstanceContext other = (ArgumentInstanceContext) obj;
if (base == null) {
if (other.base != null) return false;
} else if (!base.equals(other.base)) return false;
if (index != other.index) return false;
if (instanceKey == null) {
if (other.instanceKey != null) return false;
} else if (!instanceKey.equals(other.instanceKey)) return false;
return true;
}
@Override
public String toString() {
return "ArgumentInstanceContext [base="
+ base
+ ", index="
+ index
+ ", instanceKey="
+ instanceKey
+ ']';
}
}
| 2,527
| 31
| 84
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstCFAPointerKeys.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultPointerKeyFactory;
public class AstCFAPointerKeys extends DelegatingAstPointerKeys {
public AstCFAPointerKeys() {
super(new DefaultPointerKeyFactory());
}
}
| 641
| 29.571429
| 75
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstCallGraph.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.cast.ir.cfg.AstInducedCFG;
import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.util.ConcurrentModificationException;
import java.util.Set;
import java.util.function.Function;
public class AstCallGraph extends ExplicitCallGraph {
public AstCallGraph(IMethod fakeRootClass2, AnalysisOptions options, IAnalysisCacheView cache) {
super(fakeRootClass2, options, cache);
}
public static class AstFakeRoot extends AbstractRootMethod {
public AstFakeRoot(
MethodReference rootMethod,
IClass declaringClass,
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView cache) {
super(rootMethod, declaringClass, cha, options, cache);
}
public AstFakeRoot(
MethodReference rootMethod,
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView cache) {
super(rootMethod, cha, options, cache);
}
@Override
public InducedCFG makeControlFlowGraph(SSAInstruction[] statements) {
return new AstInducedCFG(statements, this, Everywhere.EVERYWHERE);
}
public AstLexicalRead addGlobalRead(TypeReference type, String name) {
AstLexicalRead s = new AstLexicalRead(statements.size(), nextLocal++, null, name, type);
statements.add(s);
return s;
}
}
public abstract static class ScriptFakeRoot extends AstFakeRoot {
public ScriptFakeRoot(
MethodReference rootMethod,
IClass declaringClass,
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView cache) {
super(rootMethod, declaringClass, cha, options, cache);
}
public ScriptFakeRoot(
MethodReference rootMethod,
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView cache) {
super(rootMethod, cha, options, cache);
}
public abstract SSAAbstractInvokeInstruction addDirectCall(
int functionVn, int[] argVns, CallSiteReference callSite);
@Override
public SSANewInstruction addAllocation(TypeReference T) {
if (cha.isSubclassOf(
cha.lookupClass(T),
cha.lookupClass(declaringClass.getClassLoader().getLanguage().getRootType()))) {
int instance = nextLocal++;
NewSiteReference ref = NewSiteReference.make(statements.size(), T);
SSANewInstruction result =
getDeclaringClass()
.getClassLoader()
.getInstructionFactory()
.NewInstruction(statements.size(), instance, ref);
statements.add(result);
return result;
} else {
return super.addAllocation(T);
}
}
}
public class AstCGNode extends ExplicitNode {
// TODO should this be a Set<Consumer<Object>> instead? I don't see the return values from the
// callbacks ever being used
private Set<Function<Object, Object>> callbacks;
private AstCGNode(IMethod method, Context context) {
super(method, context);
}
private void fireCallbacks() {
if (callbacks != null) {
boolean done = false;
while (!done) {
try {
for (Function<Object, Object> function : callbacks) {
Object ignored = function.apply(null);
}
} catch (ConcurrentModificationException e) {
done = false;
continue;
}
done = true;
}
}
}
private boolean hasCallback(Function<Object, Object> callback) {
return callbacks != null && callbacks.contains(callback);
}
private boolean hasAllCallbacks(Set<Function<Object, Object>> callbacks) {
return callbacks != null && this.callbacks.containsAll(callbacks);
}
public void addCallback(Function<Object, Object> callback) {
if (!hasCallback(callback)) {
if (callbacks == null) {
callbacks = HashSetFactory.make(1);
}
callbacks.add(callback);
for (CGNode p : Iterator2Iterable.make(getCallGraph().getPredNodes(this))) {
((AstCGNode) p).addCallback(callback);
}
}
}
public void addAllCallbacks(Set<Function<Object, Object>> callback) {
if (!hasAllCallbacks(callbacks)) {
if (callbacks == null) {
callbacks = HashSetFactory.make(1);
}
callbacks.addAll(callback);
for (CGNode p : Iterator2Iterable.make(getCallGraph().getPredNodes(this))) {
((AstCGNode) p).addAllCallbacks(callback);
}
}
}
public void clearMutatedCache(CallSiteReference cs) {
targets.remove(cs.getProgramCounter());
}
@Override
public boolean addTarget(CallSiteReference site, CGNode node) {
if (super.addTarget(site, node)) {
if (((AstCGNode) node).callbacks != null) {
((AstCGNode) node).fireCallbacks();
addAllCallbacks(((AstCGNode) node).callbacks);
}
return true;
} else {
return false;
}
}
}
@Override
protected ExplicitNode makeNode(IMethod method, Context context) {
return new AstCGNode(method, context);
}
}
| 6,502
| 31.193069
| 99
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstContextInsensitiveSSAContextInterpreter.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.CodeScanner;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ContextInsensitiveSSAInterpreter;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.util.collections.EmptyIterator;
import java.util.Iterator;
/**
* A version of {@link ContextInsensitiveSSAInterpreter} that uses the IR for {@link
* #iterateNewSites(CGNode)} and {@link #iterateCallSites(CGNode)} when we have an {@link
* AstMethod}. ({@link ContextInsensitiveSSAInterpreter} defaults to using {@link CodeScanner},
* which only works for bytecodes.)
*/
public class AstContextInsensitiveSSAContextInterpreter extends ContextInsensitiveSSAInterpreter {
public AstContextInsensitiveSSAContextInterpreter(
AnalysisOptions options, IAnalysisCacheView cache) {
super(options, cache);
}
public boolean understands(IMethod method) {
return method instanceof AstMethod;
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode N) {
IR ir = getIR(N);
if (ir == null) {
return EmptyIterator.instance();
} else {
return ir.iterateNewSites();
}
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode N) {
IR ir = getIR(N);
if (ir == null) {
return EmptyIterator.instance();
} else {
return ir.iterateCallSites();
}
}
}
| 2,077
| 31.984127
| 98
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstGlobalPointerKey.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.ipa.callgraph.propagation.AbstractPointerKey;
public class AstGlobalPointerKey extends AbstractPointerKey {
private final String globalName;
public String getName() {
return globalName;
}
public AstGlobalPointerKey(String globalName) {
this.globalName = globalName;
}
@Override
public boolean equals(Object x) {
return (x instanceof AstGlobalPointerKey)
&& ((AstGlobalPointerKey) x).globalName.equals(globalName);
}
@Override
public int hashCode() {
return globalName.hashCode();
}
@Override
public String toString() {
return "[global: " + globalName + ']';
}
}
| 1,061
| 24.285714
| 72
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstHeapModel.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.ipa.modref.ExtendedHeapModel;
public interface AstHeapModel extends ExtendedHeapModel, AstPointerKeyFactory {}
| 550
| 31.411765
| 80
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstPointerKeyFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory;
import java.util.Iterator;
public interface AstPointerKeyFactory extends PointerKeyFactory {
Iterator<PointerKey> getPointerKeysForReflectedFieldRead(InstanceKey I, InstanceKey F);
Iterator<PointerKey> getPointerKeysForReflectedFieldWrite(InstanceKey I, InstanceKey F);
/**
* get a pointer key for the object catalog of I. The object catalog stores the names of all known
* properties of I.
*/
PointerKey getPointerKeyForObjectCatalog(InstanceKey I);
}
| 1,073
| 34.8
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/AstSSAPropagationCallGraphBuilder.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.analysis.reflection.ReflectionContextInterpreter;
import com.ibm.wala.cast.ipa.callgraph.AstCallGraph.AstCGNode;
import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys.ScopeMappingInstanceKey;
import com.ibm.wala.cast.ir.ssa.AstAssertInstruction;
import com.ibm.wala.cast.ir.ssa.AstEchoInstruction;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.ir.ssa.AstInstructionVisitor;
import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction;
import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access;
import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cast.ir.ssa.AstLexicalWrite;
import com.ibm.wala.cast.ir.ssa.AstPropertyRead;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction;
import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction;
import com.ibm.wala.cast.ir.translator.AstTranslator;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.AstMethod.LexicalInformation;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.IntSetVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysisImpl;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory;
import com.ibm.wala.ipa.callgraph.propagation.PointsToMap;
import com.ibm.wala.ipa.callgraph.propagation.PointsToSetVariable;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.PropagationSystem;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultSSAInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DelegatingSSAContextInterpreter;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.modref.ArrayLengthKey;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableMapping;
import java.io.UTFDataFormatException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCallGraphBuilder {
public static final boolean DEBUG_TYPE_INFERENCE = false;
public static final boolean DEBUG_PROPERTIES = false;
// /////////////////////////////////////////////////////////////////////////
//
// language specialization interface
//
// /////////////////////////////////////////////////////////////////////////
/**
* should we maintain an object catalog for each instance key, storing the names of all known
* properties of the instance key? required to handle {@link EachElementGetInstruction}s.
*
* @see AstConstraintVisitor#visitPut(SSAPutInstruction)
* @see AstConstraintVisitor#visitEachElementGet(EachElementGetInstruction)
*/
protected abstract boolean useObjectCatalog();
/**
* each language can specify whether a particular field name should be stored in object catalogs
* or not. By default, always return false.
*/
@SuppressWarnings("unused")
protected boolean isUncataloguedField(IClass type, String fieldName) {
return false;
}
// /////////////////////////////////////////////////////////////////////////
//
// overall control
//
// /////////////////////////////////////////////////////////////////////////
public abstract GlobalObjectKey getGlobalObject(Atom language);
protected AstSSAPropagationCallGraphBuilder(
IMethod fakeRootClass,
AnalysisOptions options,
IAnalysisCacheView cache,
PointerKeyFactory pointerKeyFactory) {
super(fakeRootClass, options, cache, pointerKeyFactory);
}
public SSAContextInterpreter makeDefaultContextInterpreters(
SSAContextInterpreter appContextInterpreter, AnalysisOptions options, IClassHierarchy cha) {
SSAContextInterpreter c = new DefaultSSAInterpreter(options, getAnalysisCache());
c =
new DelegatingSSAContextInterpreter(
new AstContextInsensitiveSSAContextInterpreter(options, getAnalysisCache()), c);
c =
new DelegatingSSAContextInterpreter(
ReflectionContextInterpreter.createReflectionContextInterpreter(
cha, options, getAnalysisCache()),
c);
if (appContextInterpreter == null) return c;
else return new DelegatingSSAContextInterpreter(appContextInterpreter, c);
}
// /////////////////////////////////////////////////////////////////////////
//
// specialized pointer analysis
//
// /////////////////////////////////////////////////////////////////////////
@Override
protected PropagationSystem makeSystem(AnalysisOptions options) {
return new PropagationSystem(callGraph, pointerKeyFactory, instanceKeyFactory) {
@Override
public PointerAnalysis<InstanceKey> makePointerAnalysis(PropagationCallGraphBuilder builder) {
return new AstPointerAnalysisImpl(
builder, cg, pointsToMap, instanceKeys, pointerKeyFactory, instanceKeyFactory);
}
};
}
public static class AstPointerAnalysisImpl extends PointerAnalysisImpl {
public AstPointerAnalysisImpl(
PropagationCallGraphBuilder builder,
CallGraph cg,
PointsToMap pointsToMap,
MutableMapping<InstanceKey> instanceKeys,
PointerKeyFactory pointerKeys,
InstanceKeyFactory iKeyFactory) {
super(builder, cg, pointsToMap, instanceKeys, pointerKeys, iKeyFactory);
}
@Override
protected HeapModel makeHeapModel() {
class Model extends HModel implements AstHeapModel {
@Override
public PointerKey getPointerKeyForArrayLength(InstanceKey I) {
return new ArrayLengthKey(I);
}
@Override
public Iterator<PointerKey> getPointerKeysForReflectedFieldRead(
InstanceKey I, InstanceKey F) {
return ((AstPointerKeyFactory) pointerKeys).getPointerKeysForReflectedFieldRead(I, F);
}
@Override
public Iterator<PointerKey> getPointerKeysForReflectedFieldWrite(
InstanceKey I, InstanceKey F) {
return ((AstPointerKeyFactory) pointerKeys).getPointerKeysForReflectedFieldWrite(I, F);
}
@Override
public PointerKey getPointerKeyForObjectCatalog(InstanceKey I) {
return ((AstPointerKeyFactory) pointerKeys).getPointerKeyForObjectCatalog(I);
}
}
return new Model();
}
@Override
protected ImplicitPointsToSetVisitor makeImplicitPointsToVisitor(LocalPointerKey lpk) {
return new AstImplicitPointsToSetVisitor(this, lpk);
}
public static class AstImplicitPointsToSetVisitor extends ImplicitPointsToSetVisitor
implements AstInstructionVisitor {
public AstImplicitPointsToSetVisitor(AstPointerAnalysisImpl analysis, LocalPointerKey lpk) {
super(analysis, lpk);
}
@Override
public void visitPropertyRead(AstPropertyRead instruction) {}
@Override
public void visitPropertyWrite(AstPropertyWrite instruction) {}
@Override
public void visitAstLexicalRead(AstLexicalRead instruction) {}
@Override
public void visitAstLexicalWrite(AstLexicalWrite instruction) {}
@Override
public void visitAstGlobalRead(AstGlobalRead instruction) {
pointsToSet =
analysis.computeImplicitPointsToSetAtGet(
node, instruction.getDeclaredField(), -1, true);
}
@Override
public void visitAstGlobalWrite(AstGlobalWrite instruction) {}
@Override
public void visitAssert(AstAssertInstruction instruction) {}
@Override
public void visitEachElementGet(EachElementGetInstruction inst) {}
@Override
public void visitEachElementHasNext(EachElementHasNextInstruction inst) {}
@Override
public void visitIsDefined(AstIsDefinedInstruction inst) {}
@Override
public void visitEcho(AstEchoInstruction inst) {}
}
}
// /////////////////////////////////////////////////////////////////////////
//
// top-level node constraint generation
//
// /////////////////////////////////////////////////////////////////////////
@Override
protected ExplicitCallGraph createEmptyCallGraph(IMethod fakeRootClass, AnalysisOptions options) {
return new AstCallGraph(fakeRootClass, options, getAnalysisCache());
}
public static class AstInterestingVisitor extends InterestingVisitor
implements AstInstructionVisitor {
public AstInterestingVisitor(int vn) {
super(vn);
}
@Override
public void visitPropertyRead(AstPropertyRead instruction) {
bingo = true;
}
@Override
public void visitPropertyWrite(AstPropertyWrite instruction) {
bingo = true;
}
@Override
public void visitAstLexicalRead(AstLexicalRead instruction) {
bingo = true;
}
@Override
public void visitAstLexicalWrite(AstLexicalWrite instruction) {
bingo = true;
}
@Override
public void visitAstGlobalRead(AstGlobalRead instruction) {
bingo = true;
}
@Override
public void visitAstGlobalWrite(AstGlobalWrite instruction) {
bingo = true;
}
@Override
public void visitAssert(AstAssertInstruction instruction) {
bingo = true;
}
@Override
public void visitEachElementGet(EachElementGetInstruction inst) {
bingo = true;
}
@Override
public void visitEachElementHasNext(EachElementHasNextInstruction inst) {}
@Override
public void visitIsDefined(AstIsDefinedInstruction inst) {}
@Override
public void visitEcho(AstEchoInstruction inst) {}
}
@Override
protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) {
return new AstInterestingVisitor(vn);
}
@Override
public boolean hasNoInterestingUses(CGNode node, int vn, DefUse du) {
if (node.getMethod() instanceof AstMethod) {
// uses in nested functions are interesting
IntSet uses = ((AstIRFactory.AstIR) node.getIR()).lexicalInfo().getAllExposedUses();
if (uses.contains(vn)) {
return false;
}
}
return super.hasNoInterestingUses(node, vn, du);
}
// /////////////////////////////////////////////////////////////////////////
//
// IR visitor specialization for Ast-specific IR types
//
// /////////////////////////////////////////////////////////////////////////
@Override
public ConstraintVisitor makeVisitor(CGNode node) {
return new AstConstraintVisitor(this, node);
}
protected static class AstConstraintVisitor extends ConstraintVisitor
implements AstInstructionVisitor {
public AstConstraintVisitor(AstSSAPropagationCallGraphBuilder builder, CGNode node) {
super(builder, node);
}
@Override
protected AstSSAPropagationCallGraphBuilder getBuilder() {
return (AstSSAPropagationCallGraphBuilder) builder;
}
public PointerKey getPointerKeyForObjectCatalog(InstanceKey I) {
return ((AstPointerKeyFactory) getBuilder().getPointerKeyFactory())
.getPointerKeyForObjectCatalog(I);
}
public Iterator<PointerKey> getPointerKeysForReflectedFieldRead(InstanceKey I, InstanceKey F) {
return ((AstPointerKeyFactory) getBuilder().getPointerKeyFactory())
.getPointerKeysForReflectedFieldRead(I, F);
}
public Iterator<PointerKey> getPointerKeysForReflectedFieldWrite(InstanceKey I, InstanceKey F) {
return ((AstPointerKeyFactory) getBuilder().getPointerKeyFactory())
.getPointerKeysForReflectedFieldWrite(I, F);
}
private static void visitLexical(final LexicalOperator op) {
op.doLexicalPointerKeys();
// I have no idea what the code below does, but commenting it out doesn't
// break any regression tests. --MS
// if (! checkLexicalInstruction(instruction)) {
// system.newSideEffect(op, getPointerKeyForLocal(1));
// }
}
@Override
public void visitPropertyRead(AstPropertyRead instruction) {
if (AstSSAPropagationCallGraphBuilder.DEBUG_PROPERTIES) {
Position instructionPosition = getInstructionPosition(instruction);
if (instructionPosition != null) {
System.err.println(
"processing read instruction " + instruction + ", position " + instructionPosition);
}
}
newFieldRead(node, instruction.getUse(0), instruction.getUse(1), instruction.getDef(0));
}
private Position getInstructionPosition(SSAInstruction instruction) {
IMethod method = node.getMethod();
if (method instanceof AstMethod) {
return ((AstMethod) method).getSourcePosition(instruction.iIndex());
}
return null;
}
@Override
public void visitPropertyWrite(AstPropertyWrite instruction) {
if (AstSSAPropagationCallGraphBuilder.DEBUG_PROPERTIES) {
Position instructionPosition = getInstructionPosition(instruction);
if (instructionPosition != null) {
System.err.println(
"processing write instruction " + instruction + ", position " + instructionPosition);
}
}
newFieldWrite(node, instruction.getUse(0), instruction.getUse(1), instruction.getUse(2));
}
@Override
public void visitAstLexicalRead(AstLexicalRead instruction) {
visitLexical(
new LexicalOperator((AstCGNode) node, instruction.getAccesses(), true) {
@Override
protected void action(PointerKey lexicalKey, int vn) {
PointerKey lval = getPointerKeyForLocal(vn);
if (lexicalKey instanceof LocalPointerKey) {
CGNode lnode = ((LocalPointerKey) lexicalKey).getNode();
int lvn = ((LocalPointerKey) lexicalKey).getValueNumber();
IRView lir = getBuilder().getCFAContextInterpreter().getIRView(lnode);
SymbolTable lsymtab = lir.getSymbolTable();
DefUse ldu = getBuilder().getCFAContextInterpreter().getDU(lnode);
// DefUse ldu = getAnalysisCache().getDefUse(lir);
if (contentsAreInvariant(lsymtab, ldu, lvn)) {
InstanceKey[] ik = getInvariantContents(lsymtab, ldu, lnode, lvn);
system.recordImplicitPointsToSet(lexicalKey);
for (InstanceKey element : ik) {
system.findOrCreateIndexForInstanceKey(element);
system.newConstraint(lval, element);
}
return;
}
}
system.newConstraint(lval, assignOperator, lexicalKey);
}
});
}
@Override
public void visitAstLexicalWrite(AstLexicalWrite instruction) {
visitLexical(
new LexicalOperator((AstCGNode) node, instruction.getAccesses(), false) {
@Override
protected void action(PointerKey lexicalKey, int vn) {
PointerKey rval = getPointerKeyForLocal(vn);
if (contentsAreInvariant(symbolTable, du, vn)) {
InstanceKey[] ik = getInvariantContents(vn);
system.recordImplicitPointsToSet(rval);
for (InstanceKey element : ik) {
system.findOrCreateIndexForInstanceKey(element);
system.newConstraint(lexicalKey, element);
}
} else {
system.newConstraint(lexicalKey, assignOperator, rval);
}
}
});
}
@Override
public void visitAstGlobalRead(AstGlobalRead instruction) {
visitGetInternal(instruction.getDef(), -1, true, instruction.getDeclaredField());
}
@Override
public void visitAstGlobalWrite(AstGlobalWrite instruction) {
visitPutInternal(instruction.getVal(), -1, true, instruction.getDeclaredField());
}
@Override
public void visitPut(SSAPutInstruction inst) {
super.visitPut(inst);
if (inst.isStatic() || !getBuilder().useObjectCatalog()) return;
// update the object catalog corresponding to the base pointer, adding the
// name of the field as a property
SymbolTable symtab = ir.getSymbolTable();
int objVn = inst.getRef();
String fieldName = null;
try {
fieldName = inst.getDeclaredField().getName().toUnicodeString();
} catch (UTFDataFormatException e) {
Assertions.UNREACHABLE();
}
final PointerKey objKey = getPointerKeyForLocal(objVn);
final InstanceKey[] fieldNameKeys = new InstanceKey[] {getInstanceKeyForConstant(fieldName)};
assert fieldNameKeys.length == 1;
if (contentsAreInvariant(symtab, du, objVn)) {
system.recordImplicitPointsToSet(objKey);
final InstanceKey[] objKeys = getInvariantContents(objVn);
for (InstanceKey key : objKeys) {
if (!getBuilder().isUncataloguedField(key.getConcreteType(), fieldName)) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(key);
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldNameKeys[0]);
}
}
}
} else {
final String hack = fieldName;
system.newSideEffect(
new UnaryOperator<>() {
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects
.getValue()
.foreach(
optr -> {
InstanceKey object = system.getInstanceKey(optr);
if (!getBuilder().isUncataloguedField(object.getConcreteType(), hack)) {
PointerKey cat = getPointerKeyForObjectCatalog(object);
if (cat != null) {
system.newConstraint(cat, fieldNameKeys[0]);
}
}
});
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public String toString() {
return "field name record: " + objKey;
}
},
objKey);
}
}
@Override
public void visitAssert(AstAssertInstruction instruction) {}
@Override
public void visitEachElementHasNext(EachElementHasNextInstruction inst) {}
@Override
public void visitEachElementGet(EachElementGetInstruction inst) {
int lval = inst.getDef(0);
final PointerKey lk = getPointerKeyForLocal(lval);
int rval = inst.getUse(0);
final PointerKey rk = getPointerKeyForLocal(rval);
if (contentsAreInvariant(symbolTable, du, rval)) {
InstanceKey objects[] = getInvariantContents(rval);
for (InstanceKey object : objects) {
PointerKey catalog = getPointerKeyForObjectCatalog(object);
system.newConstraint(lk, assignOperator, catalog);
}
} else {
system.newSideEffect(
new UnaryOperator<>() {
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects
.getValue()
.foreach(
optr -> {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
if (objCatalog != null) {
system.newConstraint(lk, assignOperator, objCatalog);
}
});
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public String toString() {
return "get catalog op" + rk;
}
},
rk);
}
}
@Override
public void visitIsDefined(AstIsDefinedInstruction inst) {}
@Override
public void visitEcho(AstEchoInstruction inst) {}
// /////////////////////////////////////////////////////////////////////////
//
// lexical scoping handling
//
// /////////////////////////////////////////////////////////////////////////
private abstract class LexicalOperator extends UnaryOperator<PointsToSetVariable> {
/** node in which lexical accesses are performed */
private final AstCGNode node;
/** the lexical accesses to be handled */
private final Access[] accesses;
/** are all the lexical accesses loads? if false, they are all stores */
private final boolean isLoad;
private LexicalOperator(AstCGNode node, Access[] accesses, boolean isLoad) {
this.node = node;
this.isLoad = isLoad;
this.accesses = accesses;
}
/**
* perform the necessary {@link #action(PointerKey, int)}s for the accesses. For each access,
* we determine the possible {@link CGNode}s corresponding to its definer (see {@link
* AstConstraintVisitor#getLexicalDefiners(CGNode, Pair)}). Handle using {@link
* AstConstraintVisitor#handleRootLexicalReference(String, String, CGNode)} .
*/
private void doLexicalPointerKeys() {
for (Access accesse : accesses) {
final String name = accesse.variableName;
final String definer = accesse.variableDefiner;
final int vn = accesse.valueNumber;
if (AstTranslator.DEBUG_LEXICAL)
System.err.println(("looking up lexical parent " + definer));
Set<CGNode> creators = getLexicalDefiners(node, Pair.make(name, definer));
for (CGNode n : creators) {
PointerKey funargKey = handleRootLexicalReference(name, definer, n);
action(funargKey, vn);
}
}
}
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
doLexicalPointerKeys();
return NOT_CHANGED;
}
protected abstract void action(PointerKey lexicalKey, int vn);
@Override
public String toString() {
return "lexical op";
}
@Override
public boolean equals(Object o) {
if (!(o instanceof LexicalOperator)) {
return false;
} else {
LexicalOperator other = (LexicalOperator) o;
if (isLoad != other.isLoad) {
return false;
} else if (!node.equals(other.node)) {
return false;
} else if (accesses.length != other.accesses.length) {
return false;
} else {
for (int i = 0; i < accesses.length; i++) {
if (!accesses[i].equals(other.accesses[i])) {
return false;
}
}
for (int i = 0; i < accesses.length; i++) {
if (!accesses[i].equals(other.accesses[i])) {
return false;
}
}
return true;
}
}
}
@Override
public int hashCode() {
return node.hashCode() * accesses[0].hashCode() * accesses.length;
}
}
private Set<CGNode> getLexicalDefiners(
final CGNode opNode, final Pair<String, String> definer) {
if (definer == null) {
return Collections.singleton(getBuilder().getCallGraph().getFakeRootNode());
} else if (getBuilder().sameMethod(opNode, definer.snd)) {
// lexical access to a variable declared in opNode itself
return Collections.singleton(opNode);
} else {
final Set<CGNode> result = HashSetFactory.make();
PointerKey F = getBuilder().getPointerKeyForLocal(opNode, 1);
IRView ir = getBuilder().getCFAContextInterpreter().getIRView(opNode);
SymbolTable symtab = ir.getSymbolTable();
DefUse du = getBuilder().getCFAContextInterpreter().getDU(opNode);
if (contentsAreInvariant(symtab, du, 1)) {
system.recordImplicitPointsToSet(F);
final InstanceKey[] functionKeys = getInvariantContents(symtab, du, opNode, 1);
for (InstanceKey functionKey : functionKeys) {
system.findOrCreateIndexForInstanceKey(functionKey);
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) functionKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
}
}
} else {
PointsToSetVariable FV = system.findOrCreatePointsToSet(F);
if (FV.getValue() != null) {
FV.getValue()
.foreach(
ptr -> {
InstanceKey iKey = system.getInstanceKey(ptr);
if (iKey instanceof ScopeMappingInstanceKey) {
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) iKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
}
} else {
// Assertions.UNREACHABLE("unexpected instance key " + iKey);
}
});
}
}
return result;
}
}
private final Set<PointerKey> discoveredUpwardFunargs = HashSetFactory.make();
/**
* add constraints that assign the final value of name in definingNode to the upward funarg
* (lhs), modeling adding of the state to the closure
*/
private void addUpwardFunargConstraints(
PointerKey lhs, String name, String definer, CGNode definingNode) {
discoveredUpwardFunargs.add(lhs);
LexicalInformation LI = ((AstIRFactory.AstIR) definingNode.getIR()).lexicalInfo();
Pair<String, String>[] names = LI.getExposedNames();
for (int i = 0; i < names.length; i++) {
if (name.equals(names[i].fst) && definer.equals(names[i].snd)) {
int vn = LI.getExitExposedUses()[i];
if (vn > 0) {
IRView ir = getBuilder().getCFAContextInterpreter().getIRView(definingNode);
DefUse du = getBuilder().getCFAContextInterpreter().getDU(definingNode);
SymbolTable st = ir.getSymbolTable();
PointerKey rhs = getBuilder().getPointerKeyForLocal(definingNode, vn);
if (contentsAreInvariant(st, du, vn)) {
system.recordImplicitPointsToSet(rhs);
final InstanceKey[] objs = getInvariantContents(st, du, definingNode, vn);
for (InstanceKey obj : objs) {
system.findOrCreateIndexForInstanceKey(obj);
system.newConstraint(lhs, obj);
}
} else {
system.newConstraint(lhs, assignOperator, rhs);
}
}
return;
}
}
Assertions.UNREACHABLE();
}
/**
* handle a lexical reference where we found no parent call graph node defining the name; it's
* either a global or an upward funarg
*/
private PointerKey handleRootLexicalReference(
String name, String definer, final CGNode definingNode) {
// global variable
if (definer == null) {
return new AstGlobalPointerKey(name);
// upward funarg
} else {
class UpwardFunargPointerKey extends AstGlobalPointerKey {
UpwardFunargPointerKey(String name) {
super(name);
}
public CGNode getDefiningNode() {
return definingNode;
}
@Override
public boolean equals(Object x) {
return (x instanceof UpwardFunargPointerKey)
&& super.equals(x)
&& (definingNode == null
? definingNode == ((UpwardFunargPointerKey) x).getDefiningNode()
: definingNode.equals(((UpwardFunargPointerKey) x).getDefiningNode()));
}
@Override
public int hashCode() {
return super.hashCode() * ((definingNode == null) ? 17 : definingNode.hashCode());
}
@Override
public String toString() {
return "[upward:" + getName() + ':' + definingNode + ']';
}
}
PointerKey result = new UpwardFunargPointerKey(name);
if (!discoveredUpwardFunargs.contains(result) && definingNode != null) {
addUpwardFunargConstraints(result, name, definer, definingNode);
}
return result;
}
}
// /////////////////////////////////////////////////////////////////////////
//
// property manipulation handling
//
// /////////////////////////////////////////////////////////////////////////
protected interface ReflectedFieldAction {
void action(AbstractFieldPointerKey fieldKey);
void dump(AbstractFieldPointerKey fieldKey, boolean constObj, boolean constProp);
}
private void newFieldOperation(
CGNode opNode,
final int objVn,
final int fieldsVn,
final boolean isLoadOperation,
final ReflectedFieldAction action) {
IRView ir = getBuilder().getCFAContextInterpreter().getIRView(opNode);
SymbolTable symtab = ir.getSymbolTable();
DefUse du = getBuilder().getCFAContextInterpreter().getDU(opNode);
PointerKey objKey = getBuilder().getPointerKeyForLocal(opNode, objVn);
final PointerKey fieldKey = getBuilder().getPointerKeyForLocal(opNode, fieldsVn);
// log field access
if (DEBUG_PROPERTIES) {
if (isLoadOperation) System.err.print(("adding read of " + objKey + '.' + fieldKey + ':'));
else System.err.print(("adding write of " + objKey + '.' + fieldKey + ':'));
if (contentsAreInvariant(symtab, du, objVn)) {
System.err.print(" constant obj:");
InstanceKey[] x = getInvariantContents(symtab, du, opNode, objVn);
for (InstanceKey element : x) {
System.err.print((element.toString() + ' '));
}
} else {
System.err.print((" obj:" + system.findOrCreatePointsToSet(objKey)));
}
if (contentsAreInvariant(symtab, du, fieldsVn)) {
System.err.print(" constant prop:");
InstanceKey[] x = getInvariantContents(symtab, du, opNode, fieldsVn);
for (InstanceKey element : x) {
System.err.print((element.toString() + ' '));
}
} else {
System.err.print((" props:" + system.findOrCreatePointsToSet(fieldKey)));
}
System.err.print("\n");
}
// make sure instance keys get mapped for PointerAnalysisImpl
if (contentsAreInvariant(symtab, du, objVn)) {
InstanceKey[] x = getInvariantContents(symtab, du, opNode, objVn);
for (InstanceKey element : x) {
system.findOrCreateIndexForInstanceKey(element);
}
}
if (contentsAreInvariant(symtab, du, fieldsVn)) {
InstanceKey[] x = getInvariantContents(symtab, du, opNode, fieldsVn);
for (InstanceKey element : x) {
system.findOrCreateIndexForInstanceKey(element);
}
}
// process field access
if (contentsAreInvariant(symtab, du, objVn)) {
system.recordImplicitPointsToSet(objKey);
final InstanceKey[] objKeys = getInvariantContents(symtab, du, opNode, objVn);
if (contentsAreInvariant(symtab, du, fieldsVn)) {
system.recordImplicitPointsToSet(fieldKey);
InstanceKey[] fieldsKeys = getInvariantContents(symtab, du, opNode, fieldsVn);
newFieldOperationObjectAndFieldConstant(isLoadOperation, action, objKeys, fieldsKeys);
} else {
newFieldOperationOnlyObjectConstant(isLoadOperation, action, fieldKey, objKeys);
}
} else {
if (contentsAreInvariant(symtab, du, fieldsVn)) {
system.recordImplicitPointsToSet(fieldKey);
final InstanceKey[] fieldsKeys = getInvariantContents(symtab, du, opNode, fieldsVn);
newFieldOperationOnlyFieldConstant(isLoadOperation, action, objKey, fieldsKeys);
} else {
newFieldFullOperation(isLoadOperation, action, objKey, fieldKey);
}
}
if (DEBUG_PROPERTIES) {
System.err.println("finished\n");
}
}
protected void newFieldOperationFieldConstant(
CGNode opNode,
final boolean isLoadOperation,
final ReflectedFieldAction action,
final int objVn,
final InstanceKey[] fieldsKeys) {
IRView ir = getBuilder().getCFAContextInterpreter().getIRView(opNode);
SymbolTable symtab = ir.getSymbolTable();
DefUse du = getBuilder().getCFAContextInterpreter().getDU(opNode);
PointerKey objKey = getBuilder().getPointerKeyForLocal(opNode, objVn);
if (contentsAreInvariant(symtab, du, objVn)) {
system.recordImplicitPointsToSet(objKey);
InstanceKey[] objectKeys = getInvariantContents(symtab, du, opNode, objVn);
newFieldOperationObjectAndFieldConstant(isLoadOperation, action, objectKeys, fieldsKeys);
} else {
newFieldOperationOnlyFieldConstant(isLoadOperation, action, objKey, fieldsKeys);
}
}
protected void newFieldFullOperation(
final boolean isLoadOperation,
final ReflectedFieldAction action,
PointerKey objKey,
final PointerKey fieldKey) {
system.newSideEffect(
new AbstractOperator<>() {
private final MutableIntSet doneReceiver = IntSetUtil.make();
private final MutableIntSet doneField = IntSetUtil.make();
@Override
public byte evaluate(PointsToSetVariable lhs, final PointsToSetVariable[] rhs) {
final IntSetVariable<?> receivers = rhs[0];
final IntSetVariable<?> fields = rhs[1];
if (receivers.getValue() != null && fields.getValue() != null) {
receivers
.getValue()
.foreach(
rptr -> {
final InstanceKey receiver = system.getInstanceKey(rptr);
if (!isLoadOperation) {
PointerKey cat = getPointerKeyForObjectCatalog(receiver);
if (cat != null) {
system.newConstraint(cat, assignOperator, fieldKey);
}
}
fields
.getValue()
.foreach(
fptr -> {
if (!doneField.contains(fptr) || !doneReceiver.contains(rptr)) {
InstanceKey field = system.getInstanceKey(fptr);
for (PointerKey pkey :
Iterator2Iterable.make(
isLoadOperation
? getPointerKeysForReflectedFieldRead(
receiver, field)
: getPointerKeysForReflectedFieldWrite(
receiver, field))) {
AbstractFieldPointerKey key =
(AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES) action.dump(key, false, false);
action.action(key);
}
}
});
});
doneReceiver.addAll(receivers.getValue());
doneField.addAll(fields.getValue());
}
return NOT_CHANGED;
}
@Override
public String toString() {
return "field op";
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
},
objKey,
fieldKey);
}
protected void newFieldOperationOnlyFieldConstant(
final boolean isLoadOperation,
final ReflectedFieldAction action,
final PointerKey objKey,
final InstanceKey[] fieldsKeys) {
system.newSideEffect(
new UnaryOperator<>() {
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects
.getValue()
.foreach(
optr -> {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
for (InstanceKey fieldsKey : fieldsKeys) {
if (isLoadOperation) {
for (PointerKey pkey :
Iterator2Iterable.make(
getPointerKeysForReflectedFieldRead(object, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES) action.dump(key, true, false);
action.action(key);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKey);
}
for (PointerKey pkey :
Iterator2Iterable.make(
getPointerKeysForReflectedFieldWrite(object, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES) action.dump(key, true, false);
action.action(key);
}
}
}
});
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public String toString() {
return "field op" + objKey;
}
},
objKey);
}
protected void newFieldOperationOnlyObjectConstant(
final boolean isLoadOperation,
final ReflectedFieldAction action,
final PointerKey fieldKey,
final InstanceKey[] objKeys) {
if (!isLoadOperation) {
for (InstanceKey objKey : objKeys) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(objKey);
if (objCatalog != null) {
system.newConstraint(objCatalog, assignOperator, fieldKey);
}
}
}
system.newSideEffect(
new UnaryOperator<>() {
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> fields = rhs;
if (fields.getValue() != null) {
fields
.getValue()
.foreach(
fptr -> {
InstanceKey field = system.getInstanceKey(fptr);
for (InstanceKey objKey : objKeys) {
for (PointerKey pkey :
Iterator2Iterable.make(
isLoadOperation
? getPointerKeysForReflectedFieldRead(objKey, field)
: getPointerKeysForReflectedFieldWrite(objKey, field))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES) action.dump(key, false, true);
action.action(key);
}
}
});
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public String toString() {
return "field op" + fieldKey;
}
},
fieldKey);
}
protected void newFieldOperationObjectAndFieldConstant(
final boolean isLoadOperation,
final ReflectedFieldAction action,
final InstanceKey[] objKeys,
InstanceKey[] fieldsKeys) {
for (InstanceKey objKey : objKeys) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(objKey);
for (InstanceKey fieldsKey : fieldsKeys) {
if (isLoadOperation) {
for (PointerKey pkey :
Iterator2Iterable.make(getPointerKeysForReflectedFieldRead(objKey, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES) action.dump(key, true, true);
action.action(key);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKey);
}
for (PointerKey pkey :
Iterator2Iterable.make(getPointerKeysForReflectedFieldWrite(objKey, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES) action.dump(key, true, true);
action.action(key);
}
}
}
}
}
public void newFieldWrite(CGNode opNode, int objVn, int fieldsVn, int rhsVn) {
IRView ir = getBuilder().getCFAContextInterpreter().getIRView(opNode);
SymbolTable symtab = ir.getSymbolTable();
DefUse du = getBuilder().getCFAContextInterpreter().getDU(opNode);
PointerKey rhsKey = getBuilder().getPointerKeyForLocal(opNode, rhsVn);
if (contentsAreInvariant(symtab, du, rhsVn)) {
system.recordImplicitPointsToSet(rhsKey);
newFieldWrite(opNode, objVn, fieldsVn, getInvariantContents(symtab, du, opNode, rhsVn));
} else {
newFieldWrite(opNode, objVn, fieldsVn, rhsKey);
}
}
private final class ConstantWriter implements ReflectedFieldAction {
private final InstanceKey[] rhsFixedValues;
private ConstantWriter(InstanceKey[] rhsFixedValues) {
this.rhsFixedValues = rhsFixedValues;
}
@Override
public void dump(AbstractFieldPointerKey fieldKey, boolean constObj, boolean constProp) {
System.err.println(
("writing fixed rvals to " + fieldKey + ' ' + constObj + ", " + constProp));
for (InstanceKey rhsFixedValue : rhsFixedValues) {
System.err.println(("writing " + rhsFixedValue));
}
}
@Override
public void action(AbstractFieldPointerKey fieldKey) {
if (!representsNullType(fieldKey.getInstanceKey())) {
for (InstanceKey rhsFixedValue : rhsFixedValues) {
system.findOrCreateIndexForInstanceKey(rhsFixedValue);
system.newConstraint(fieldKey, rhsFixedValue);
}
}
}
}
public void newFieldWrite(
CGNode opNode, int objVn, int fieldsVn, final InstanceKey[] rhsFixedValues) {
newFieldOperation(opNode, objVn, fieldsVn, false, new ConstantWriter(rhsFixedValues));
}
public void newFieldWrite(
CGNode opNode, int objVn, InstanceKey[] fieldKeys, final InstanceKey[] rhsValues) {
newFieldOperationFieldConstant(
opNode, false, new ConstantWriter(rhsValues), objVn, fieldKeys);
}
private final class NormalWriter implements ReflectedFieldAction {
private final PointerKey rhs;
private NormalWriter(PointerKey rhs) {
this.rhs = rhs;
}
@Override
public void dump(AbstractFieldPointerKey fieldKey, boolean constObj, boolean constProp) {
System.err.println(
("write " + rhs + " to " + fieldKey + ' ' + constObj + ", " + constProp));
}
@Override
public void action(AbstractFieldPointerKey fieldKey) {
if (!representsNullType(fieldKey.getInstanceKey())) {
system.newConstraint(fieldKey, assignOperator, rhs);
}
}
}
public void newFieldWrite(CGNode opNode, int objVn, int fieldsVn, final PointerKey rhs) {
newFieldOperation(opNode, objVn, fieldsVn, false, new NormalWriter(rhs));
}
public void newFieldWrite(
CGNode opNode, int objVn, InstanceKey[] fieldKeys, final PointerKey rhs) {
newFieldOperationFieldConstant(opNode, false, new NormalWriter(rhs), objVn, fieldKeys);
}
protected void newFieldRead(CGNode opNode, int objVn, int fieldsVn, int lhsVn) {
newFieldRead(opNode, objVn, fieldsVn, getBuilder().getPointerKeyForLocal(opNode, lhsVn));
}
protected class FieldReadAction implements ReflectedFieldAction {
private final PointerKey lhs;
public FieldReadAction(PointerKey lhs) {
this.lhs = lhs;
}
@Override
public void dump(AbstractFieldPointerKey fieldKey, boolean constObj, boolean constProp) {
System.err.println(
("read " + lhs + " from " + fieldKey + ' ' + constObj + ", " + constProp));
}
@Override
public void action(AbstractFieldPointerKey fieldKey) {
if (!representsNullType(fieldKey.getInstanceKey())) {
system.newConstraint(lhs, assignOperator, fieldKey);
AbstractFieldPointerKey unknown = getBuilder().fieldKeyForUnknownWrites(fieldKey);
if (unknown != null) {
system.newConstraint(lhs, assignOperator, unknown);
}
}
}
}
protected ReflectedFieldAction fieldReadAction(PointerKey lhs) {
return new FieldReadAction(lhs);
}
protected void newFieldRead(CGNode opNode, int objVn, int fieldsVn, final PointerKey lhs) {
newFieldOperation(opNode, objVn, fieldsVn, true, fieldReadAction(lhs));
}
}
/**
* If the given fieldKey represents a concrete field, return the corresponding field key that
* represents all writes to unknown fields that could potentially alias fieldKey
*/
protected abstract AbstractFieldPointerKey fieldKeyForUnknownWrites(
AbstractFieldPointerKey fieldKey);
/**
* Is definingMethod the same as the method represented by opNode? We need this since the names
* for methods in some languages don't map in the straightforward way to the CGNode
*/
protected abstract boolean sameMethod(final CGNode opNode, final String definingMethod);
}
| 50,057
| 36.245536
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CAstAnalysisScope.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation. All rights reserved. This program
* and the accompanying materials are made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.cast.loader.SingleClassLoaderFactory;
import com.ibm.wala.classLoader.ArrayClassLoader;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.debug.Assertions;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
public class CAstAnalysisScope extends AnalysisScope {
private final ClassLoaderReference theLoader;
public CAstAnalysisScope(SingleClassLoaderFactory loaders, Collection<Language> languages) {
super(languages);
this.theLoader = loaders.getTheReference();
}
public CAstAnalysisScope(
String[] sourceFileNames, SingleClassLoaderFactory loaders, Collection<Language> languages) {
this(loaders, languages);
for (String sourceFileName : sourceFileNames) {
File F = new File(sourceFileName);
addSourceFileToScope(theLoader, F, F.getPath());
}
}
public CAstAnalysisScope(
Module[] sources, SingleClassLoaderFactory loaders, Collection<Language> languages) {
this(loaders, languages);
for (Module source : sources) {
addToScope(theLoader, source);
}
}
/**
* Return the information regarding the primordial loader.
*
* @return ClassLoaderReference
*/
@Override
public ClassLoaderReference getPrimordialLoader() {
Assertions.UNREACHABLE();
return null;
}
/**
* Return the information regarding the extension loader.
*
* @return ClassLoaderReference
*/
@Override
public ClassLoaderReference getExtensionLoader() {
Assertions.UNREACHABLE();
return null;
}
/**
* Return the information regarding the application loader.
*
* @return ClassLoaderReference
*/
@Override
public ClassLoaderReference getApplicationLoader() {
Assertions.UNREACHABLE();
return null;
}
/** @return Returns the arrayClassLoader. */
@Override
public ArrayClassLoader getArrayClassLoader() {
Assertions.UNREACHABLE();
return null;
}
/**
* Return the information regarding the application loader.
*
* @return ClassLoaderReference
*/
@Override
public ClassLoaderReference getSyntheticLoader() {
return null;
}
/** Add a class file to the scope for a loader */
@Override
public void addClassFileToScope(ClassLoaderReference loader, File file) {
Assertions.UNREACHABLE();
}
/** @return the ClassLoaderReference specified by {@code name}. */
@Override
public ClassLoaderReference getLoader(Atom name) {
assert name.equals(theLoader.getName());
return theLoader;
}
/** */
@Override
public Collection<ClassLoaderReference> getLoaders() {
return Collections.singleton(theLoader);
}
/** @return the number of loaders. */
@Override
public int getNumberOfLoaders() {
return 1;
}
@Override
public String toString() {
return super.toString() + '\n' + theLoader + ": " + getModules(theLoader);
}
}
| 3,481
| 25.992248
| 99
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CAstCallGraphUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.cast.loader.SingleClassLoaderFactory;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
public class CAstCallGraphUtil {
/** flag to prevent dumping of verbose call graph / pointer analysis output */
public static boolean AVOID_DUMP = true;
public static SourceFileModule makeSourceModule(URL script, String dir, String name) {
// DO NOT use File.separator here, since this name is matched against
// URLs. It seems that, in DOS, URL.getFile() does not return a
// \-separated file name, but rather one with /'s. Rather makes one
// wonder why the function is called get_File_ :(
return makeSourceModule(script, dir + '/' + name);
}
public static SourceFileModule makeSourceModule(URL script, String scriptName) {
String hackedName = script.getFile().replaceAll("%5c", "/").replaceAll("%20", " ");
File scriptFile = new File(hackedName);
assert hackedName.endsWith(scriptName)
: scriptName + " does not match file " + script.getFile();
return new SourceFileModule(scriptFile, scriptName, null) {
@Override
public InputStream getInputStream() {
BOMInputStream bs =
new BOMInputStream(
super.getInputStream(),
false,
ByteOrderMark.UTF_8,
ByteOrderMark.UTF_16LE,
ByteOrderMark.UTF_16BE,
ByteOrderMark.UTF_32LE,
ByteOrderMark.UTF_32BE);
try {
if (bs.hasBOM()) {
System.err.println("removing BOM " + bs.getBOM());
}
return bs;
} catch (IOException e) {
return super.getInputStream();
}
}
};
}
public static AnalysisScope makeScope(
String[] files, SingleClassLoaderFactory loaders, Language language) {
CAstAnalysisScope result =
new CAstAnalysisScope(files, loaders, Collections.singleton(language));
return result;
}
public static AnalysisScope makeScope(
Module[] files, SingleClassLoaderFactory loaders, Language language) {
CAstAnalysisScope result =
new CAstAnalysisScope(files, loaders, Collections.singleton(language));
return result;
}
public static IAnalysisCacheView makeCache(IRFactory<IMethod> factory) {
return new AnalysisCacheImpl(factory);
}
public static String getShortName(CGNode nd) {
IMethod method = nd.getMethod();
return getShortName(method);
}
public static String getShortName(IMethod method) {
String origName = method.getName().toString();
String result = origName;
if (origName.equals("do") || origName.equals("ctor")) {
result = method.getDeclaringClass().getName().toString();
result = result.substring(result.lastIndexOf('/') + 1);
if (origName.equals("ctor")) {
if (result.equals("LFunction")) {
String s = method.toString();
if (s.indexOf('(') != -1) {
String functionName = s.substring(s.indexOf('(') + 1, s.indexOf(')'));
functionName = functionName.substring(functionName.lastIndexOf('/') + 1);
result += ' ' + functionName;
}
}
result = "ctor of " + result;
}
}
return result;
}
public static void dumpCG(
SSAContextInterpreter interp, PointerAnalysis<? extends InstanceKey> PA, CallGraph CG) {
if (AVOID_DUMP) return;
for (CGNode N : CG) {
System.err.print("callees of node " + getShortName(N) + " : [");
boolean fst = true;
for (CGNode n : Iterator2Iterable.make(CG.getSuccNodes(N))) {
if (fst) fst = false;
else System.err.print(", ");
System.err.print(getShortName(n));
}
System.err.println("]");
System.err.println("\nIR of node " + N.getGraphNodeId() + ", context " + N.getContext());
IRView ir = interp.getIRView(N);
if (ir != null) {
System.err.println(ir);
} else {
System.err.println("no IR!");
}
}
System.err.println("pointer analysis");
for (PointerKey n : PA.getPointerKeys()) {
try {
System.err.println((n + " --> " + PA.getPointsToSet(n)));
} catch (Throwable e) {
System.err.println(("error computing set for " + n));
}
}
}
public static SourceFileModule[] handleFileNames(String[] fileNameArgs) {
SourceFileModule[] fileNames = new SourceFileModule[fileNameArgs.length];
for (int i = 0; i < fileNameArgs.length; i++) {
if (new File(fileNameArgs[i]).exists()) {
try {
fileNames[i] =
CAstCallGraphUtil.makeSourceModule(
new File(fileNameArgs[i]).toURI().toURL(), fileNameArgs[i]);
} catch (MalformedURLException e) {
Assertions.UNREACHABLE(e.toString());
}
} else {
URL url = CAstCallGraphUtil.class.getClassLoader().getResource(fileNameArgs[i]);
fileNames[i] = CAstCallGraphUtil.makeSourceModule(url, fileNameArgs[i]);
}
}
return fileNames;
}
}
| 6,485
| 35.033333
| 95
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CrossLanguageCallGraph.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cast.util.TargetLanguageSelector;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A CallGraph implementation adapted to work for graphs that contain code entities from multiple
* languages, and hence multiple specialized forms of IR. The root node delegates to one of several
* language-specific root nodes, allowing each language to use its own specialized IR constructs for
* entry points.
*
* @author Julian Dolby (dolby@us.ibm.com)
*/
public class CrossLanguageCallGraph extends AstCallGraph {
public CrossLanguageCallGraph(
TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> roots,
IMethod fakeRootClass2,
AnalysisOptions options,
IAnalysisCacheView cache) {
super(fakeRootClass2, options, cache);
this.roots = roots;
}
private final TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> roots;
private final Set<CGNode> languageRootNodes = HashSetFactory.make();
private final Map<Atom, IMethod> languageRoots = HashMapFactory.make();
public AbstractRootMethod getLanguageRoot(Atom language) {
if (!languageRoots.containsKey(language)) {
AbstractRootMethod languageRoot = roots.get(language, this);
CGNode languageRootNode = null;
try {
languageRootNode = findOrCreateNode(languageRoot, Everywhere.EVERYWHERE);
} catch (CancelException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
languageRootNodes.add(languageRootNode);
CallSiteReference site =
CallSiteReference.make(
1, languageRoot.getReference(), IInvokeInstruction.Dispatch.STATIC);
CGNode fakeRootNode = getFakeRootNode();
CrossLanguageFakeRoot fakeRootMethod = (CrossLanguageFakeRoot) fakeRootNode.getMethod();
site = fakeRootMethod.addInvocationInternal(new int[0], site).getCallSite();
fakeRootNode.addTarget(site, languageRootNode);
languageRoots.put(language, languageRoot);
}
return (AbstractRootMethod) languageRoots.get(language);
}
public static ClassLoaderReference crossCoreLoader = ClassLoaderReference.Primordial;
public static TypeReference fakeRootClass =
TypeReference.findOrCreate(crossCoreLoader, TypeName.findOrCreate("CrossFakeRoot"));
public static MethodReference rootMethod =
MethodReference.findOrCreate(fakeRootClass, FakeRootMethod.name, FakeRootMethod.descr);
public class CrossLanguageFakeRoot extends ScriptFakeRoot {
public CrossLanguageFakeRoot(
IClass declaringClass,
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView cache) {
super(rootMethod, declaringClass, cha, options, cache);
}
public CrossLanguageFakeRoot(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(rootMethod, cha, options, cache);
}
public int addPhi(TypeReference type, int[] values) {
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addPhi(values);
}
@Override
public int addGetInstance(FieldReference ref, int object) {
TypeReference type = ref.getDeclaringClass();
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addGetInstance(ref, object);
}
@Override
public int addGetStatic(FieldReference ref) {
TypeReference type = ref.getDeclaringClass();
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addGetStatic(ref);
}
@Override
public int addCheckcast(TypeReference[] type, int rv, boolean isPEI) {
Atom language = type[0].getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addCheckcast(type, rv, isPEI);
}
@Override
public SSANewInstruction addAllocation(TypeReference type) {
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addAllocation(type);
}
@Override
public SSAAbstractInvokeInstruction addInvocation(int[] params, CallSiteReference site) {
TypeReference type = site.getDeclaredTarget().getDeclaringClass();
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addInvocation(params, site);
}
public SSAAbstractInvokeInstruction addInvocationInternal(
int[] params, CallSiteReference site) {
return super.addInvocation(params, site);
}
@Override
public AstLexicalRead addGlobalRead(TypeReference type, String name) {
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return ((AstFakeRoot) root).addGlobalRead(type, name);
}
@Override
public SSAAbstractInvokeInstruction addDirectCall(
int functionVn, int[] argVns, CallSiteReference callSite) {
TypeReference type = callSite.getDeclaredTarget().getDeclaringClass();
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return ((ScriptFakeRoot) root).addDirectCall(functionVn, argVns, callSite);
}
}
Iterator<CGNode> getLanguageRoots() {
return languageRootNodes.iterator();
}
@Override
protected CGNode makeFakeRootNode() throws CancelException {
return findOrCreateNode(
new CrossLanguageFakeRoot(cha, options, getAnalysisCache()), Everywhere.EVERYWHERE);
}
}
| 7,289
| 36.005076
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CrossLanguageClassTargetSelector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.ClassTargetSelector;
import java.util.Map;
/**
* A ClassTargetSelector implementation that delegates to one of several child selectors based on
* the language of the type being allocated. This selector uses the language associated with the
* TypeReference of the allocated type to delagate t =o the appropriate language-specific selector.
*
* @author Julian Dolby (dolby@us.ibm.com)
*/
public class CrossLanguageClassTargetSelector implements ClassTargetSelector {
private final Map<Atom, ClassTargetSelector> languageSelectors;
public CrossLanguageClassTargetSelector(Map<Atom, ClassTargetSelector> languageSelectors) {
this.languageSelectors = languageSelectors;
}
private static Atom getLanguage(NewSiteReference target) {
return target.getDeclaredType().getClassLoader().getLanguage();
}
private ClassTargetSelector getSelector(NewSiteReference site) {
return languageSelectors.get(getLanguage(site));
}
@Override
public IClass getAllocatedTarget(CGNode caller, NewSiteReference site) {
return getSelector(site).getAllocatedTarget(caller, site);
}
}
| 1,729
| 35.041667
| 99
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/ipa/callgraph/CrossLanguageContextSelector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cast.ipa.callgraph;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.util.intset.IntSet;
import java.util.Map;
/**
* A ContextSelector implementation adapted to work for analysis across multiple languages. This
* context selector delegates to one of several child selectors based on the language of the code
* body for which a context is being selected.
*
* <p>This provides a convenient way to integrate multiple, language-specific specialized context
* policies---such as the ones used for clone() in Java and runtime primitives in JavaScript.
*
* @author Julian Dolby (dolby@us.ibm.com)
*/
public class CrossLanguageContextSelector implements ContextSelector {
private final Map<Atom, ContextSelector> languageSelectors;
public CrossLanguageContextSelector(Map<Atom, ContextSelector> languageSelectors) {
this.languageSelectors = languageSelectors;
}
private static Atom getLanguage(CallSiteReference site) {
return site.getDeclaredTarget().getDeclaringClass().getClassLoader().getLanguage();
}
private ContextSelector getSelector(CallSiteReference site) {
return languageSelectors.get(getLanguage(site));
}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
return getSelector(site).getCalleeTarget(caller, site, callee, receiver);
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return getSelector(site).getRelevantParameters(caller, site);
}
}
| 2,230
| 36.183333
| 97
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.