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/rhino/src/main/java/com/ibm/wala/cast/js/translator/CAstRhinoLoopUnwindingTranslatorFactory.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.classLoader.SourceModule;
public class CAstRhinoLoopUnwindingTranslatorFactory
extends JavaScriptLoopUnwindingTranslatorFactory {
public CAstRhinoLoopUnwindingTranslatorFactory(int unwindFactor) {
super(unwindFactor);
}
public CAstRhinoLoopUnwindingTranslatorFactory() {
this(3);
}
@Override
protected TranslatorToCAst translateInternal(CAst Ast, SourceModule M, String N) {
return new CAstRhinoTranslator(M, true);
}
}
| 976
| 29.53125
| 84
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/main/java/com/ibm/wala/cast/js/translator/CAstRhinoTranslator.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.RewritingTranslatorToCAst;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.classLoader.ModuleEntry;
public class CAstRhinoTranslator extends RewritingTranslatorToCAst {
public CAstRhinoTranslator(ModuleEntry m, boolean replicateForDoLoops) {
super(m, new RhinoToAstTranslator(new CAstImpl(), m, m.getName(), replicateForDoLoops));
}
}
| 817
| 36.181818
| 92
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/main/java/com/ibm/wala/cast/js/translator/CAstRhinoTranslatorFactory.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.classLoader.ModuleEntry;
public class CAstRhinoTranslatorFactory implements JavaScriptTranslatorFactory {
@Override
public TranslatorToCAst make(CAst ast, ModuleEntry M) {
return new CAstRhinoTranslator(M, false);
}
}
| 753
| 30.416667
| 80
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/main/java/com/ibm/wala/cast/js/translator/RhinoToAstTranslator.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.js.html.MappedSourceModule;
import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.tree.CAst;
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.impl.CAstOperator;
import com.ibm.wala.cast.tree.impl.CAstSymbolImpl;
import com.ibm.wala.cast.tree.impl.RangePosition;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter.CopyKey;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter.RewriteContext;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.cast.tree.visit.CAstVisitor;
import com.ibm.wala.cast.util.CAstPattern;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.core.util.warnings.Warning;
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.debug.Assertions;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.Node;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.Token;
import org.mozilla.javascript.ast.ArrayComprehension;
import org.mozilla.javascript.ast.ArrayComprehensionLoop;
import org.mozilla.javascript.ast.ArrayLiteral;
import org.mozilla.javascript.ast.Assignment;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.AstRoot;
import org.mozilla.javascript.ast.Block;
import org.mozilla.javascript.ast.BreakStatement;
import org.mozilla.javascript.ast.CatchClause;
import org.mozilla.javascript.ast.Comment;
import org.mozilla.javascript.ast.ConditionalExpression;
import org.mozilla.javascript.ast.ContinueStatement;
import org.mozilla.javascript.ast.DoLoop;
import org.mozilla.javascript.ast.ElementGet;
import org.mozilla.javascript.ast.EmptyExpression;
import org.mozilla.javascript.ast.EmptyStatement;
import org.mozilla.javascript.ast.ErrorNode;
import org.mozilla.javascript.ast.ExpressionStatement;
import org.mozilla.javascript.ast.ForInLoop;
import org.mozilla.javascript.ast.ForLoop;
import org.mozilla.javascript.ast.FunctionCall;
import org.mozilla.javascript.ast.FunctionNode;
import org.mozilla.javascript.ast.IfStatement;
import org.mozilla.javascript.ast.InfixExpression;
import org.mozilla.javascript.ast.Jump;
import org.mozilla.javascript.ast.KeywordLiteral;
import org.mozilla.javascript.ast.Label;
import org.mozilla.javascript.ast.LabeledStatement;
import org.mozilla.javascript.ast.LetNode;
import org.mozilla.javascript.ast.Name;
import org.mozilla.javascript.ast.NewExpression;
import org.mozilla.javascript.ast.NumberLiteral;
import org.mozilla.javascript.ast.ObjectLiteral;
import org.mozilla.javascript.ast.ObjectProperty;
import org.mozilla.javascript.ast.ParenthesizedExpression;
import org.mozilla.javascript.ast.PropertyGet;
import org.mozilla.javascript.ast.RegExpLiteral;
import org.mozilla.javascript.ast.ReturnStatement;
import org.mozilla.javascript.ast.Scope;
import org.mozilla.javascript.ast.ScriptNode;
import org.mozilla.javascript.ast.StringLiteral;
import org.mozilla.javascript.ast.SwitchCase;
import org.mozilla.javascript.ast.SwitchStatement;
import org.mozilla.javascript.ast.Symbol;
import org.mozilla.javascript.ast.ThrowStatement;
import org.mozilla.javascript.ast.TryStatement;
import org.mozilla.javascript.ast.UnaryExpression;
import org.mozilla.javascript.ast.UpdateExpression;
import org.mozilla.javascript.ast.VariableDeclaration;
import org.mozilla.javascript.ast.VariableInitializer;
import org.mozilla.javascript.ast.WhileLoop;
import org.mozilla.javascript.ast.WithStatement;
import org.mozilla.javascript.ast.XmlDotQuery;
import org.mozilla.javascript.ast.XmlElemRef;
import org.mozilla.javascript.ast.XmlExpression;
import org.mozilla.javascript.ast.XmlFragment;
import org.mozilla.javascript.ast.XmlLiteral;
import org.mozilla.javascript.ast.XmlMemberGet;
import org.mozilla.javascript.ast.XmlPropRef;
import org.mozilla.javascript.ast.XmlRef;
import org.mozilla.javascript.ast.XmlString;
import org.mozilla.javascript.ast.Yield;
public class RhinoToAstTranslator implements TranslatorToCAst {
/**
* a dummy name to use for standard function calls, only used to distinguish them from constructor
* calls
*/
public static final String STANDARD_CALL_FN_NAME = "do";
/** name used for constructor calls, used to distinguish them from standard function calls */
public static final String CTOR_CALL_FN_NAME = "ctor";
private final boolean DEBUG = false;
/**
* shared interface for all objects storing contextual information during the Rhino AST traversal
*/
private interface WalkContext extends JavaScriptTranslatorToCAst.WalkContext<WalkContext, Node> {}
/** default implementation of WalkContext; methods do nothing / return null */
private static class RootContext extends JavaScriptTranslatorToCAst.RootContext<WalkContext, Node>
implements WalkContext {}
/** context used for function / script declarations */
private static class FunctionContext
extends JavaScriptTranslatorToCAst.FunctionContext<WalkContext, Node> implements WalkContext {
FunctionContext(WalkContext parent, Node s) {
super(parent, s);
}
}
/** context used for top-level script declarations */
private static class ScriptContext extends FunctionContext {
private final String script;
ScriptContext(WalkContext parent, ScriptNode s, String script) {
super(parent, s);
this.script = script;
}
@Override
public String script() {
return script;
}
}
private static class MemberDestructuringContext
extends JavaScriptTranslatorToCAst.MemberDestructuringContext<WalkContext, Node>
implements WalkContext {
protected MemberDestructuringContext(
WalkContext parent, Node initialBaseFor, int operationIndex) {
super(parent, initialBaseFor, operationIndex);
}
}
private static class BreakContext
extends JavaScriptTranslatorToCAst.BreakContext<WalkContext, Node> implements WalkContext {
@Override
public WalkContext getParent() {
return (WalkContext) super.getParent();
}
BreakContext(WalkContext parent, Node breakTo, String label) {
super(parent, breakTo, label);
}
}
private static class LoopContext extends TranslatorToCAst.LoopContext<WalkContext, Node>
implements WalkContext {
LoopContext(WalkContext parent, Node breakTo, Node continueTo, String label) {
super(parent, breakTo, continueTo, label);
}
@Override
public WalkContext getParent() {
return (WalkContext) super.getParent();
}
}
private static class TryCatchContext extends TranslatorToCAst.TryCatchContext<WalkContext, Node>
implements WalkContext {
TryCatchContext(WalkContext parent, CAstNode catchNode) {
super(parent, catchNode);
}
@Override
public WalkContext getParent() {
return (WalkContext) super.getParent();
}
}
private static String operationReceiverName(int operationIndex) {
return "$$destructure$rcvr" + operationIndex;
}
private CAstNode operationReceiverVar(int operationIndex) {
return Ast.makeNode(CAstNode.VAR, Ast.makeConstant(operationReceiverName(operationIndex)));
}
private static String operationElementName(int operationIndex) {
return "$$destructure$elt" + operationIndex;
}
private CAstNode operationElementVar(int operationIndex) {
return Ast.makeNode(CAstNode.VAR, Ast.makeConstant(operationElementName(operationIndex)));
}
private static CAstNode translateOpcode(int nodeType) {
switch (nodeType) {
case Token.POS:
case Token.ADD:
case Token.ASSIGN_ADD:
return CAstOperator.OP_ADD;
case Token.DIV:
case Token.ASSIGN_DIV:
return CAstOperator.OP_DIV;
case Token.ASSIGN_LSH:
case Token.LSH:
return CAstOperator.OP_LSH;
case Token.MOD:
case Token.ASSIGN_MOD:
return CAstOperator.OP_MOD;
case Token.MUL:
case Token.ASSIGN_MUL:
return CAstOperator.OP_MUL;
case Token.RSH:
case Token.ASSIGN_RSH:
return CAstOperator.OP_RSH;
case Token.SUB:
case Token.NEG:
case Token.ASSIGN_SUB:
return CAstOperator.OP_SUB;
case Token.URSH:
case Token.ASSIGN_URSH:
return CAstOperator.OP_URSH;
case Token.BITAND:
case Token.ASSIGN_BITAND:
return CAstOperator.OP_BIT_AND;
case Token.BITOR:
case Token.ASSIGN_BITOR:
return CAstOperator.OP_BIT_OR;
case Token.BITXOR:
case Token.ASSIGN_BITXOR:
return CAstOperator.OP_BIT_XOR;
case Token.EQ:
case Token.IFEQ:
return CAstOperator.OP_EQ;
case Token.SHEQ:
return CAstOperator.OP_STRICT_EQ;
case Token.GE:
return CAstOperator.OP_GE;
case Token.GT:
return CAstOperator.OP_GT;
case Token.LE:
return CAstOperator.OP_LE;
case Token.LT:
return CAstOperator.OP_LT;
case Token.NE:
case Token.IFNE:
return CAstOperator.OP_NE;
case Token.SHNE:
return CAstOperator.OP_STRICT_NE;
case Token.BITNOT:
return CAstOperator.OP_BITNOT;
case Token.NOT:
return CAstOperator.OP_NOT;
default:
Assertions.UNREACHABLE();
return null;
}
}
private CAstNode makeBuiltinNew(String typeName) {
return Ast.makeNode(CAstNode.NEW, Ast.makeConstant(typeName));
}
private CAstNode handleNew(WalkContext context, String globalName, List<CAstNode> arguments) {
return handleNew(context, readName(context, null, globalName), arguments);
}
private CAstNode handleNew(WalkContext context, CAstNode value, List<CAstNode> arguments) {
return makeCtorCall(value, arguments, context);
}
private static boolean isPrologueScript(WalkContext context) {
return JavaScriptLoader.bootstrapFileNames.contains(context.script());
}
private static Node getCallTarget(FunctionCall n) {
return n.getTarget();
}
/** is n a call to "primitive" within our synthetic modeling code? */
private static boolean isPrimitiveCall(WalkContext context, FunctionCall n) {
return isPrologueScript(context)
&& n.getType() == Token.CALL
&& getCallTarget(n).getType() == Token.NAME
&& getCallTarget(n).getString().equals("primitive");
}
private static Node getNewTarget(NewExpression n) {
return n.getTarget();
}
private static boolean isPrimitiveCreation(WalkContext context, NewExpression n) {
Node target = getNewTarget(n);
return isPrologueScript(context)
&& n.getType() == Token.NEW
&& target.getType() == Token.NAME
&& target.getString().equals("Primitives");
}
private CAstNode makeCall(
CAstNode fun, CAstNode thisptr, List<CAstNode> args, WalkContext context) {
return makeCall(fun, thisptr, args, context, STANDARD_CALL_FN_NAME);
}
private CAstNode makeCtorCall(CAstNode thisptr, List<CAstNode> args, WalkContext context) {
return makeCall(thisptr, null, args, context, CTOR_CALL_FN_NAME);
}
private CAstNode makeCall(
CAstNode fun, CAstNode thisptr, List<CAstNode> args, WalkContext context, String callee) {
int children = (args == null) ? 0 : args.size();
// children of CAst CALL node are the expression that evaluates to the
// function, followed by a name (either STANDARD_CALL_FN_NAME or
// CTOR_CALL_FN_NAME), followed by the actual
// parameters
int nargs = (thisptr == null) ? children + 2 : children + 3;
List<CAstNode> arguments = new ArrayList<>(nargs);
arguments.add(fun);
// assert callee.equals(STANDARD_CALL_FN_NAME) || callee.equals(CTOR_CALL_FN_NAME);
arguments.add(Ast.makeConstant(callee));
if (thisptr != null) arguments.add(thisptr);
if (args != null) {
arguments.addAll(args);
}
CAstNode call = Ast.makeNode(CAstNode.CALL, arguments);
context.cfg().map(call, call);
if (context.getCatchTarget() != null) {
context.cfg().add(call, context.getCatchTarget(), null);
}
return call;
}
/** Used to represent a script or function in the CAst; see walkEntity(). */
private class ScriptOrFnEntity implements CAstEntity {
private final String[] arguments;
private final String name;
private final int kind;
private final Map<CAstNode, Collection<CAstEntity>> subs;
private final CAstNode ast;
private final CAstControlFlowMap map;
private final CAstSourcePositionMap pos;
private final Position entityPosition;
private final Position namePosition;
private final Position[] paramPositions;
private ScriptOrFnEntity(
AstNode n,
Map<CAstNode, Collection<CAstEntity>> subs,
CAstNode ast,
CAstControlFlowMap map,
CAstSourcePositionMap pos,
String name) {
this.name = name;
this.entityPosition = pos.getPosition(ast);
if (n instanceof FunctionNode) {
FunctionNode f = (FunctionNode) n;
namePosition = makePosition(f.getFunctionName());
f.flattenSymbolTable(false);
int i = 0;
// The name of the function is declared within the scope of the function itself if it is a
// function expression. Otherwise, the name is declared in the same scope as the function
// declaration.
boolean isFunctionExpression =
f.getFunctionType() == FunctionNode.FUNCTION_EXPRESSION
|| f.getFunctionType() == FunctionNode.FUNCTION_EXPRESSION_STATEMENT;
arguments = new String[f.getParamCount() + 2];
if (isFunctionExpression) {
arguments[i++] = name;
} else {
// Obfuscate the name, so any references within the method to the actual function name
// become lexical accesses. We still need to keep the argument since in the WALA IR for
// JavaScript calls, the function value itself is always passed as the first argument.
arguments[i++] = "__WALA__int3rnal__fn__" + name;
}
arguments[i++] = "this";
for (int j = 0; j < f.getParamCount(); j++) {
arguments[i++] = f.getParamOrVarName(j);
}
List<AstNode> params = f.getParams();
paramPositions = new Position[params.size()];
for (int pi = 0; pi < params.size(); pi++) {
paramPositions[pi] = makePosition(params.get(pi));
}
} else {
paramPositions = new Position[0];
arguments = new String[0];
namePosition = null;
}
kind = (n instanceof FunctionNode) ? CAstEntity.FUNCTION_ENTITY : CAstEntity.SCRIPT_ENTITY;
this.subs = subs;
this.ast = ast;
this.map = map;
this.pos = pos;
}
@Override
public String toString() {
return "<JS function " + getName() + '>';
}
@Override
public String getName() {
return name;
}
@Override
public String getSignature() {
Assertions.UNREACHABLE();
return null;
}
@Override
public int getKind() {
return kind;
}
@Override
public String[] getArgumentNames() {
return arguments;
}
@Override
public CAstNode[] getArgumentDefaults() {
return new CAstNode[0];
}
@Override
public int getArgumentCount() {
return arguments.length;
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
return Collections.unmodifiableMap(subs);
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
if (subs.containsKey(construct)) return subs.get(construct).iterator();
else return EmptyIterator.instance();
}
@Override
public CAstNode getAST() {
return ast;
}
@Override
public CAstControlFlowMap getControlFlow() {
return map;
}
@Override
public CAstSourcePositionMap getSourceMap() {
return pos;
}
@Override
public CAstSourcePositionMap.Position getPosition() {
return entityPosition;
}
@Override
public CAstNodeTypeMap getNodeTypeMap() {
return null;
}
@Override
public Collection<CAstAnnotation> getAnnotations() {
return null;
}
@Override
public Collection<CAstQualifier> getQualifiers() {
Assertions.UNREACHABLE("JuliansUnnamedCAstEntity$2.getQualifiers()");
return null;
}
@Override
public CAstType getType() {
return JSAstTranslator.Any;
}
@Override
public Position getPosition(int arg) {
return paramPositions[arg];
}
@Override
public Position getNamePosition() {
return namePosition;
}
}
private CAstEntity walkEntity(
final AstNode n, List<CAstNode> body, String name, WalkContext child) {
final List<CAstNode> stmts;
// add variable / constant / function declarations, if any
if (!child.getNameDecls().isEmpty()) {
// new first statement will be a block declaring all names.
stmts = new ArrayList<>(body.size() + 1);
stmts.add(
child.getNameDecls().size() == 1
? child.getNameDecls().iterator().next()
: Ast.makeNode(CAstNode.BLOCK_STMT, child.getNameDecls()));
stmts.addAll(body);
} else stmts = new ArrayList<>(body);
final CAstNode ast = noteSourcePosition(child, Ast.makeNode(CAstNode.BLOCK_STMT, stmts), n);
final CAstControlFlowMap map = child.cfg();
final CAstSourcePositionMap pos = child.pos();
// not sure if we need this copy --MS
final Map<CAstNode, Collection<CAstEntity>> subs =
HashMapFactory.make(child.getScopedEntities());
return new ScriptOrFnEntity(n, subs, ast, map, pos, name);
}
private Position makePosition(AstNode n) {
if (n != null) {
URL url = ((SourceModule) sourceModule).getURL();
int line = n.getLineno();
Position pos =
new RangePosition(
url, line, n.getAbsolutePosition(), n.getAbsolutePosition() + n.getLength());
if (sourceModule instanceof MappedSourceModule) {
Position np = ((MappedSourceModule) sourceModule).getMapping().getIncludedPosition(pos);
if (np != null) {
return np;
}
}
return pos;
} else {
return null;
}
}
protected CAstNode noteSourcePosition(WalkContext context, CAstNode n, AstNode p) {
if (p.getLineno() != -1 && context.pos().getPosition(n) == null) {
pushSourcePosition(context, n, makePosition(p));
}
return n;
}
private CAstNode readName(WalkContext context, AstNode node, String name) {
CAstNode cn = makeVarRef(name);
if (node != null) {
context.cfg().map(node, cn);
} else {
context.cfg().map(cn, cn);
}
CAstNode target = context.getCatchTarget();
context
.cfg()
.add(
cn,
Objects.requireNonNullElse(target, CAstControlFlowMap.EXCEPTION_TO_EXIT),
JavaScriptTypes.ReferenceError);
return cn;
}
private static List<Label> getLabels(AstNode node) {
if (node instanceof LabeledStatement
|| ((node = node.getParent()) instanceof LabeledStatement)) {
return ((LabeledStatement) node).getLabels();
} else {
return null;
}
}
private static AstNode makeEmptyLabelStmt(String label) {
Label l = new Label();
l.setName(label);
LabeledStatement st = new LabeledStatement();
st.addLabel(l);
ExpressionStatement ex = new ExpressionStatement();
ex.setExpression(new EmptyExpression());
st.setStatement(ex);
return st;
}
private static WalkContext makeLoopContext(
AstNode node, WalkContext arg, AstNode breakStmt, AstNode contStmt) {
WalkContext loopContext = arg;
List<Label> labels = getLabels(node);
if (labels == null) {
loopContext = new LoopContext(loopContext, breakStmt, contStmt, null);
} else {
for (Label l : labels) {
loopContext = new LoopContext(loopContext, breakStmt, contStmt, l.getName());
}
}
return loopContext;
}
private static WalkContext makeBreakContext(AstNode node, WalkContext arg, AstNode breakStmt) {
WalkContext loopContext = arg;
List<Label> labels = getLabels(node);
if (labels == null) {
loopContext = new BreakContext(loopContext, breakStmt, null);
} else {
for (Label l : labels) {
loopContext = new BreakContext(loopContext, breakStmt, l.getName());
}
}
return loopContext;
}
private class TranslatingVisitor extends TypedNodeVisitor<CAstNode, WalkContext> {
@Override
public CAstNode visit(AstNode node, WalkContext arg) {
CAstNode ast = super.visit(node, arg);
return noteSourcePosition(arg, ast, node);
}
@Override
public CAstNode visitArrayComprehension(ArrayComprehension node, WalkContext arg) {
// TODO Auto-generated method stub
assert false;
return null;
}
@Override
public CAstNode visitArrayComprehensionLoop(ArrayComprehensionLoop node, WalkContext arg) {
// TODO Auto-generated method stub
assert false;
return null;
}
@Override
public CAstNode visitArrayLiteral(ArrayLiteral node, WalkContext arg) {
int index = 0;
List<CAstNode> eltNodes = new ArrayList<>(2 * node.getElements().size());
eltNodes.add(
(isPrologueScript(arg) ? makeBuiltinNew("Array") : handleNew(arg, "Array", null)));
for (AstNode elt : node.getElements()) {
if (elt instanceof EmptyExpression) {
index++;
} else {
eltNodes.add(Ast.makeConstant(String.valueOf(index++)));
eltNodes.add(visit(elt, arg));
}
}
CAstNode lit = Ast.makeNode(CAstNode.OBJECT_LITERAL, eltNodes);
arg.cfg().map(node, lit);
return lit;
}
@Override
public CAstNode visitAssignment(Assignment node, WalkContext arg) {
if (node.getType() == Token.ASSIGN) {
return Ast.makeNode(
CAstNode.ASSIGN, visit(node.getLeft(), arg), visit(node.getRight(), arg));
} else {
return Ast.makeNode(
CAstNode.ASSIGN_POST_OP,
visit(node.getLeft(), arg),
visit(node.getRight(), arg),
translateOpcode(node.getOperator()));
}
}
@Override
public CAstNode visitAstRoot(AstRoot node, WalkContext arg) {
List<CAstNode> children = new ArrayList<>(node.getStatements().size());
for (AstNode n : node.getStatements()) {
children.add(this.visit(n, arg));
}
return Ast.makeNode(CAstNode.BLOCK_STMT, children);
}
@Override
public CAstNode visitBlock(Block node, WalkContext arg) {
List<CAstNode> nodes = new ArrayList<>();
for (Node child : node) {
nodes.add(visit((AstNode) child, arg));
}
return Ast.makeNode(nodes.isEmpty() ? CAstNode.EMPTY : CAstNode.BLOCK_STMT, nodes);
}
@Override
public CAstNode visitBreakStatement(BreakStatement node, WalkContext arg) {
CAstNode breakStmt;
Node target;
if (node.getBreakLabel() != null) {
breakStmt =
Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(node.getBreakLabel().getIdentifier()));
target = arg.getBreakFor(node.getBreakLabel().getIdentifier());
} else {
breakStmt = Ast.makeNode(CAstNode.GOTO);
target = arg.getBreakFor(null);
}
arg.cfg().map(node, breakStmt);
arg.cfg().add(node, target, null);
return breakStmt;
}
@Override
public CAstNode visitCatchClause(CatchClause node, WalkContext arg) {
return visit(node.getBody(), arg);
}
@Override
public CAstNode visitComment(Comment node, WalkContext arg) {
return Ast.makeNode(CAstNode.EMPTY);
}
@Override
public CAstNode visitConditionalExpression(ConditionalExpression node, WalkContext arg) {
return Ast.makeNode(
CAstNode.IF_EXPR,
visit(node.getTestExpression(), arg),
visit(node.getTrueExpression(), arg),
visit(node.getFalseExpression(), arg));
}
@Override
public CAstNode visitContinueStatement(ContinueStatement node, WalkContext arg) {
CAstNode continueStmt;
Node target;
if (node.getLabel() != null) {
continueStmt =
Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(node.getLabel().getIdentifier()));
target = arg.getContinueFor(node.getLabel().getIdentifier());
} else {
continueStmt = Ast.makeNode(CAstNode.GOTO);
target = arg.getContinueFor(null);
}
arg.cfg().map(node, continueStmt);
arg.cfg().add(node, target, null);
return continueStmt;
}
@Override
public CAstNode visitDoLoop(DoLoop node, WalkContext arg) {
CAstNode loopTest = visit(node.getCondition(), arg);
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, arg);
AstNode contStmt = makeEmptyLabelStmt("contLabel");
CAstNode contLabel = visit(contStmt, arg);
WalkContext loopContext = makeLoopContext(node, arg, breakStmt, contStmt);
CAstNode loopBody = visit(node.getBody(), loopContext);
CAstNode loop =
doLoopTranslator.translateDoLoop(loopTest, loopBody, contLabel, breakLabel, arg);
arg.cfg().map(node, loop);
return loop;
}
private CAstNode visitObjectRead(AstNode n, AstNode objAst, CAstNode elt, WalkContext context) {
CAstNode get, result;
int operationIndex = context.setOperation(n);
CAstNode obj = visit(objAst, context);
if (operationIndex != -1) {
get = null;
result =
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(CAstNode.ASSIGN, operationReceiverVar(operationIndex), obj),
Ast.makeNode(CAstNode.ASSIGN, operationElementVar(operationIndex), elt));
} else {
result = get = Ast.makeNode(CAstNode.OBJECT_REF, obj, elt);
}
if (get != null) {
context.cfg().map(get, get);
context
.cfg()
.add(
get,
context.getCatchTarget() != null
? context.getCatchTarget()
: CAstControlFlowMap.EXCEPTION_TO_EXIT,
JavaScriptTypes.TypeError);
}
return result;
}
@Override
public CAstNode visitElementGet(ElementGet node, WalkContext arg) {
return visitObjectRead(node, node.getTarget(), visit(node.getElement(), arg), arg);
}
@Override
public CAstNode visitEmptyExpression(EmptyExpression node, WalkContext arg) {
return Ast.makeNode(CAstNode.EMPTY);
}
@Override
public CAstNode visitEmptyStatement(EmptyStatement node, WalkContext arg) {
return Ast.makeNode(CAstNode.EMPTY);
}
@Override
public CAstNode visitErrorNode(ErrorNode node, WalkContext arg) {
assert false;
return null;
}
@Override
public CAstNode visitExpressionStatement(ExpressionStatement node, WalkContext arg) {
return visit(node.getExpression(), arg);
}
@Override
public CAstNode visitForInLoop(ForInLoop node, WalkContext arg) {
CAstNode loop;
CAstNode get;
CAstNode object = visit(node.getIteratedObject(), arg);
String name;
AstNode var = node.getIterator();
if (!(var instanceof Name || var instanceof VariableDeclaration || var instanceof LetNode)) {
String V = "$$V";
CAstNode obj =
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl("$$obj", JSAstTranslator.Any)),
object);
arg.addNameDecl(
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(V, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")));
arg.addNameDecl(
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl("$$P", JSAstTranslator.Any)),
readName(arg, null, "$$undefined")));
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, arg);
AstNode contStmt = makeEmptyLabelStmt("contLabel");
CAstNode contLabel = visit(contStmt, arg);
WalkContext loopContext = makeLoopContext(node, arg, breakStmt, contStmt);
loop =
Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(
CAstNode.BLOCK_STMT,
obj,
contLabel,
Ast.makeNode(
CAstNode.LOOP,
Ast.makeNode(
CAstNode.BINARY_EXPR,
CAstOperator.OP_NE,
Ast.makeConstant(null),
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("$$P")),
get =
Ast.makeNode(
CAstNode.EACH_ELEMENT_GET,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("$$obj")),
readName(arg, null, "$$P"))),
Ast.makeNode(
CAstNode.ASSIGN,
visit(var, loopContext),
readName(arg, null, "$$P")),
readName(arg, null, "$$P"))),
visit(node.getBody(), loopContext)),
breakLabel));
arg.cfg().map(node, loop);
arg.cfg().map(get, get);
CAstNode ctch = arg.getCatchTarget();
arg.cfg()
.add(
get,
Objects.requireNonNullElse(ctch, CAstControlFlowMap.EXCEPTION_TO_EXIT),
JavaScriptTypes.ReferenceError);
return loop;
}
// TODO: fix the correlation-tracking rewriters, and kill the old for..in translation
// set up
String tempName = "for in loop temp";
CAstNode[] loopHeader =
new CAstNode[] {
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(tempName, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")),
Ast.makeNode(
CAstNode.ASSIGN, Ast.makeNode(CAstNode.VAR, Ast.makeConstant(tempName)), object)
};
if (useNewForIn) {
assert var instanceof Name || var instanceof VariableDeclaration || var instanceof LetNode
: var.getClass() + " " + var;
if (var instanceof Name) {
name = ((Name) var).getString();
} else {
VariableDeclaration decl;
if (var instanceof LetNode) {
decl = ((LetNode) var).getVariables();
} else {
decl = (VariableDeclaration) var;
}
assert decl.getVariables().size() == 1;
VariableInitializer init = decl.getVariables().iterator().next();
name = init.getTarget().getString();
arg.addNameDecl(
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(name, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")));
}
// body
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, arg);
AstNode contStmt = makeEmptyLabelStmt("contLabel");
CAstNode contLabel = visit(contStmt, arg);
// TODO: Figure out why this is needed to make the correlation extraction tests pass
// TODO: remove this silly label
AstNode garbageStmt = makeEmptyLabelStmt("garbageLabel");
CAstNode garbageLabel = visit(garbageStmt, arg);
WalkContext loopContext = makeLoopContext(node, arg, breakStmt, contStmt);
CAstNode body =
Ast.makeNode(
CAstNode.BLOCK_STMT,
// initNode,
visit(node.getBody(), loopContext),
garbageLabel);
loop =
Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(
CAstNode.BLOCK_STMT,
loopHeader[0],
loopHeader[1],
contLabel,
Ast.makeNode(
CAstNode.LOOP,
Ast.makeNode(
CAstNode.BINARY_EXPR,
CAstOperator.OP_NE,
Ast.makeConstant(null),
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(name)),
get =
Ast.makeNode(
CAstNode.EACH_ELEMENT_GET,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(tempName)),
readName(arg, null, name))),
readName(arg, null, name))),
body),
breakLabel));
} else {
CAstNode initNode;
assert var instanceof Name || var instanceof VariableDeclaration || var instanceof LetNode
: var.getClass() + " " + var + " " + var.getLineno() + ":" + var.getPosition();
if (var instanceof Name) {
name = ((Name) var).getString();
} else {
VariableDeclaration decl;
if (var instanceof LetNode) {
decl = ((LetNode) var).getVariables();
} else {
decl = (VariableDeclaration) var;
}
assert decl.getVariables().size() == 1;
VariableInitializer init = decl.getVariables().iterator().next();
name = init.getTarget().getString();
arg.addNameDecl(
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(name, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")));
}
initNode =
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(name)),
get =
Ast.makeNode(
CAstNode.EACH_ELEMENT_GET,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(tempName)),
readName(arg, null, name)));
arg.cfg().map(get, get);
CAstNode ctch = arg.getCatchTarget();
arg.cfg()
.add(
get,
Objects.requireNonNullElse(ctch, CAstControlFlowMap.EXCEPTION_TO_EXIT),
JavaScriptTypes.ReferenceError);
// body
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, arg);
AstNode contStmt = makeEmptyLabelStmt("contLabel");
CAstNode contLabel = visit(contStmt, arg);
// TODO: Figure out why this is needed to make the correlation extraction tests pass
// TODO: remove this silly label
AstNode garbageStmt = makeEmptyLabelStmt("garbageLabel");
CAstNode garbageLabel = visit(garbageStmt, arg);
WalkContext loopContext = makeLoopContext(node, arg, breakStmt, contStmt);
CAstNode body =
Ast.makeNode(
CAstNode.BLOCK_STMT, initNode, visit(node.getBody(), loopContext), garbageLabel);
loop =
Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(
CAstNode.BLOCK_STMT,
loopHeader[0],
loopHeader[1],
contLabel,
Ast.makeNode(
CAstNode.LOOP,
Ast.makeNode(
CAstNode.BINARY_EXPR,
CAstOperator.OP_NE,
Ast.makeConstant(null),
get =
Ast.makeNode(
CAstNode.EACH_ELEMENT_GET,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(tempName)),
readName(arg, null, name))),
body),
breakLabel));
}
arg.cfg().map(node, loop);
arg.cfg().map(get, get);
CAstNode ctch = arg.getCatchTarget();
arg.cfg()
.add(
get,
Objects.requireNonNullElse(ctch, CAstControlFlowMap.EXCEPTION_TO_EXIT),
JavaScriptTypes.ReferenceError);
return loop;
}
@Override
public CAstNode visitForLoop(ForLoop node, WalkContext arg) {
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, arg);
AstNode contStmt = makeEmptyLabelStmt("contLabel");
CAstNode contLabel = visit(contStmt, arg);
WalkContext loopContext = makeLoopContext(node, arg, breakStmt, contStmt);
CAstNode loop;
CAstNode top =
Ast.makeNode(
CAstNode.BLOCK_STMT,
visit(node.getInitializer(), arg),
loop =
Ast.makeNode(
CAstNode.LOOP,
visit(node.getCondition(), arg),
Ast.makeNode(
CAstNode.BLOCK_STMT,
visit(node.getBody(), loopContext),
contLabel,
visit(node.getIncrement(), arg))),
breakLabel);
arg.cfg().map(node, loop);
return top;
}
private List<CAstNode> gatherCallArguments(Node call, WalkContext context) {
List<AstNode> nodes = ((FunctionCall) call).getArguments();
List<CAstNode> args = new ArrayList<>(nodes.size());
for (AstNode node : nodes) {
args.add(visit(node, context));
}
return args;
}
@Override
public CAstNode visitFunctionCall(FunctionCall n, WalkContext context) {
if (!isPrimitiveCall(context, n)) {
AstNode callee = n.getTarget();
int thisBaseVarNum = ++tempVarNum;
WalkContext child = new MemberDestructuringContext(context, callee, thisBaseVarNum);
CAstNode fun = visit(callee, child);
// the first actual parameter appearing within the parentheses of the
// call (i.e., possibly excluding the 'this' parameter)
List<CAstNode> args = gatherCallArguments(n, context);
if (child.foundMemberOperation(callee))
return Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new CAstSymbolImpl(
operationReceiverName(thisBaseVarNum), JSAstTranslator.Any)),
Ast.makeConstant(null)),
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new CAstSymbolImpl(
operationElementName(thisBaseVarNum), JSAstTranslator.Any)),
Ast.makeConstant(null)),
fun,
makeCall(
operationElementVar(thisBaseVarNum),
operationReceiverVar(thisBaseVarNum),
args,
context,
"dispatch")));
else {
CAstNode globalRef = makeVarRef(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME);
context.cfg().map(globalRef, globalRef);
return makeCall(fun, globalRef, args, context);
}
} else {
return Ast.makeNode(CAstNode.PRIMITIVE, gatherCallArguments(n, context));
}
}
private String getParentName(AstNode fn) {
for (int i = 5; fn != null && i > 0; i--, fn = fn.getParent()) {
if (fn instanceof ObjectProperty) {
ObjectProperty prop = (ObjectProperty) fn;
AstNode label = prop.getLeft();
if (label instanceof Name) {
return ((Name) label).getString();
}
}
}
return null;
}
@Override
public CAstNode visitFunctionNode(FunctionNode fn, WalkContext context) {
WalkContext child = new FunctionContext(context, fn);
List<CAstNode> body = new ArrayList<>();
body.add(visit(fn.getBody(), child));
String name;
Name x = fn.getFunctionName();
if (x == null || x.getIdentifier() == null || x.getIdentifier().isEmpty()) {
name = scriptName + '@' + fn.getAbsolutePosition();
String label = getParentName(fn);
if (label != null) {
name = name + ':' + label;
}
} else {
name = fn.getFunctionName().getIdentifier();
if (fn.getFunctionType() == FunctionNode.FUNCTION_EXPRESSION) {
// there is a possibility of another function expression in the same scope with the same
// name. check for that case and use a different name when it occurs. the checking code
// looks for CAstNode keys in the context's scoped entities map constructed for function
// expressions
boolean nameExists =
context.getScopedEntities().keySet().stream()
.filter(
n ->
n != null
&& n.getKind() == CAstNode.FUNCTION_EXPR
&& n.getChildCount() == 1)
.map(n -> n.getChild(0))
.filter(
n -> n.getKind() == CAstNode.CONSTANT && n.getValue() instanceof CAstEntity)
.map(n -> ((CAstEntity) n.getValue()).getName())
.anyMatch(name::equals);
if (nameExists) {
name = name + '@' + fn.getAbsolutePosition();
}
}
}
if (DEBUG) System.err.println(name + '\n' + body);
CAstEntity fne = walkEntity(fn, body, name, child);
if (DEBUG) System.err.println(fne.getName());
if (fn.getFunctionType() == FunctionNode.FUNCTION_EXPRESSION) {
CAstNode fun = Ast.makeNode(CAstNode.FUNCTION_EXPR, Ast.makeConstant(fne));
context.addScopedEntity(fun, fne);
return fun;
} else {
context.addNameDecl(Ast.makeNode(CAstNode.FUNCTION_STMT, Ast.makeConstant(fne)));
context.addScopedEntity(null, fne);
return Ast.makeNode(CAstNode.EMPTY);
}
}
@Override
public CAstNode visitIfStatement(IfStatement node, WalkContext arg) {
if (node.getElsePart() != null) {
return Ast.makeNode(
CAstNode.IF_STMT,
visit(node.getCondition(), arg),
visit(node.getThenPart(), arg),
visit(node.getElsePart(), arg));
} else {
return Ast.makeNode(
CAstNode.IF_STMT, visit(node.getCondition(), arg), visit(node.getThenPart(), arg));
}
}
@Override
public CAstNode visitInfixExpression(InfixExpression node, WalkContext arg) {
if (node.getType() == Token.OR) {
CAstNode l = visit(node.getLeft(), arg);
CAstNode r = visit(node.getRight(), arg);
return Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl("or temp", JSAstTranslator.Any)),
l),
Ast.makeNode(
CAstNode.IF_EXPR,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("or temp")),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("or temp")),
r)));
} else if (node.getType() == Token.AND) {
CAstNode l = visit(node.getLeft(), arg);
CAstNode r = visit(node.getRight(), arg);
return Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(
CAstNode.BLOCK_EXPR,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl("and temp", JSAstTranslator.Any)),
l),
Ast.makeNode(
CAstNode.IF_EXPR,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("and temp")),
r,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("and temp")))));
} else if (node.getType() == Token.COMMA) {
return Ast.makeNode(
CAstNode.BLOCK_EXPR, visit(node.getLeft(), arg), visit(node.getRight(), arg));
} else if (node.getType() == Token.IN) {
AstNode value = node.getLeft();
AstNode property = node.getRight();
return Ast.makeNode(CAstNode.IS_DEFINED_EXPR, visit(value, arg), visit(property, arg));
} else if (node.getType() == Token.INSTANCEOF) {
AstNode value = node.getLeft();
AstNode type = node.getRight();
return Ast.makeNode(CAstNode.INSTANCEOF, visit(value, arg), visit(type, arg));
} else {
return Ast.makeNode(
CAstNode.BINARY_EXPR,
translateOpcode(node.getOperator()),
visit(node.getLeft(), arg),
visit(node.getRight(), arg));
}
}
@Override
public CAstNode visitJump(Jump node, WalkContext arg) {
throw new InternalError("should not see jump nodes");
}
@Override
public CAstNode visitKeywordLiteral(KeywordLiteral node, WalkContext arg) {
switch (node.getType()) {
case Token.THIS:
{
if (arg.top() instanceof ScriptNode && !(arg.top() instanceof FunctionNode)) {
CAstNode globalRef = makeVarRef(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME);
arg.cfg().map(globalRef, globalRef);
return globalRef;
} else {
return Ast.makeNode(CAstNode.VAR, Ast.makeConstant("this"));
}
}
case Token.TRUE:
{
return Ast.makeConstant(true);
}
case Token.FALSE:
{
return Ast.makeConstant(false);
}
case Token.NULL:
case Token.DEBUGGER:
{
return Ast.makeConstant(null);
}
default:
throw new RuntimeException(
"unexpected keyword literal " + node + " (" + node.getType() + ')');
}
}
@Override
public CAstNode visitLabel(Label node, WalkContext arg) {
String label = node.getName();
return Ast.makeConstant(label);
}
@Override
public CAstNode visitLabeledStatement(LabeledStatement node, WalkContext arg) {
ExpressionStatement ex = new ExpressionStatement();
ex.setExpression(new EmptyExpression());
CAstNode exNode = visit(ex, arg);
arg.cfg().map(ex, exNode);
WalkContext labelBodyContext = makeBreakContext(node, arg, ex);
CAstNode result = visit(node.getStatement(), labelBodyContext);
AstNode prev = node;
for (Label label : node.getLabels()) {
result = Ast.makeNode(CAstNode.LABEL_STMT, visit(label, arg), result);
arg.cfg().map(prev, result);
prev = label;
}
return Ast.makeNode(CAstNode.BLOCK_STMT, result, exNode);
}
@Override
public CAstNode visitLetNode(LetNode node, WalkContext arg) {
VariableDeclaration decl = node.getVariables();
List<CAstNode> stmts = new ArrayList<>(decl.getVariables().size() + 1);
for (VariableInitializer init : decl.getVariables()) {
stmts.add(
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new CAstSymbolImpl(init.getTarget().getString(), JSAstTranslator.Any)),
visit(init, arg)));
}
stmts.add(visit(node.getBody(), arg));
return Ast.makeNode(CAstNode.LOCAL_SCOPE, stmts);
}
@Override
public CAstNode visitName(Name n, WalkContext context) {
return readName(context, n, n.getString());
}
@Override
public CAstNode visitNewExpression(NewExpression n, WalkContext context) {
if (isPrimitiveCreation(context, n)) {
return makeBuiltinNew(getNewTarget(n).getString());
} else {
AstNode receiver = n.getTarget();
return handleNew(context, visit(receiver, context), gatherCallArguments(n, context));
}
}
@Override
public CAstNode visitNumberLiteral(NumberLiteral node, WalkContext arg) {
return Ast.makeConstant(node.getDouble());
}
@Override
public CAstNode visitObjectLiteral(ObjectLiteral n, WalkContext context) {
List<ObjectProperty> props = n.getElements();
List<CAstNode> args = new ArrayList<>(props.size() * 2 + 1);
args.add(
(isPrologueScript(context)
? makeBuiltinNew("Object")
: handleNew(context, "Object", null)));
for (ObjectProperty prop : props) {
AstNode label = prop.getLeft();
args.add(
(label instanceof Name)
? Ast.makeConstant(((Name) prop.getLeft()).getString())
: visit(label, context));
args.add(visit(prop, context));
}
CAstNode lit = Ast.makeNode(CAstNode.OBJECT_LITERAL, args);
context.cfg().map(n, lit);
return lit;
}
@Override
public CAstNode visitObjectProperty(ObjectProperty node, WalkContext context) {
return visit(node.getRight(), context);
}
@Override
public CAstNode visitParenthesizedExpression(ParenthesizedExpression node, WalkContext arg) {
return visit(node.getExpression(), arg);
}
@Override
public CAstNode visitPropertyGet(PropertyGet node, WalkContext arg) {
CAstNode elt = Ast.makeConstant(node.getProperty().getString());
return visitObjectRead(node, node.getTarget(), elt, arg);
}
@Override
public CAstNode visitRegExpLiteral(RegExpLiteral node, WalkContext arg) {
CAstNode flagsNode = Ast.makeConstant(node.getFlags());
CAstNode valNode = Ast.makeConstant(node.getValue());
return handleNew(arg, "RegExp", Arrays.asList(new CAstNode[] {flagsNode, valNode}));
}
@Override
public CAstNode visitReturnStatement(ReturnStatement node, WalkContext arg) {
AstNode val = node.getReturnValue();
if (val != null) {
return Ast.makeNode(CAstNode.RETURN, visit(val, arg));
} else {
return Ast.makeNode(CAstNode.RETURN);
}
}
@Override
public CAstNode visitScope(Scope node, WalkContext arg) {
List<CAstNode> nodes = new ArrayList<>();
for (Node child : node) {
nodes.add(visit((AstNode) child, arg));
}
if (nodes.isEmpty()) {
return Ast.makeNode(CAstNode.EMPTY);
} else {
return Ast.makeNode(CAstNode.LOCAL_SCOPE, Ast.makeNode(CAstNode.BLOCK_STMT, nodes));
}
}
@Override
public CAstNode visitScriptNode(ScriptNode node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitStringLiteral(StringLiteral node, WalkContext arg) {
return Ast.makeConstant(node.getValue());
}
@Override
public CAstNode visitSwitchCase(SwitchCase node, WalkContext arg) {
if (node.getStatements() == null) {
return Ast.makeNode(CAstNode.EMPTY);
} else {
List<CAstNode> stmts = new ArrayList<>(node.getStatements().size());
for (AstNode statement : node.getStatements()) {
stmts.add(visit(statement, arg));
}
return Ast.makeNode(CAstNode.BLOCK_STMT, stmts);
}
}
@Override
public CAstNode visitSwitchStatement(SwitchStatement node, WalkContext context) {
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, context);
WalkContext switchBodyContext = makeBreakContext(node, context, breakStmt);
int i = 0;
List<CAstNode> children = new ArrayList<>(node.getCases().size() * 2);
for (SwitchCase sc : node.getCases()) {
CAstNode label =
Ast.makeNode(
CAstNode.LABEL_STMT,
Ast.makeConstant(String.valueOf(i / 2)),
Ast.makeNode(CAstNode.EMPTY));
context.cfg().map(label, label);
children.add(label);
if (sc.isDefault()) {
context.cfg().add(node, label, CAstControlFlowMap.SWITCH_DEFAULT);
} else {
CAstNode labelCAst = visit(sc.getExpression(), context);
context.cfg().add(node, label, labelCAst);
}
children.add(visit(sc, switchBodyContext));
}
CAstNode s =
Ast.makeNode(
CAstNode.SWITCH,
visit(node.getExpression(), context),
Ast.makeNode(CAstNode.BLOCK_STMT, children));
context.cfg().map(node, s);
return Ast.makeNode(CAstNode.BLOCK_STMT, s, breakLabel);
}
@Override
public CAstNode visitSymbol(Symbol node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitThrowStatement(ThrowStatement n, WalkContext context) {
CAstNode catchNode = context.getCatchTarget();
if (catchNode != null) {
context.cfg().add(n, context.getCatchTarget(), null);
} else {
context.cfg().add(n, CAstControlFlowMap.EXCEPTION_TO_EXIT, null);
}
CAstNode throwAst = Ast.makeNode(CAstNode.THROW, visit(n.getExpression(), context));
context.cfg().map(n, throwAst);
return throwAst;
}
@Override
public CAstNode visitTryStatement(TryStatement node, WalkContext arg) {
WalkContext outer = arg;
List<CatchClause> catches = node.getCatchClauses();
CAstNode tryCatch;
String unwindName = null;
CAstNode unwindCatch = null;
if (node.getFinallyBlock() != null) {
unwindName = "$$unwind" + tempVarNum++;
String unwindCatchName = "$$unwind" + tempVarNum++;
CAstNode var = Ast.makeConstant(unwindCatchName);
arg.addNameDecl(
noteSourcePosition(
arg,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(unwindCatchName, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")),
node));
arg.addNameDecl(
noteSourcePosition(
arg,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(unwindName, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")),
node));
unwindCatch =
Ast.makeNode(
CAstNode.CATCH,
var,
Ast.makeNode(
CAstNode.ASSIGN,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(unwindName)),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(unwindCatchName))));
arg.cfg().map(unwindCatch, unwindCatch);
outer = new TryCatchContext(arg, unwindCatch);
}
if (catches != null && catches.size() > 0) {
String catchVarName = catches.get(0).getVarName().getString();
CAstNode var = Ast.makeConstant(catchVarName);
arg.addNameDecl(
noteSourcePosition(
arg,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(new CAstSymbolImpl(catchVarName, JSAstTranslator.Any)),
readName(arg, null, "$$undefined")),
node));
CAstNode code = Ast.makeNode(CAstNode.THROW, var);
for (int i = catches.size() - 1; i >= 0; i--) {
CatchClause clause = catches.get(i);
if (clause.getCatchCondition() != null) {
code =
Ast.makeNode(
CAstNode.IF_STMT,
visit(clause.getCatchCondition(), outer),
visit(clause.getBody(), outer),
code);
} else {
code = visit(clause, outer);
}
}
CAstNode catchBlock = Ast.makeNode(CAstNode.CATCH, var, code);
arg.cfg().map(catchBlock, catchBlock);
TryCatchContext tryContext = new TryCatchContext(outer, catchBlock);
tryCatch =
Ast.makeNode(
CAstNode.TRY,
visit(node.getTryBlock(), tryContext),
/*Ast.makeNode(CAstNode.LOCAL_SCOPE,*/ catchBlock /*)*/);
} else {
tryCatch = visit(node.getTryBlock(), arg);
}
if (node.getFinallyBlock() != null) {
return Ast.makeNode(
CAstNode.BLOCK_STMT,
Ast.makeNode(CAstNode.TRY, tryCatch, unwindCatch),
visit(node.getFinallyBlock(), arg),
Ast.makeNode(
CAstNode.IF_STMT,
Ast.makeNode(
CAstNode.BINARY_EXPR,
CAstOperator.OP_NE,
Ast.makeNode(CAstNode.VAR, Ast.makeConstant(unwindName)),
readName(arg, null, "$$undefined")),
Ast.makeNode(
CAstNode.THROW, Ast.makeNode(CAstNode.VAR, Ast.makeConstant(unwindName)))));
} else {
return tryCatch;
}
}
@Override
public CAstNode visitUnaryExpression(UnaryExpression node, WalkContext arg) {
if (node.getType() == Token.TYPEOFNAME) {
return Ast.makeNode(
CAstNode.TYPE_OF, Ast.makeNode(CAstNode.VAR, Ast.makeConstant(node.getString())));
} else if (node.getType() == Token.TYPEOF) {
return Ast.makeNode(CAstNode.TYPE_OF, visit(node.getOperand(), arg));
} else if (node.getType() == Token.DELPROP) {
AstNode expr = node.getOperand();
if (expr instanceof FunctionCall) {
expr = ((FunctionCall) expr).getTarget();
assert expr instanceof PropertyGet;
}
return Ast.makeNode(CAstNode.ASSIGN, visit(expr, arg), Ast.makeConstant(null));
} else if (node.getType() == Token.VOID) {
return Ast.makeConstant(null);
} else {
return Ast.makeNode(
CAstNode.UNARY_EXPR,
translateOpcode(node.getOperator()),
visit(node.getOperand(), arg));
}
}
@Override
public CAstNode visitUpdateExpression(UpdateExpression node, WalkContext arg) {
if (node.getType() == Token.INC || node.getType() == Token.DEC) {
CAstNode op = (node.getType() == Token.DEC) ? CAstOperator.OP_SUB : CAstOperator.OP_ADD;
AstNode l = node.getOperand();
CAstNode last = visit(l, arg);
return Ast.makeNode(
(node.isPostfix() ? CAstNode.ASSIGN_POST_OP : CAstNode.ASSIGN_PRE_OP),
last,
Ast.makeConstant(1),
op);
} else {
throw new RuntimeException("unexpected UpdateExpression " + node.toSource());
}
}
@Override
public CAstNode visitVariableDeclaration(VariableDeclaration node, WalkContext arg) {
List<VariableInitializer> inits = node.getVariables();
List<CAstNode> children = new ArrayList<>(inits.size());
for (VariableInitializer init : inits) {
arg.addNameDecl(
noteSourcePosition(
arg,
Ast.makeNode(
CAstNode.DECL_STMT,
Ast.makeConstant(
new CAstSymbolImpl(init.getTarget().getString(), JSAstTranslator.Any)),
readName(arg, null, "$$undefined")),
node));
if (init.getInitializer() == null) {
children.add(Ast.makeNode(CAstNode.EMPTY));
} else {
CAstNode initCode = visit(init, arg);
CAstPattern nameVarPattern =
CAstPattern.parse("VAR(\"" + init.getTarget().getString() + "\")");
if (!nameVarPattern.new Matcher() {
@Override
protected boolean enterEntity(
CAstEntity n, Context context, CAstVisitor<Context> visitor) {
return true;
}
@Override
protected boolean doVisit(CAstNode n, Context context, CAstVisitor<Context> visitor) {
return true;
}
}.findAll(null, initCode).isEmpty()) {
initCode =
Ast.makeNode(
CAstNode.SPECIAL_PARENT_SCOPE,
Ast.makeConstant(init.getTarget().getString()),
initCode);
}
children.add(
Ast.makeNode(
CAstNode.ASSIGN, readName(arg, null, init.getTarget().getString()), initCode));
}
}
if (children.size() == 1) {
return children.get(0);
} else {
return Ast.makeNode(CAstNode.BLOCK_STMT, children);
}
}
@Override
public CAstNode visitVariableInitializer(VariableInitializer node, WalkContext context) {
if (node.getInitializer() != null) {
return visit(node.getInitializer(), context);
} else {
return Ast.makeNode(CAstNode.EMPTY);
}
}
@Override
public CAstNode visitWhileLoop(WhileLoop node, WalkContext arg) {
AstNode breakStmt = makeEmptyLabelStmt("breakLabel");
CAstNode breakLabel = visit(breakStmt, arg);
AstNode contStmt = makeEmptyLabelStmt("contLabel");
CAstNode contLabel = visit(contStmt, arg);
WalkContext loopContext = makeLoopContext(node, arg, breakStmt, contStmt);
CAstNode loop =
Ast.makeNode(
CAstNode.BLOCK_STMT,
contLabel,
Ast.makeNode(
CAstNode.LOOP,
visit(node.getCondition(), arg),
visit(node.getBody(), loopContext)),
breakLabel);
arg.cfg().map(node, loop);
return loop;
}
@Override
public CAstNode visitWithStatement(WithStatement node, WalkContext arg) {
// TODO implement this somehow
return Ast.makeNode(CAstNode.EMPTY);
}
@Override
public CAstNode visitXmlDotQuery(XmlDotQuery node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlElemRef(XmlElemRef node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlExpression(XmlExpression node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlFragment(XmlFragment node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlLiteral(XmlLiteral node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlMemberGet(XmlMemberGet node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlPropRef(XmlPropRef node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlRef(XmlRef node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitXmlString(XmlString node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode visitYield(Yield node, WalkContext arg) {
// TODO Auto-generated method stub
return null;
}
}
/*
private CAstNode walkNodesInternal(final Node n, WalkContext context) {
final int NT = n.getType();
System.err.println(NT + " " + n.getClass());
switch (NT) {
case Token.FUNCTION: {
//int fnIndex = n.getExistingIntProp(Node.FUNCTION_PROP);
//FunctionNode fn = context.top().getFunctionNode(fnIndex);
FunctionNode fn = (FunctionNode)n;
CAstEntity fne = walkEntity(fn, context);
System.err.println(fne.getName());
if (fn.getFunctionType() == FunctionNode.FUNCTION_EXPRESSION) {
CAstNode fun = Ast.makeNode(CAstNode.FUNCTION_EXPR, Ast.makeConstant(fne));
context.addScopedEntity(fun, fne);
return fun;
} else {
context.addNameDecl(Ast.makeNode(CAstNode.FUNCTION_STMT, Ast.makeConstant(fne)));
context.addScopedEntity(null, fne);
return Ast.makeNode(CAstNode.EMPTY);
}
}
case Token.CATCH_SCOPE: {
Node catchVarNode = n.getFirstChild();
String catchVarName = catchVarNode.getString();
assert catchVarName != null;
context.setCatchVar(catchVarName);
return Ast.makeNode(CAstNode.EMPTY);
}
case Token.LOCAL_BLOCK: {
return Ast.makeNode(CAstNode.BLOCK_EXPR, walkChildren(n, context));
}
case Token.TRY: {
Node catchNode = ((Jump) n).target;
Node finallyNode = ((Jump) n).getFinally();
ArrayList<Node> tryList = new ArrayList<Node>();
ArrayList<Node> catchList = new ArrayList<Node>();
ArrayList<Node> finallyList = new ArrayList<Node>();
ArrayList<Node> current = tryList;
Node c;
for (c = n.getFirstChild(); c.getNext() != null; c = c.getNext()) {
if (c == catchNode) {
current = catchList;
} else if (c == finallyNode) {
current = finallyList;
}
if (c.getType() == Token.GOTO &&
// ((Node.Jump)c).target == lastChildNode &&
(c.getNext() == catchNode || c.getNext() == finallyNode)) {
continue;
}
current.add(c);
}
CAstNode finallyBlock = null;
if (finallyNode != null) {
int i = 0;
CAstNode[] finallyAsts = new CAstNode[finallyList.size()];
for (Node fn : finallyList) {
finallyAsts[i++] = walkNodes(fn, context);
}
finallyBlock = Ast.makeNode(CAstNode.BLOCK_STMT, finallyAsts);
}
if (catchNode != null) {
int i = 0;
WalkContext catchChild = new CatchBlockContext(context);
CAstNode[] catchAsts = new CAstNode[catchList.size()];
for (Node cn : catchList.iterator()) {
catchAsts[i++] = walkNodes(cn, catchChild);
}
CAstNode catchBlock = Ast.makeNode(CAstNode.CATCH, Ast.makeConstant(catchChild.getCatchVar()),
Ast.makeNode(CAstNode.BLOCK_STMT, catchAsts));
context.cfg().map(catchBlock, catchBlock);
i = 0;
WalkContext tryChild = new TryBlockContext(context, catchBlock);
CAstNode[] tryAsts = new CAstNode[tryList.size()];
for (Node tn : tryList) {
tryAsts[i++] = walkNodes(tn, tryChild);
}
CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts);
if (finallyBlock != null) {
return Ast.makeNode(CAstNode.BLOCK_STMT,
Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), finallyBlock), walkNodes(c, context));
} else {
return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.TRY, tryBlock, catchBlock), walkNodes(c, context));
}
} else {
int i = 0;
CAstNode[] tryAsts = new CAstNode[tryList.size()];
for (Node tn : tryList) {
tryAsts[i++] = walkNodes(tn, context);
}
CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts);
return Ast.makeNode(
CAstNode.BLOCK_STMT,
Ast.makeNode(CAstNode.UNWIND, Ast.makeNode(CAstNode.BLOCK_STMT, tryBlock),
Ast.makeNode(CAstNode.BLOCK_STMT, finallyBlock)), walkNodes(c, context));
}
}
case Token.JSR: {
return Ast.makeNode(CAstNode.EMPTY);
/*
* Node jsrTarget = ((Node.Jump)n).target; Node finallyNode =
* jsrTarget.getNext(); return walkNodes(finallyNode, context);
*
}
/*
* case Token.ENTERWITH: { return
* Ast.makeNode(JavaScriptCAstNode.ENTER_WITH,
* walkNodes(n.getFirstChild(), context)); }
*
* case Token.LEAVEWITH: { return
* Ast.makeNode(JavaScriptCAstNode.EXIT_WITH, Ast.makeConstant(null)); }
*
case Token.ENTERWITH:
case Token.LEAVEWITH: {
return Ast.makeNode(CAstNode.EMPTY);
}
case Token.LOOP: {
LoopContext child = new LoopContext(context);
CAstNode[] nodes = walkChildren(n, child);
if (child.forInInitExpr != null) {
String nm = child.forInVar;
return Ast.makeNode(CAstNode.BLOCK_STMT, Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm, true)),
walkNodes(child.forInInitExpr, context)), nodes);
} else {
return Ast.makeNode(CAstNode.BLOCK_STMT, nodes);
}
}
case Token.SWITCH: {
SwitchStatement s = (SwitchStatement) n;
Node switchValue = s.getExpression();
CAstNode defaultLabel = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeNode(CAstNode.EMPTY));
context.cfg().map(defaultLabel, defaultLabel);
List<CAstNode> labelCasts = new ArrayList<CAstNode>();
List<CAstNode> codeCasts = new ArrayList<CAstNode>();
for (SwitchCase kase : s.getCases()) {
assert kase.getType() == Token.CASE;
Node caseLbl = kase.getExpression();
CAstNode labelCast = walkNodes(caseLbl, context);
labelCasts.add(labelCast);
CAstNode targetCast = Ast.makeNode(CAstNode.EMPTY);
context.cfg().map(targetCast, labelCast);
codeCasts.add(targetCast);
context.cfg().add(s, targetCast, labelCast);
for(Node target : kase.getStatements()) {
codeCasts.add(walkNodes(target, context));
}
}
CAstNode[] children = codeCasts.toArray(new CAstNode[codeCasts.size()]);
context.cfg().add(s, defaultLabel, CAstControlFlowMap.SWITCH_DEFAULT);
CAstNode switchAst = Ast.makeNode(CAstNode.SWITCH, walkNodes(switchValue, context), children);
noteSourcePosition(context, switchAst, s);
context.cfg().map(s, switchAst);
return switchAst;
}
case Token.WITH:
case Token.FINALLY:
case Token.BLOCK:
case Token.LABEL: {
return Ast.makeNode(CAstNode.BLOCK_STMT, walkChildren(n, context));
}
case Token.EXPR_VOID:
case Token.EXPR_RESULT: {
WalkContext child = new ExpressionContext(context);
Node expr = ((ExpressionStatement) n).getExpression();
if (NT == Token.EXPR_RESULT) {
// EXPR_RESULT node is just a wrapper, so if we care about base pointer
// of n, we
// care about child of n
child.updateBase(n, expr);
}
return walkNodes(expr, child);
}
case Token.CALL: {
if (!isPrimitiveCall(context, n)) {
CAstNode base = makeVarRef("$$ base");
Node callee = (n instanceof FunctionCall) ? ((FunctionCall)n).getTarget() : n.getFirstChild();
WalkContext child = new BaseCollectingContext(context, callee, "$$ base");
CAstNode fun = walkNodes(callee, child);
// the first actual parameter appearing within the parentheses of the
// call (i.e., possibly excluding the 'this' parameter)
CAstNode[] args = gatherCallArguments(n, context);
if (child.foundBase(callee))
return Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(CAstNode.BLOCK_EXPR,
Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl("$$ base")), Ast.makeConstant(null)),
makeCall(fun, base, args, context)));
<<<<<<< .mine
else
return makeCall(fun, Ast.makeConstant(null), args, context);
=======
else {
// pass the global object as the receiver argument
return makeCall(fun, makeVarRef(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME), firstParamInParens, context);
}
>>>>>>> .r4418
} else {
return Ast.makeNode(CAstNode.PRIMITIVE, gatherCallArguments(n, context));
}
}
case Token.BINDNAME:
case Token.NAME: {
return readName(context, n.getString());
}
case Token.THIS: {
return makeVarRef("this");
}
case Token.THISFN: {
return makeVarRef(((FunctionNode) context.top()).getFunctionName());
}
case Token.STRING: {
if (n instanceof StringLiteral) {
return Ast.makeConstant(((StringLiteral)n).getValue());
} else {
return Ast.makeConstant(n.getString());
}
}
case Token.NUMBER: {
return Ast.makeConstant(n.getDouble());
}
case Token.FALSE: {
return Ast.makeConstant(false);
}
case Token.TRUE: {
return Ast.makeConstant(true);
}
case Token.NULL:
case Token.VOID: {
return Ast.makeConstant(null);
}
case Token.ADD:
case Token.DIV:
case Token.LSH:
case Token.MOD:
case Token.MUL:
case Token.RSH:
case Token.SUB:
case Token.URSH:
case Token.BITAND:
case Token.BITOR:
case Token.BITXOR:
case Token.EQ:
case Token.SHEQ:
case Token.GE:
case Token.GT:
case Token.LE:
case Token.LT:
case Token.SHNE:
case Token.NE: {
Node l;
Node r;
if (n instanceof InfixExpression) {
l = ((InfixExpression)n).getLeft();
r = ((InfixExpression)n).getRight();
} else {
l = n.getFirstChild();
r = l.getNext();
}
return Ast.makeNode(CAstNode.BINARY_EXPR, translateOpcode(NT), walkNodes(l, context), walkNodes(r, context));
}
case Token.BITNOT:
case Token.NOT: {
return Ast.makeNode(CAstNode.UNARY_EXPR, translateOpcode(NT), walkNodes(((UnaryExpression)n).getOperand(), context));
}
case Token.VAR:
case Token.CONST: {
List<CAstNode> result = new ArrayList<CAstNode>();
if (n instanceof VariableDeclaration) {
for(VariableInitializer var : ((VariableDeclaration)n).getVariables()) {
context.addNameDecl(Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(var.getTarget().getString())),
readName(context, "$$undefined")));
if (var.getInitializer() != null) {
WalkContext child = new ExpressionContext(context);
result.add(Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.VAR, Ast.makeConstant(var.getTarget().getString())),
walkNodes(var.getInitializer(), child)));
}
}
} else {
Node nm = n.getFirstChild();
while (nm != null) {
context.addNameDecl(Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(nm.getString())),
readName(context, "$$undefined")));
<<<<<<< .mine
if (nm.getFirstChild() != null) {
WalkContext child = new ExpressionContext(context);
=======
result.add(Ast.makeNode(CAstNode.ASSIGN, makeVarRef(nm.getString()),
walkNodes(nm.getFirstChild(), child)));
>>>>>>> .r4418
result.add(Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.VAR, Ast.makeConstant(nm.getString())),
walkNodes(nm.getFirstChild(), child)));
}
nm = nm.getNext();
}
}
if (result.size() > 0) {
return Ast.makeNode(CAstNode.BLOCK_EXPR, result.toArray(new CAstNode[result.size()]));
} else {
return Ast.makeNode(CAstNode.EMPTY);
}
}
case Token.REGEXP: {
int regexIdx = n.getIntProp(Node.REGEXP_PROP, -1);
assert regexIdx != -1 : "while converting: " + context.top().toStringTree(context.top()) + "\nlooking at bad regex:\n "
+ n.toStringTree(context.top());
String flags = context.top().getRegexpFlags(regexIdx);
CAstNode flagsNode = Ast.makeConstant(flags);
String str = context.top().getRegexpString(regexIdx);
Node strNode = Node.newString(str);
return handleNew(context, "RegExp", new CAstNode[]{ flagsNode });
}
case Token.ENUM_INIT_KEYS: {
context.createForInVar(n.getFirstChild());
return Ast.makeNode(CAstNode.EMPTY);
}
case Token.ENUM_ID: {
return Ast.makeNode(CAstNode.EACH_ELEMENT_GET, makeVarRef(context.getForInInitVar()));
}
case Token.ENUM_NEXT: {
return Ast.makeNode(CAstNode.EACH_ELEMENT_HAS_NEXT, makeVarRef(context.getForInInitVar()));
}
case Token.RETURN: {
Node val = n.getFirstChild();
if (val != null) {
WalkContext child = new ExpressionContext(context);
return Ast.makeNode(CAstNode.RETURN, walkNodes(val, child));
} else {
return Ast.makeNode(CAstNode.RETURN);
}
}
case Token.ASSIGN:
{
Assignment a = (Assignment) n;
return Ast.makeNode(CAstNode.ASSIGN, walkNodes(a.getLeft(), context), walkNodes(a.getRight(), context));
}
case Token.ASSIGN_ADD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_DIV:
case Token.ASSIGN_LSH:
case Token.ASSIGN_MOD:
case Token.ASSIGN_MUL:
case Token.ASSIGN_RSH:
case Token.ASSIGN_SUB:
case Token.ASSIGN_URSH: {
Assignment a = (Assignment) n;
return Ast.makeNode(CAstNode.ASSIGN_POST_OP,
walkNodes(a.getLeft(), context),
walkNodes(a.getRight(), context),
translateOpcode(a.getOperator()));
}
case Token.SETNAME: {
Node nm = n.getFirstChild();
return Ast.makeNode(CAstNode.ASSIGN, walkNodes(nm, context), walkNodes(nm.getNext(), context));
}
case Token.IFNE:
case Token.IFEQ: {
context.cfg().add(n, ((Jump) n).target, Boolean.TRUE);
WalkContext child = new ExpressionContext(context);
CAstNode gotoAst = Ast.makeNode(CAstNode.IFGOTO, translateOpcode(NT), walkNodes(n.getFirstChild(), child),
Ast.makeConstant(1));
context.cfg().map(n, gotoAst);
return gotoAst;
}
case Token.GOTO: {
context.cfg().add(n, ((Jump) n).target, null);
CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Jump) n).target.labelId()));
context.cfg().map(n, gotoAst);
return gotoAst;
}
case Token.BREAK: {
context.cfg().add(n, ((Jump) n).getJumpStatement().target, null);
CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Jump) n).getJumpStatement().target.labelId()));
context.cfg().map(n, gotoAst);
return gotoAst;
}
case Token.CONTINUE: {
context.cfg().add(n, ((Jump) n).getJumpStatement().getContinue(), null);
CAstNode gotoAst = Ast.makeNode(CAstNode.GOTO, Ast.makeConstant(((Jump) n).getJumpStatement().getContinue().labelId()));
context.cfg().map(n, gotoAst);
return gotoAst;
}
case Token.TARGET: {
CAstNode result = Ast.makeNode(CAstNode.LABEL_STMT, Ast.makeConstant(n.labelId()), Ast.makeNode(CAstNode.EMPTY));
context.cfg().map(n, result);
return result;
}
<<<<<<< .mine
=======
case Token.OR: {
Node l = n.getFirstChild();
Node r = l.getNext();
CAstNode lhs = walkNodes(l, context);
String lhsTempName = "or___lhs";
// { lhsTemp := <lhs>; if(lhsTemp) { lhsTemp } else { <rhs> }
return Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(CAstNode.BLOCK_EXPR,
Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs),
Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), makeVarRef(lhsTempName), walkNodes(r, context))));
}
case Token.AND: {
Node l = n.getFirstChild();
Node r = l.getNext();
CAstNode lhs = walkNodes(l, context);
String lhsTempName = "and___lhs";
// { lhsTemp := <lhs>; if(lhsTemp) { <rhs> } else { lhsTemp }
return Ast.makeNode(
CAstNode.LOCAL_SCOPE,
Ast.makeNode(CAstNode.BLOCK_EXPR,
Ast.makeNode(CAstNode.DECL_STMT, Ast.makeConstant(new CAstSymbolImpl(lhsTempName)), lhs),
Ast.makeNode(CAstNode.IF_EXPR, makeVarRef(lhsTempName), walkNodes(r, context), makeVarRef(lhsTempName))));
}
>>>>>>> .r4418
case Token.HOOK: {
Node cond = n.getFirstChild();
Node thenBranch = cond.getNext();
Node elseBranch = thenBranch.getNext();
return Ast.makeNode(CAstNode.IF_EXPR, walkNodes(cond, context), walkNodes(thenBranch, context),
walkNodes(elseBranch, context));
}
case Token.NEW: {
if (isPrimitiveCreation(context, n)) {
return makeBuiltinNew(getNewTarget(n).getString());
} else {
Node receiver = ((NewExpression)n).getTarget();
return handleNew(context, walkNodes(receiver, context), gatherCallArguments(n, context));
}
}
case Token.ARRAYLIT: {
int count = 0;
for (Node x = n.getFirstChild(); x != null; count++, x = x.getNext())
;
int i = 0;
CAstNode[] args = new CAstNode[2 * count + 1];
args[i++] = (isPrologueScript(context)) ? makeBuiltinNew("Array") : handleNew(context, "Array", null);
int[] skips = (int[]) n.getProp(Node.SKIP_INDEXES_PROP);
int skip = 0;
int idx = 0;
Node elt = n.getFirstChild();
while (elt != null) {
if (skips != null && skip < skips.length && skips[skip] == idx) {
skip++;
idx++;
continue;
}
args[i++] = Ast.makeConstant(idx++);
args[i++] = walkNodes(elt, context);
elt = elt.getNext();
}
return Ast.makeNode(CAstNode.OBJECT_LITERAL, args);
}
case Token.OBJECTLIT: {
CAstNode[] args;
if (n instanceof ObjectLiteral) {
List<ObjectProperty> props = ((ObjectLiteral)n).getElements();
args = new CAstNode[props.size() * 2 + 1];
int i = 0;
args[i++] = ((isPrologueScript(context)) ? makeBuiltinNew("Object") : handleNew(context, "Object", null));
for(ObjectProperty prop : props) {
args[i++] = walkNodes(prop.getLeft(), context);
args[i++] = walkNodes(prop.getRight(), context);
}
} else {
Object[] propertyList = (Object[]) n.getProp(Node.OBJECT_IDS_PROP);
args = new CAstNode[propertyList.length * 2 + 1];
int i = 0;
args[i++] = ((isPrologueScript(context)) ? makeBuiltinNew("Object") : handleNew(context, "Object", null));
Node val = n.getFirstChild();
int nameIdx = 0;
for (; nameIdx < propertyList.length; nameIdx++, val = val.getNext()) {
args[i++] = Ast.makeConstant(propertyList[nameIdx]);
args[i++] = walkNodes(val, context);
}
}
return Ast.makeNode(CAstNode.OBJECT_LITERAL, args);
}
case Token.GETPROP:
case Token.GETELEM: {
<<<<<<< .mine
Node receiver;
Node element;
if (n instanceof PropertyGet) {
receiver = ((PropertyGet)n).getLeft();
element = ((PropertyGet)n).getRight();
=======
Node receiver = n.getFirstChild();
Node element = receiver.getNext();
CAstNode rcvr = walkNodes(receiver, context);
String baseVarName = context.getBaseVarNameIfRelevant(n);
CAstNode elt = walkNodes(element, context);
CAstNode get, result;
if (baseVarName != null) {
result = Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr),
get = Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt));
>>>>>>> .r4418
} else {
receiver = ((ElementGet)n).getTarget();
element = ((ElementGet)n).getElement();
}
return handleFieldGet(n, context, receiver, element);
}
case Token.GET_REF: {
// read of __proto__
// first and only child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__".
// c1 has a single child, the base pointer for the reference
Node child1 = n.getFirstChild();
assert child1.getType() == Token.REF_SPECIAL;
assert child1.getProp(Node.NAME_PROP).equals("__proto__");
Node receiver = child1.getFirstChild();
assert child1.getNext() == null;
CAstNode rcvr = walkNodes(receiver, context);
final CAstNode result = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__"));
if (context.getCatchTarget() != null) {
context.cfg().map(result, result);
context.cfg().add(result, context.getCatchTarget(), JavaScriptTypes.TypeError);
}
return result;
}
case Token.SETPROP:
case Token.SETELEM: {
Node receiver = n.getFirstChild();
Node elt = receiver.getNext();
Node val = elt.getNext();
CAstNode rcvr = walkNodes(receiver, context);
return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)),
walkNodes(val, context));
}
case Token.SET_REF: {
// first child c1 is of type Token.REF_SPECIAL whose NAME_PROP property should be "__proto__".
// c1 has a single child, the base pointer for the reference
// second child c2 is RHS of assignment
Node child1 = n.getFirstChild();
assert child1.getType() == Token.REF_SPECIAL;
assert child1.getProp(Node.NAME_PROP).equals("__proto__");
Node receiver = child1.getFirstChild();
Node val = child1.getNext();
CAstNode rcvr = walkNodes(receiver, context);
return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, Ast.makeConstant("__proto__")),
walkNodes(val, context));
}
case Token.DELPROP: {
Node receiver = n.getFirstChild();
Node element = receiver.getNext();
CAstNode rcvr = walkNodes(receiver, context);
String baseVarName = context.getBaseVarNameIfRelevant(n);
CAstNode elt = walkNodes(element, context);
if (baseVarName != null) {
return Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, makeVarRef(baseVarName), rcvr),
Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, makeVarRef(baseVarName), elt), Ast.makeConstant(null)));
} else {
return Ast.makeNode(CAstNode.ASSIGN, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt), Ast.makeConstant(null));
}
}
<<<<<<< .mine
=======
case Token.TYPEOFNAME: {
return Ast.makeNode(CAstNode.TYPE_OF, makeVarRef(n.getString()));
}
>>>>>>> .r4418
case Token.SETPROP_OP:
case Token.SETELEM_OP: {
Node receiver = n.getFirstChild();
Node elt = receiver.getNext();
Node op = elt.getNext();
CAstNode rcvr = walkNodes(receiver, context);
return Ast.makeNode(CAstNode.ASSIGN_POST_OP, Ast.makeNode(CAstNode.OBJECT_REF, rcvr, walkNodes(elt, context)),
walkNodes(op.getFirstChild().getNext(), context), translateOpcode(op.getType()));
}
case Token.THROW: {
CAstNode catchNode = context.getCatchTarget();
if (catchNode != null)
context.cfg().add(n, context.getCatchTarget(), null);
else
context.cfg().add(n, CAstControlFlowMap.EXCEPTION_TO_EXIT, null);
CAstNode throwAst = Ast.makeNode(CAstNode.THROW, walkNodes(n.getFirstChild(), context));
context.cfg().map(n, throwAst);
return throwAst;
}
case Token.EMPTY: {
return Ast.makeConstant(null);
}
case Token.IN: {
Node value = n.getFirstChild();
Node property = value.getNext();
return Ast.makeNode(CAstNode.IS_DEFINED_EXPR, walkNodes(property, context), walkNodes(value, context));
}
case Token.IF: {
IfStatement stmt = (IfStatement)n;
if (stmt.getElsePart() != null) {
return Ast.makeNode(CAstNode.IF_STMT,
walkNodes(stmt.getCondition(), context),
walkNodes(stmt.getThenPart(), context),
walkNodes(stmt.getElsePart(), context));
} else {
return Ast.makeNode(CAstNode.IF_STMT,
walkNodes(stmt.getCondition(), context),
walkNodes(stmt.getThenPart(), context));
}
}
case Token.FOR: {
ForLoop f = (ForLoop) n;
return Ast.makeNode(CAstNode.BLOCK_STMT,
walkNodes(f.getInitializer(), context),
Ast.makeNode(CAstNode.LOOP,
walkNodes(f.getCondition(), context),
walkNodes(f.getBody(), context),
walkNodes(f.getIncrement(), context)));
}
case Token.LP: {
return walkNodes(((ParenthesizedExpression)n).getExpression(), context);
}
default: {
System.err.println("while converting: " + context.top().toStringTree(context.top()) + "\nlooking at unhandled:\n "
+ n.toStringTree(context.top()) + "\n(of type " + NT + ") (of class " + n.getClass() + ")" + " at " + n.getLineno());
Assertions.UNREACHABLE();
return null;
}
}
}
<<<<<<< .mine
private CAstNode handleFieldGet(final Node n, WalkContext context,
Node receiver, Node element) {
CAstNode rcvr = walkNodes(receiver, context);
CAstNode baseVar = context.getBaseVarIfRelevant(n);
CAstNode elt = walkNodes(element, context);
CAstNode get, result;
if (baseVar != null) {
result = Ast.makeNode(CAstNode.BLOCK_EXPR, Ast.makeNode(CAstNode.ASSIGN, baseVar, rcvr),
get = Ast.makeNode(CAstNode.OBJECT_REF, baseVar, elt));
} else {
result = get = Ast.makeNode(CAstNode.OBJECT_REF, rcvr, elt);
}
if (context.getCatchTarget() != null) {
context.cfg().map(get, get);
context.cfg().add(get, context.getCatchTarget(), JavaScriptTypes.TypeError);
}
return result;
}
private CAstNode[] walkChildren(final Node n, WalkContext context) {
List<CAstNode> children = new ArrayList<CAstNode>();
Iterator<Node> nodes = n.iterator();
while (nodes.hasNext()) {
children.add(walkNodes(nodes.next(), context));
}
return children.toArray(new CAstNode[ children.size() ]);
}
/**
* count the number of successor siblings of n, including n
*
private int countSiblingsStartingFrom(Node n) {
int siblings = 0;
for (Node c = n; c != null; c = c.getNext(), siblings++)
;
return siblings;
}
private Iterator<? extends Node> varDeclGetVars(Node n) {
if (n instanceof VariableDeclaration) {
return ((VariableDeclaration)n).getVariables().iterator();
} else {
return new SiblingIterator(n.getFirstChild());
}
}
*/
private CAstNode makeVarRef(String varName) {
return Ast.makeNode(CAstNode.VAR, Ast.makeConstant(varName));
}
/** parse the JavaScript code using Rhino, and then translate the resulting AST to CAst */
@Override
public CAstEntity translateToCAst()
throws Error, IOException, com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error {
class CAstErrorReporter implements ErrorReporter {
private final Set<Warning> w = HashSetFactory.make();
@Override
public void error(
final String arg0, final String arg1, final int arg2, final String arg3, int arg4) {
w.add(
new Warning(Warning.SEVERE) {
@Override
public String getMsg() {
return arg0 + ": " + arg1 + '@' + arg2 + ": " + arg3;
}
});
}
@Override
public EvaluatorException runtimeError(
String arg0, String arg1, int arg2, String arg3, int arg4) {
error(arg0, arg1, arg2, arg3, arg4);
return null;
}
@Override
public void warning(String arg0, String arg1, int arg2, String arg3, int arg4) {
// ignore warnings
}
}
CAstErrorReporter reporter = new CAstErrorReporter();
CompilerEnvirons compilerEnv = new CompilerEnvirons();
compilerEnv.setErrorReporter(reporter);
compilerEnv.setReservedKeywordAsIdentifier(true);
compilerEnv.setIdeMode(true);
if (DEBUG) {
System.err.println(("translating " + scriptName + " with Rhino"));
}
Parser P = new Parser(compilerEnv, compilerEnv.getErrorReporter());
AstRoot top = P.parse(Kit.readReader(sourceReader), scriptName, 1);
if (!reporter.w.isEmpty()) {
throw new TranslatorToCAst.Error(reporter.w);
}
final FunctionContext child = new ScriptContext(new RootContext(), top, top.getSourceName());
TranslatingVisitor tv = new TranslatingVisitor();
List<CAstNode> body = new ArrayList<>();
for (Node bn : top) {
body.add(tv.visit((AstNode) bn, child));
}
return walkEntity(top, body, top.getSourceName(), child);
}
private final CAst Ast;
private final String scriptName;
private final ModuleEntry sourceModule;
private final Reader sourceReader;
private int tempVarNum = 0;
private final DoLoopTranslator doLoopTranslator;
private final boolean useNewForIn;
public RhinoToAstTranslator(
CAst Ast, ModuleEntry m, String scriptName, boolean replicateForDoLoops) {
this(Ast, m, scriptName, replicateForDoLoops, false);
}
public RhinoToAstTranslator(
CAst Ast,
ModuleEntry m,
String scriptName,
boolean replicateForDoLoops,
boolean useNewForIn) {
this.Ast = Ast;
this.scriptName = scriptName;
this.sourceModule = m;
this.sourceReader = new InputStreamReader(sourceModule.getInputStream());
this.doLoopTranslator = new DoLoopTranslator(replicateForDoLoops, Ast);
this.useNewForIn = useNewForIn;
}
@Override
public <C extends RewriteContext<K>, K extends CopyKey<K>> void addRewriter(
CAstRewriterFactory<C, K> factory, boolean prepend) {
assert false;
}
}
| 97,234
| 33.419469
| 134
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/main/java/com/ibm/wala/cast/js/translator/TypedNodeVisitor.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 org.mozilla.javascript.ast.ArrayComprehension;
import org.mozilla.javascript.ast.ArrayComprehensionLoop;
import org.mozilla.javascript.ast.ArrayLiteral;
import org.mozilla.javascript.ast.Assignment;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.AstRoot;
import org.mozilla.javascript.ast.Block;
import org.mozilla.javascript.ast.BreakStatement;
import org.mozilla.javascript.ast.CatchClause;
import org.mozilla.javascript.ast.Comment;
import org.mozilla.javascript.ast.ConditionalExpression;
import org.mozilla.javascript.ast.ContinueStatement;
import org.mozilla.javascript.ast.DoLoop;
import org.mozilla.javascript.ast.ElementGet;
import org.mozilla.javascript.ast.EmptyExpression;
import org.mozilla.javascript.ast.EmptyStatement;
import org.mozilla.javascript.ast.ErrorNode;
import org.mozilla.javascript.ast.ExpressionStatement;
import org.mozilla.javascript.ast.ForInLoop;
import org.mozilla.javascript.ast.ForLoop;
import org.mozilla.javascript.ast.FunctionCall;
import org.mozilla.javascript.ast.FunctionNode;
import org.mozilla.javascript.ast.IfStatement;
import org.mozilla.javascript.ast.InfixExpression;
import org.mozilla.javascript.ast.Jump;
import org.mozilla.javascript.ast.KeywordLiteral;
import org.mozilla.javascript.ast.Label;
import org.mozilla.javascript.ast.LabeledStatement;
import org.mozilla.javascript.ast.LetNode;
import org.mozilla.javascript.ast.Name;
import org.mozilla.javascript.ast.NewExpression;
import org.mozilla.javascript.ast.NumberLiteral;
import org.mozilla.javascript.ast.ObjectLiteral;
import org.mozilla.javascript.ast.ObjectProperty;
import org.mozilla.javascript.ast.ParenthesizedExpression;
import org.mozilla.javascript.ast.PropertyGet;
import org.mozilla.javascript.ast.RegExpLiteral;
import org.mozilla.javascript.ast.ReturnStatement;
import org.mozilla.javascript.ast.Scope;
import org.mozilla.javascript.ast.ScriptNode;
import org.mozilla.javascript.ast.StringLiteral;
import org.mozilla.javascript.ast.SwitchCase;
import org.mozilla.javascript.ast.SwitchStatement;
import org.mozilla.javascript.ast.Symbol;
import org.mozilla.javascript.ast.ThrowStatement;
import org.mozilla.javascript.ast.TryStatement;
import org.mozilla.javascript.ast.UnaryExpression;
import org.mozilla.javascript.ast.UpdateExpression;
import org.mozilla.javascript.ast.VariableDeclaration;
import org.mozilla.javascript.ast.VariableInitializer;
import org.mozilla.javascript.ast.WhileLoop;
import org.mozilla.javascript.ast.WithStatement;
import org.mozilla.javascript.ast.XmlDotQuery;
import org.mozilla.javascript.ast.XmlElemRef;
import org.mozilla.javascript.ast.XmlExpression;
import org.mozilla.javascript.ast.XmlFragment;
import org.mozilla.javascript.ast.XmlLiteral;
import org.mozilla.javascript.ast.XmlMemberGet;
import org.mozilla.javascript.ast.XmlPropRef;
import org.mozilla.javascript.ast.XmlRef;
import org.mozilla.javascript.ast.XmlString;
import org.mozilla.javascript.ast.Yield;
public abstract class TypedNodeVisitor<R, A> {
public R visit(AstNode node, A arg) {
if (node instanceof ArrayComprehension) {
return visitArrayComprehension((ArrayComprehension) node, arg);
} else if (node instanceof WhileLoop) {
return visitWhileLoop((WhileLoop) node, arg);
} else if (node instanceof ArrayComprehensionLoop) {
return visitArrayComprehensionLoop((ArrayComprehensionLoop) node, arg);
} else if (node instanceof ArrayLiteral) {
return visitArrayLiteral((ArrayLiteral) node, arg);
} else if (node instanceof Assignment) {
return visitAssignment((Assignment) node, arg);
} else if (node instanceof AstRoot) {
return visitAstRoot((AstRoot) node, arg);
} else if (node instanceof Block) {
return visitBlock((Block) node, arg);
} else if (node instanceof BreakStatement) {
return visitBreakStatement((BreakStatement) node, arg);
} else if (node instanceof CatchClause) {
return visitCatchClause((CatchClause) node, arg);
} else if (node instanceof Comment) {
return visitComment((Comment) node, arg);
} else if (node instanceof ConditionalExpression) {
return visitConditionalExpression((ConditionalExpression) node, arg);
} else if (node instanceof ContinueStatement) {
return visitContinueStatement((ContinueStatement) node, arg);
} else if (node instanceof DoLoop) {
return visitDoLoop((DoLoop) node, arg);
} else if (node instanceof ElementGet) {
return visitElementGet((ElementGet) node, arg);
} else if (node instanceof EmptyExpression) {
return visitEmptyExpression((EmptyExpression) node, arg);
} else if (node instanceof EmptyStatement) {
return visitEmptyStatement((EmptyStatement) node, arg);
} else if (node instanceof ErrorNode) {
return visitErrorNode((ErrorNode) node, arg);
} else if (node instanceof ExpressionStatement) {
return visitExpressionStatement((ExpressionStatement) node, arg);
} else if (node instanceof ForInLoop) {
return visitForInLoop((ForInLoop) node, arg);
} else if (node instanceof ForLoop) {
return visitForLoop((ForLoop) node, arg);
} else if (node instanceof NewExpression) {
return visitNewExpression((NewExpression) node, arg);
} else if (node instanceof FunctionCall) {
return visitFunctionCall((FunctionCall) node, arg);
} else if (node instanceof FunctionNode) {
return visitFunctionNode((FunctionNode) node, arg);
} else if (node instanceof IfStatement) {
return visitIfStatement((IfStatement) node, arg);
} else if (node instanceof KeywordLiteral) {
return visitKeywordLiteral((KeywordLiteral) node, arg);
} else if (node instanceof Label) {
return visitLabel((Label) node, arg);
} else if (node instanceof LabeledStatement) {
return visitLabeledStatement((LabeledStatement) node, arg);
} else if (node instanceof LetNode) {
return visitLetNode((LetNode) node, arg);
} else if (node instanceof Name) {
return visitName((Name) node, arg);
} else if (node instanceof NumberLiteral) {
return visitNumberLiteral((NumberLiteral) node, arg);
} else if (node instanceof ObjectLiteral) {
return visitObjectLiteral((ObjectLiteral) node, arg);
} else if (node instanceof ObjectProperty) {
return visitObjectProperty((ObjectProperty) node, arg);
} else if (node instanceof ParenthesizedExpression) {
return visitParenthesizedExpression((ParenthesizedExpression) node, arg);
} else if (node instanceof PropertyGet) {
return visitPropertyGet((PropertyGet) node, arg);
} else if (node instanceof RegExpLiteral) {
return visitRegExpLiteral((RegExpLiteral) node, arg);
} else if (node instanceof ReturnStatement) {
return visitReturnStatement((ReturnStatement) node, arg);
} else if (node instanceof Scope) {
return visitScope((Scope) node, arg);
} else if (node instanceof ScriptNode) {
return visitScriptNode((ScriptNode) node, arg);
} else if (node instanceof StringLiteral) {
return visitStringLiteral((StringLiteral) node, arg);
} else if (node instanceof SwitchCase) {
return visitSwitchCase((SwitchCase) node, arg);
} else if (node instanceof SwitchStatement) {
return visitSwitchStatement((SwitchStatement) node, arg);
} else if (node instanceof ThrowStatement) {
return visitThrowStatement((ThrowStatement) node, arg);
} else if (node instanceof TryStatement) {
return visitTryStatement((TryStatement) node, arg);
} else if (node instanceof UnaryExpression) {
return visitUnaryExpression((UnaryExpression) node, arg);
} else if (node instanceof UpdateExpression) {
return visitUpdateExpression((UpdateExpression) node, arg);
} else if (node instanceof VariableDeclaration) {
return visitVariableDeclaration((VariableDeclaration) node, arg);
} else if (node instanceof VariableInitializer) {
return visitVariableInitializer((VariableInitializer) node, arg);
} else if (node instanceof WithStatement) {
return visitWithStatement((WithStatement) node, arg);
} else if (node instanceof XmlDotQuery) {
return visitXmlDotQuery((XmlDotQuery) node, arg);
} else if (node instanceof XmlElemRef) {
return visitXmlElemRef((XmlElemRef) node, arg);
} else if (node instanceof XmlExpression) {
return visitXmlExpression((XmlExpression) node, arg);
} else if (node instanceof XmlLiteral) {
return visitXmlLiteral((XmlLiteral) node, arg);
} else if (node instanceof XmlMemberGet) {
return visitXmlMemberGet((XmlMemberGet) node, arg);
} else if (node instanceof XmlPropRef) {
return visitXmlPropRef((XmlPropRef) node, arg);
} else if (node instanceof XmlString) {
return visitXmlString((XmlString) node, arg);
} else if (node instanceof Yield) {
return visitYield((Yield) node, arg);
} else if (node instanceof InfixExpression) {
return visitInfixExpression((InfixExpression) node, arg);
} else if (node instanceof Jump) {
return visitJump((Jump) node, arg);
} else {
throw new Error("unexpected node type " + node.getClass().getName());
}
}
public abstract R visitArrayComprehension(ArrayComprehension node, A arg);
public abstract R visitArrayComprehensionLoop(ArrayComprehensionLoop node, A arg);
public abstract R visitArrayLiteral(ArrayLiteral node, A arg);
public abstract R visitAssignment(Assignment node, A arg);
public abstract R visitAstRoot(AstRoot node, A arg);
public abstract R visitBlock(Block node, A arg);
public abstract R visitBreakStatement(BreakStatement node, A arg);
public abstract R visitCatchClause(CatchClause node, A arg);
public abstract R visitComment(Comment node, A arg);
public abstract R visitConditionalExpression(ConditionalExpression node, A arg);
public abstract R visitContinueStatement(ContinueStatement node, A arg);
public abstract R visitDoLoop(DoLoop node, A arg);
public abstract R visitElementGet(ElementGet node, A arg);
public abstract R visitEmptyExpression(EmptyExpression node, A arg);
public abstract R visitEmptyStatement(EmptyStatement node, A arg);
public abstract R visitErrorNode(ErrorNode node, A arg);
public abstract R visitExpressionStatement(ExpressionStatement node, A arg);
public abstract R visitForInLoop(ForInLoop node, A arg);
public abstract R visitForLoop(ForLoop node, A arg);
public abstract R visitFunctionCall(FunctionCall node, A arg);
public abstract R visitFunctionNode(FunctionNode node, A arg);
public abstract R visitIfStatement(IfStatement node, A arg);
public abstract R visitInfixExpression(InfixExpression node, A arg);
public abstract R visitJump(Jump node, A arg);
public abstract R visitKeywordLiteral(KeywordLiteral node, A arg);
public abstract R visitLabel(Label node, A arg);
public abstract R visitLabeledStatement(LabeledStatement node, A arg);
public abstract R visitLetNode(LetNode node, A arg);
public abstract R visitName(Name node, A arg);
public abstract R visitNewExpression(NewExpression node, A arg);
public abstract R visitNumberLiteral(NumberLiteral node, A arg);
public abstract R visitObjectLiteral(ObjectLiteral node, A arg);
public abstract R visitObjectProperty(ObjectProperty node, A arg);
public abstract R visitParenthesizedExpression(ParenthesizedExpression node, A arg);
public abstract R visitPropertyGet(PropertyGet node, A arg);
public abstract R visitRegExpLiteral(RegExpLiteral node, A arg);
public abstract R visitReturnStatement(ReturnStatement node, A arg);
public abstract R visitScope(Scope node, A arg);
public abstract R visitScriptNode(ScriptNode node, A arg);
public abstract R visitStringLiteral(StringLiteral node, A arg);
public abstract R visitSwitchCase(SwitchCase node, A arg);
public abstract R visitSwitchStatement(SwitchStatement node, A arg);
public abstract R visitSymbol(Symbol node, A arg);
public abstract R visitThrowStatement(ThrowStatement node, A arg);
public abstract R visitTryStatement(TryStatement node, A arg);
public abstract R visitUnaryExpression(UnaryExpression node, A arg);
public abstract R visitUpdateExpression(UpdateExpression node, A arg);
public abstract R visitVariableDeclaration(VariableDeclaration node, A arg);
public abstract R visitVariableInitializer(VariableInitializer node, A arg);
public abstract R visitWhileLoop(WhileLoop node, A arg);
public abstract R visitWithStatement(WithStatement node, A arg);
public abstract R visitXmlDotQuery(XmlDotQuery node, A arg);
public abstract R visitXmlElemRef(XmlElemRef node, A arg);
public abstract R visitXmlExpression(XmlExpression node, A arg);
public abstract R visitXmlFragment(XmlFragment node, A arg);
public abstract R visitXmlLiteral(XmlLiteral node, A arg);
public abstract R visitXmlMemberGet(XmlMemberGet node, A arg);
public abstract R visitXmlPropRef(XmlPropRef node, A arg);
public abstract R visitXmlRef(XmlRef node, A arg);
public abstract R visitXmlString(XmlString node, A arg);
public abstract R visitYield(Yield node, A arg);
}
| 13,653
| 41.403727
| 86
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/AbstractFieldBasedTest.java
|
package com.ibm.wala.cast.js.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.test.TestJSCallGraphShape;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.CallGraph2JSON;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.SourceURLModule;
import com.ibm.wala.core.util.ProgressMaster;
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.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
public abstract class AbstractFieldBasedTest extends TestJSCallGraphShape {
protected FieldBasedCGUtil util;
public AbstractFieldBasedTest() {
super();
}
@Before
public void setUp() throws Exception {
util = new FieldBasedCGUtil(new CAstRhinoTranslatorFactory());
}
protected JSCallGraph runTest(String script, Object[][] assertions, BuilderType... builderTypes)
throws WalaException, Error, CancelException {
return runTest(
TestFieldBasedCG.class.getClassLoader().getResource(script), assertions, builderTypes);
}
protected JSCallGraph runTest(URL url, Object[][] assertions, BuilderType... builderTypes)
throws WalaException, Error, CancelException {
JSCallGraph cg = null;
for (BuilderType builderType : builderTypes) {
IProgressMonitor monitor = ProgressMaster.make(new NullProgressMonitor(), 45000, true);
try {
cg =
util.buildCG(url, builderType, monitor, false, DefaultSourceExtractor.factory)
.getCallGraph();
System.err.println(cg);
verifyGraphAssertions(cg, assertions);
} catch (AssertionError afe) {
throw new AssertionError(builderType + ": " + afe.getMessage(), afe);
}
}
return cg;
}
protected JSCallGraph runBoundedTest(
String script, Object[][] assertions, BuilderType builderType, int bound)
throws WalaException, Error, CancelException {
JSCallGraph cg = null;
JavaScriptLoaderFactory loaders = new JavaScriptLoaderFactory(new CAstRhinoTranslatorFactory());
IProgressMonitor monitor = ProgressMaster.make(new NullProgressMonitor(), 45000, true);
List<Module> scripts = new ArrayList<>();
URL url = TestFieldBasedCG.class.getClassLoader().getResource(script);
scripts.add(new SourceURLModule(url));
scripts.add(JSCallGraphUtil.getPrologueFile("prologue.js"));
try {
cg =
util.buildBoundedCG(loaders, scripts.toArray(new Module[0]), monitor, false, bound)
.getCallGraph();
System.err.println(cg);
verifyGraphAssertions(cg, assertions);
} catch (AssertionError afe) {
throw new AssertionError(builderType + ": " + afe.getMessage(), afe);
}
return cg;
}
protected void dumpCG(JSCallGraph cg) {
CallGraph2JSON cg2JSON = new CallGraph2JSON(false);
Map<String, Map<String, Set<String>>> edges = cg2JSON.extractEdges(cg);
for (Map<String, Set<String>> sitesInMethod : edges.values()) {
for (Map.Entry<String, Set<String>> entry : sitesInMethod.entrySet()) {
for (String callee : entry.getValue()) {
System.out.println(entry.getKey() + " -> " + callee);
}
}
}
}
}
| 3,803
| 37.816327
| 100
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/FieldBasedCGGamesTest.java
|
package com.ibm.wala.cast.js.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.test.RequiresInternetTests;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
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;
import org.junit.experimental.categories.Category;
@Category(RequiresInternetTests.class)
public class FieldBasedCGGamesTest extends AbstractFieldBasedTest {
@Test
public void testBunnyHunt() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.themaninblue.com/experiment/BunnyHunt/");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC);
}
@Ignore("seems to break with http issues")
@Test
public void testBeslimed() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.markus-inger.de/test/game.php");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC);
}
@Ignore("seems to break with http issues")
@Test
public void testDiggAttack() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.pixastic.com/labs/digg_attack/");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC);
}
@Ignore
@Test
public void testRiverRaider() throws IOException, WalaException, Error, CancelException {
URL url =
new URL(
"http://playstar.mobi/games/riverraider/index.html?playerId=&gameId=8&highscore=102425");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC_WORKLIST);
}
@Ignore("fails with \"timed out\" CancelException")
@Test
public void testSolitaire() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.inmensia.com/files/solitaire1.0.html");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC);
}
@Test // (expected = CancelException.class)
public void testWorldOfSolitaire() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://worldofsolitaire.com/");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC);
}
@Test
public void testMinesweeper() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.inmensia.com/files/minesweeper1.0.html");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC_WORKLIST);
}
@Test
public void testProtoRPG() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.protorpg.com/games/protorpg/?game=prologue");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC_WORKLIST);
}
@Test
public void testBattleship() throws IOException, WalaException, Error, CancelException {
URL url = new URL("http://www.sinkmyship.com/battleship/single.html");
runTest(url, new Object[][] {}, BuilderType.OPTIMISTIC_WORKLIST);
}
}
| 3,004
| 38.025974
| 101
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/FieldBasedComparisonTest.java
|
package com.ibm.wala.cast.js.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.test.ExtractingToPredictableFileNames;
import com.ibm.wala.cast.js.test.TestSimplePageCallGraphShape;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import org.junit.Test;
public class FieldBasedComparisonTest extends AbstractFieldBasedTest {
private void test(String file, Object[][] assertions, BuilderType builderType)
throws WalaException, Error, CancelException {
try (ExtractingToPredictableFileNames predictable = new ExtractingToPredictableFileNames()) {
runTest(file, assertions, builderType);
}
}
@Test(expected = AssertionError.class)
public void testSkeletonPessimistic() throws WalaException, Error, CancelException {
test(
"pages/skeleton.html",
TestSimplePageCallGraphShape.assertionsForSkeleton,
BuilderType.PESSIMISTIC);
}
@Test
public void testSkeletonOptimistic() throws WalaException, Error, CancelException {
test(
"pages/skeleton.html",
TestSimplePageCallGraphShape.assertionsForSkeleton,
BuilderType.OPTIMISTIC);
}
@Test
public void testSkeletonWorklist() throws WalaException, Error, CancelException {
test(
"pages/skeleton.html",
TestSimplePageCallGraphShape.assertionsForSkeleton,
BuilderType.OPTIMISTIC_WORKLIST);
}
@Test(expected = AssertionError.class)
public void testSkeleton2Pessimistic() throws WalaException, Error, CancelException {
test(
"pages/skeleton2.html",
TestSimplePageCallGraphShape.assertionsForSkeleton2,
BuilderType.PESSIMISTIC);
}
@Test
public void testSkeleton2Optimistic() throws WalaException, Error, CancelException {
test(
"pages/skeleton2.html",
TestSimplePageCallGraphShape.assertionsForSkeleton2,
BuilderType.OPTIMISTIC);
}
@Test
public void testSkeleton2Worklist() throws WalaException, Error, CancelException {
test(
"pages/skeleton2.html",
TestSimplePageCallGraphShape.assertionsForSkeleton2,
BuilderType.OPTIMISTIC_WORKLIST);
}
}
| 2,278
| 32.514706
| 97
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/FieldBasedJQueryTest.java
|
package com.ibm.wala.cast.js.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.test.RequiresInternetTests;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import java.net.URL;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(RequiresInternetTests.class)
public class FieldBasedJQueryTest extends AbstractFieldBasedTest {
@Test
public void test1_8_2() throws IOException, WalaException, Error, CancelException {
runTest(
new URL("http://code.jquery.com/jquery-1.8.2.js"),
new Object[][] {},
BuilderType.OPTIMISTIC_WORKLIST);
}
}
| 799
| 32.333333
| 85
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/TestBoundedFieldBasedCG.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.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import org.junit.Test;
public class TestBoundedFieldBasedCG extends AbstractFieldBasedTest {
private static final Object[][] assertionsForBound1JS =
new Object[][] {
new Object[] {ROOT, new String[] {"suffix:bounded.js"}},
new Object[] {"suffix:bounded.js", new String[] {"suffix:y", "!suffix:x"}},
new Object[] {"suffix:call", new String[] {"!suffix:m"}}
};
@Test
public void testBound1Worklist() throws WalaException, Error, CancelException {
runBoundedTest(
"tests/fieldbased/bounded.js", assertionsForBound1JS, BuilderType.OPTIMISTIC_WORKLIST, 1);
}
private static final Object[][] assertionsForBound2JS =
new Object[][] {
new Object[] {ROOT, new String[] {"suffix:bounded.js"}},
new Object[] {"suffix:bounded.js", new String[] {"suffix:x", "suffix:y"}},
new Object[] {"suffix:call", new String[] {"!suffix:m"}}
};
@Test
public void testBound2Worklist() throws WalaException, Error, CancelException {
runBoundedTest(
"tests/fieldbased/bounded.js", assertionsForBound2JS, BuilderType.OPTIMISTIC_WORKLIST, 2);
}
private static final Object[][] assertionsForBound3JS =
new Object[][] {
new Object[] {ROOT, new String[] {"suffix:bounded.js"}},
new Object[] {"suffix:bounded.js", new String[] {"suffix:x", "suffix:y", "suffix:call"}},
new Object[] {"suffix:call", new String[] {"suffix:m"}},
};
@Test
public void testBound3Worklist() throws WalaException, Error, CancelException {
runBoundedTest(
"tests/fieldbased/bounded.js", assertionsForBound3JS, BuilderType.OPTIMISTIC_WORKLIST, 3);
}
}
| 2,311
| 38.186441
| 98
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/TestFieldBasedCG.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.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.PlatformUtil;
import com.ibm.wala.util.WalaException;
import org.junit.Ignore;
import org.junit.Test;
public class TestFieldBasedCG extends AbstractFieldBasedTest {
private static final Object[][] assertionsForSimpleJS =
new Object[][] {
new Object[] {ROOT, new String[] {"suffix:simple.js"}},
new Object[] {"suffix:simple.js", new String[] {"suffix:foo", "suffix:bar", "suffix:A"}},
new Object[] {"suffix:foo", new String[] {"suffix:bar"}},
new Object[] {"suffix:aluis", new String[] {"suffix:aluis"}}
};
@Test
public void testSimpleJSPessimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/simple.js", assertionsForSimpleJS, BuilderType.PESSIMISTIC);
}
@Test
public void testSimpleJSOptimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/simple.js", assertionsForSimpleJS, BuilderType.OPTIMISTIC);
}
@Test
public void testSimpleJSWorklist() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/simple.js", assertionsForSimpleJS, BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForOneShot =
new Object[][] {
new Object[] {ROOT, new String[] {"suffix:oneshot.js"}},
new Object[] {"suffix:oneshot.js", new String[] {"suffix:f"}},
new Object[] {"suffix:f", new String[] {"suffix:g"}}
};
@Test
public void testOneshotPessimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/oneshot.js", assertionsForOneShot, BuilderType.PESSIMISTIC);
}
@Test
public void testOneshotOptimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/oneshot.js", assertionsForOneShot, BuilderType.OPTIMISTIC);
}
@Test
public void testOneshotWorklist() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/oneshot.js", assertionsForOneShot, BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForCallbacks =
new Object[][] {
new Object[] {ROOT, new String[] {"suffix:callbacks.js"}},
new Object[] {"suffix:callbacks.js", new String[] {"suffix:f"}},
new Object[] {"suffix:f", new String[] {"suffix:k", "suffix:n"}},
new Object[] {"suffix:k", new String[] {"suffix:l", "suffix:p"}}
};
@Test
public void testCallbacksOptimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/callbacks.js", assertionsForCallbacks, BuilderType.OPTIMISTIC);
}
@Test
public void testCallbacksWorklist() throws WalaException, Error, CancelException {
runTest(
"tests/fieldbased/callbacks.js", assertionsForCallbacks, BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForLexical =
new Object[][] {new Object[] {"suffix:h", new String[] {"suffix:g"}}};
@Test
public void testLexicalPessimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/lexical.js", assertionsForLexical, BuilderType.PESSIMISTIC);
}
@Test
public void testLexicalOptimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/lexical.js", assertionsForLexical, BuilderType.OPTIMISTIC);
}
@Test
public void testLexicalWorklist() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/lexical.js", assertionsForLexical, BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForReflectiveCall =
new Object[][] {
new Object[] {
"suffix:h",
new String[] {"suffix:Function_prototype_call", "suffix:Function_prototype_apply"}
},
new Object[] {"suffix:Function_prototype_call", new String[] {"suffix:f"}},
new Object[] {"suffix:Function_prototype_apply", new String[] {"suffix:x"}},
new Object[] {"suffix:f", new String[] {"suffix:k"}},
new Object[] {"suffix:p", new String[] {"suffix:n"}}
};
@Test
public void testReflectiveCallOptimistic() throws WalaException, Error, CancelException {
runTest(
"tests/fieldbased/reflective_calls.js",
assertionsForReflectiveCall,
BuilderType.OPTIMISTIC);
}
@Test
public void testReflectiveCallWorklist() throws WalaException, Error, CancelException {
runTest(
"tests/fieldbased/reflective_calls.js",
assertionsForReflectiveCall,
BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForNew =
new Object[][] {
new Object[] {"suffix:new.js", new String[] {"suffix:g", "suffix:f"}},
new Object[] {"suffix:g", new String[] {"!suffix:k"}}
};
@Test
public void testNewOptimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/new.js", assertionsForNew, BuilderType.OPTIMISTIC);
}
@Test
public void testNewWorklist() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/new.js", assertionsForNew, BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForCallbacks2 =
new Object[][] {
new Object[] {"suffix:callbacks2.js", new String[] {"suffix:g"}},
new Object[] {"suffix:g", new String[] {"suffix:k", "!suffix:l"}}
};
@Test
public void testCallbacks2Optimistic() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/callbacks2.js", assertionsForCallbacks2, BuilderType.OPTIMISTIC);
}
@Test
public void testCallbacks2Worklist() throws WalaException, Error, CancelException {
runTest(
"tests/fieldbased/callbacks2.js", assertionsForCallbacks2, BuilderType.OPTIMISTIC_WORKLIST);
}
@Test
public void testNewFnEmptyNoCrash() throws WalaException, Error, CancelException {
runTest("tests/fieldbased/new_fn_empty.js", new Object[][] {}, BuilderType.OPTIMISTIC_WORKLIST);
}
private static final Object[][] assertionsForRecursiveLexWrite =
new Object[][] {new Object[] {"suffix:outer", new String[] {"suffix:foo", "suffix:bar"}}};
@Test
public void testRecursiveLexWrite() throws WalaException, Error, CancelException {
runTest(
"tests/recursive_lex_write.js",
assertionsForRecursiveLexWrite,
BuilderType.OPTIMISTIC_WORKLIST);
}
@Test
public void testNamedFnTwice() throws WalaException, Error, CancelException {
// hack since Windows column offsets are different
String secondFunName =
PlatformUtil.onWindows() ? "suffix:testFunExp@390" : "suffix:testFunExp@381";
runTest(
"tests/named_fn_twice.js",
new Object[][] {
new Object[] {
"suffix:named_fn_twice.js", new String[] {"suffix:testFunExp", secondFunName}
},
},
BuilderType.OPTIMISTIC_WORKLIST);
}
@Test
public void testSwitchDefault() throws WalaException, Error, CancelException {
runTest(
"tests/switch_default.js",
new Object[][] {
new Object[] {"suffix:withSwitch", new String[] {"suffix:fun1", "suffix:fun2"}},
new Object[] {"suffix:withSwitchStr", new String[] {"suffix:fun3", "suffix:fun4"}}
},
BuilderType.OPTIMISTIC_WORKLIST);
}
@Ignore
@Test
public void testBug2979() throws WalaException, Error, CancelException {
System.err.println(
runTest(
"pages/2979.html",
new Object[][] {},
BuilderType.PESSIMISTIC,
BuilderType.OPTIMISTIC,
BuilderType.OPTIMISTIC_WORKLIST));
}
@Test
public void testBadNewFunctionCall() throws WalaException, CancelException {
runTest(
"tests/fieldbased/bad_new_function_call.js",
new Object[][] {},
BuilderType.OPTIMISTIC_WORKLIST);
}
}
| 8,431
| 36.145374
| 100
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/callgraph/fieldbased/test/TestPointerAnalysisRhino.java
|
package com.ibm.wala.cast.js.rhino.callgraph.fieldbased.test;
import com.ibm.wala.cast.js.test.TestPointerAnalyses;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
public class TestPointerAnalysisRhino extends TestPointerAnalyses {
public TestPointerAnalysisRhino() {
super(new CAstRhinoTranslatorFactory());
}
}
| 343
| 27.666667
| 67
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/test/HTMLCGBuilder.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.rhino.test;
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.JavaScriptFunctionDotCallTargetSelector;
import com.ibm.wala.cast.js.ipa.callgraph.RecursionCheckContextSelector;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil.CGBuilderType;
import com.ibm.wala.core.util.ProgressMaster;
import com.ibm.wala.core.util.io.FileProvider;
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.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.NullProgressMonitor;
import com.ibm.wala.util.io.CommandLine;
import com.ibm.wala.util.io.FileUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.function.Supplier;
import org.junit.Assert;
/**
* Utility class for building call graphs of HTML pages.
*
* @author mschaefer
*/
public class HTMLCGBuilder {
public static final int DEFAULT_TIMEOUT = 120;
/**
* Simple struct-like type to hold results of call graph construction.
*
* @author mschaefer
*/
public static class CGBuilderResult {
/** time it took to build the call graph; {@code -1} if timeout occurred */
public long construction_time;
/** builder responsible for building the call graph */
public JSCFABuilder builder;
/** pointer analysis results; partial if {@link #construction_time} is {@code -1} */
public PointerAnalysis<InstanceKey> pa;
/** call graph; partial if {@link #construction_time} is {@code -1} */
public CallGraph cg;
}
/**
* Build a call graph for an HTML page, optionally with a timeout.
*
* @param src the HTML page to analyse, can either be a path to a local file or a URL
* @param timeout analysis timeout in seconds, -1 means no timeout
*/
public static CGBuilderResult buildHTMLCG(
String src, int timeout, CGBuilderType builderType, Supplier<JSSourceExtractor> fExtractor) {
CGBuilderResult res = new CGBuilderResult();
URL url = null;
try {
url = toUrl(src);
} catch (MalformedURLException e1) {
Assert.fail("Could not find page to analyse: " + src);
}
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
JSCFABuilder builder = null;
try {
builder = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url, builderType, fExtractor);
// TODO we need to find a better way to do this ContextSelector delegation;
// the code below belongs somewhere else!!!
// the bound of 4 is what is needed to pass our current framework tests
builder.setContextSelector(new RecursionCheckContextSelector(builder.getContextSelector()));
IProgressMonitor master =
ProgressMaster.make(new NullProgressMonitor(), timeout * 1000, false);
if (timeout > 0) {
master.beginTask("runSolver", 1);
}
long start = System.currentTimeMillis();
CallGraph cg =
timeout > 0
? builder.makeCallGraph(builder.getOptions(), master)
: builder.makeCallGraph(builder.getOptions());
long end = System.currentTimeMillis();
master.done();
res.construction_time = (end - start);
res.cg = cg;
res.pa = builder.getPointerAnalysis();
res.builder = builder;
return res;
} catch (CallGraphBuilderCancelException e) {
res.construction_time = -1;
res.cg = e.getPartialCallGraph();
res.pa = e.getPartialPointerAnalysis();
res.builder = builder;
return res;
} catch (Exception e) {
throw new Error(e);
}
}
private static 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, HTMLCGBuilder.class.getClassLoader());
URL url = f.toURI().toURL();
return url;
} catch (FileNotFoundException fnfe) {
return new URL(src);
}
}
/**
* Usage: HTMLCGBuilder -src path_to_html_file -timeout timeout_in_seconds -reachable
* function_name timeout argument is optional and defaults to {@link #DEFAULT_TIMEOUT}. reachable
* argument is optional. if provided, and some reachable function name contains function_name,
* will print "REACHABLE"
*/
public static void main(String[] args) throws IOException {
Properties parsedArgs = CommandLine.parse(args);
String src = parsedArgs.getProperty("src");
if (src == null) {
throw new IllegalArgumentException("-src argument is required");
}
// if src is a JS file, build trivial wrapper HTML file
if (src.endsWith(".js")) {
File tmpFile = File.createTempFile("HTMLCGBuilder", ".html");
tmpFile.deleteOnExit();
FileUtil.writeFile(
tmpFile,
"<html>"
+ " <head>"
+ " <title></title>"
+ " <script src=\""
+ src
+ "\" type='text/javascript'></script>"
+ " </head>"
+ "<body>"
+ "</body>"
+ "</html>");
src = tmpFile.getAbsolutePath();
}
int timeout;
if (parsedArgs.containsKey("timeout")) {
timeout = Integer.parseInt(parsedArgs.getProperty("timeout"));
} else {
timeout = DEFAULT_TIMEOUT;
}
String reachableName = null;
if (parsedArgs.containsKey("reachable")) {
reachableName = parsedArgs.getProperty("reachable");
}
// suppress debug output
JavaScriptFunctionDotCallTargetSelector.WARN_ABOUT_IMPRECISE_CALLGRAPH = false;
// build call graph
CGBuilderResult res =
buildHTMLCG(src, timeout, CGBuilderType.ONE_CFA, DefaultSourceExtractor.factory);
if (res.construction_time == -1) System.out.println("TIMED OUT");
else
System.out.println(
"Call graph construction took " + res.construction_time / 1000.0 + " seconds");
if (reachableName != null) {
for (CGNode node : res.cg) {
if (node.getMethod().getDeclaringClass().getName().toString().contains(reachableName)) {
System.out.println("REACHABLE");
break;
}
}
}
}
}
| 7,183
| 35.100503
| 100
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/rhino/test/PrintIRs.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.rhino.test;
import com.ibm.wala.cast.ipa.callgraph.CAstAnalysisScope;
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.MappedSourceModule;
import com.ibm.wala.cast.js.html.WebPageLoaderFactory;
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.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SourceModule;
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.ssa.IR;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.Pair;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
import java.util.function.Predicate;
public class PrintIRs {
/** prints the IR of each function in the script */
public static void printIRsForJS(String filename) throws ClassHierarchyException {
// use Rhino to parse JavaScript
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
// build a class hierarchy, for access to code info
IClassHierarchy cha = JSCallGraphUtil.makeHierarchyForScripts(filename);
printIRsForCHA(cha, t -> t.startsWith("Lprologue.js"));
}
protected static void printIRsForCHA(IClassHierarchy cha, Predicate<String> exclude) {
// for constructing IRs
IRFactory<IMethod> factory = AstIRFactory.makeDefaultFactory();
for (IClass klass : cha) {
// ignore models of built-in JavaScript methods
String name = klass.getName().toString();
if (exclude.test(name)) continue;
// get the IMethod representing the code
IMethod m = klass.getMethod(AstMethodReference.fnSelector);
if (m != null) {
IR ir = factory.makeIR(m, Everywhere.EVERYWHERE, new SSAOptions());
System.out.println(ir);
if (m instanceof AstMethod) {
AstMethod astMethod = (AstMethod) m;
System.out.println(astMethod.getSourcePosition());
}
System.out.println("===================================================\n");
}
}
}
private static void printIRsForHTML(String filename)
throws IllegalArgumentException, MalformedURLException, IOException, WalaException, Error {
// use Rhino to parse JavaScript
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
// add model for DOM APIs
JavaScriptLoader.addBootstrapFile(WebUtil.preamble);
URL url = new File(filename).toURI().toURL();
Pair<Set<MappedSourceModule>, File> p =
WebUtil.extractScriptFromHTML(url, DefaultSourceExtractor.factory);
SourceModule[] scripts = p.fst.toArray(new SourceModule[] {});
JavaScriptLoaderFactory loaders =
new WebPageLoaderFactory(JSCallGraphUtil.getTranslatorFactory());
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);
printIRsForCHA(cha, t -> t.startsWith("Lprologue.js") || t.startsWith("Lpreamble.js"));
}
public static void main(String[] args)
throws IOException, IllegalArgumentException, WalaException, Error {
String filename = args[0];
if (filename.endsWith(".js")) {
printIRsForJS(filename);
} else if (filename.endsWith(".html")) {
printIRsForHTML(filename);
}
}
}
| 4,540
| 41.439252
| 97
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/RequiresInternetTests.java
|
package com.ibm.wala.cast.js.test;
/**
* JUnit category marker for tests that require Internet access
*
* <p>To exclude Internet-requiring tests, do any of the following:
*
* <ul>
* <li>add “{@code -PexcludeRequiresInternetTests}” to the Gradle command line,
* <li>add “{@code --offline}” to the Gradle command line, or
* <li>set the {@code $CI} environment variable to "{@code true}".
* </ul>
*
* <p>Note that <a
* href="https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables">GitHub
* actions always set {@code $CI} to "{@code true}"</a>, so these tests will never run during GitHub
* actions.
*/
public interface RequiresInternetTests {}
| 716
| 34.85
| 124
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestAjaxsltCallGraphShapeRhino.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.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestAjaxsltCallGraphShapeRhino extends TestAjaxsltCallGraphShape {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
}
| 745
| 30.083333
| 79
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestArgumentSensitivityRhino.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.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestArgumentSensitivityRhino extends TestArgumentSensitivity {
@Before
public void setUp() {
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
}
}
| 749
| 30.25
| 75
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestCPA.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.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.CPAContextSelector;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
public class TestCPA {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
@Test
public void testCPA()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder builder = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "cpa.js");
builder.setContextSelector(new CPAContextSelector(builder.getContextSelector()));
CallGraph CG = builder.makeCallGraph(builder.getOptions());
JSCallGraphUtil.AVOID_DUMP = false;
CAstCallGraphUtil.dumpCG(builder.getCFAContextInterpreter(), builder.getPointerAnalysis(), CG);
}
}
| 1,657
| 36.681818
| 99
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestCallGraph2JSON.java
|
package com.ibm.wala.cast.js.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.CallGraph2JSON;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
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.HashMapFactory;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hamcrest.core.IsIterableContaining;
import org.junit.Before;
import org.junit.Test;
public class TestCallGraph2JSON {
private FieldBasedCGUtil util;
@Before
public void setUp() throws Exception {
util = new FieldBasedCGUtil(new CAstRhinoTranslatorFactory());
}
@Test
public void testBasic() throws WalaException, CancelException {
String script = "tests/fieldbased/simple.js";
CallGraph cg = buildCallGraph(script);
CallGraph2JSON cg2JSON = new CallGraph2JSON(true);
Map<String, Map<String, String[]>> parsedJSONCG = getParsedJSONCG(cg, cg2JSON);
Set<String> methods = parsedJSONCG.keySet();
assertEquals(3, methods.size());
for (Entry<String, Map<String, String[]>> entry : parsedJSONCG.entrySet()) {
if (entry.getKey().startsWith("simple.js@3")) {
Map<String, String[]> callSites = entry.getValue();
assertThat(
Arrays.asList(getTargetsStartingWith(callSites, "simple.js@4")),
hasItemStartingWith("simple.js@7"));
}
}
Map<String, String[]> flattened = flattenParsedCG(parsedJSONCG);
assertEquals(5, flattened.keySet().size());
flattened.values().stream().forEach(callees -> assertEquals(1, callees.length));
}
@Test
public void testNative() throws WalaException, CancelException {
String script = "tests/fieldbased/native_call.js";
CallGraph cg = buildCallGraph(script);
CallGraph2JSON cg2JSON = new CallGraph2JSON(false);
Map<String, String[]> parsed = getFlattenedJSONCG(cg, cg2JSON);
assertArrayEquals(
new String[] {"Array_prototype_pop (Native)"},
getTargetsStartingWith(parsed, "native_call.js@2"));
}
@Test
public void testReflectiveCalls() throws WalaException, CancelException {
String script = "tests/fieldbased/reflective_calls.js";
CallGraph cg = buildCallGraph(script);
CallGraph2JSON cg2JSON = new CallGraph2JSON(false, true);
Map<String, String[]> parsed = getFlattenedJSONCG(cg, cg2JSON);
assertThat(
Arrays.asList(getTargetsStartingWith(parsed, "reflective_calls.js@10")),
hasItemStartingWith("Function_prototype_call (Native) [reflective_calls.js@10"));
assertThat(
Arrays.asList(getTargetsStartingWith(parsed, "reflective_calls.js@11")),
hasItemStartingWith("Function_prototype_apply (Native) [reflective_calls.js@11"));
assertThat(
Arrays.asList(
getTargetsStartingWith(
parsed, "Function_prototype_call (Native) [reflective_calls.js@10")),
hasItemStartingWith("reflective_calls.js@1"));
assertThat(
Arrays.asList(
getTargetsStartingWith(
parsed, "Function_prototype_apply (Native) [reflective_calls.js@11")),
hasItemStartingWith("reflective_calls.js@5"));
}
@Test
public void testNativeCallback() throws WalaException, CancelException {
String script = "tests/fieldbased/native_callback.js";
CallGraph cg = buildCallGraph(script);
CallGraph2JSON cg2JSON = new CallGraph2JSON(false);
Map<String, String[]> parsed = getFlattenedJSONCG(cg, cg2JSON);
assertArrayEquals(
new String[] {"Array_prototype_map (Native)"},
getTargetsStartingWith(parsed, "native_callback.js@2"));
assertThat(
Arrays.asList(getTargetsStartingWith(parsed, "Function_prototype_call (Native)")),
hasItemStartingWith("native_callback.js@3"));
}
/**
* returns a parsed version of the JSON of the call graph, but flattened to just be a map from
* call sites to targets (stripping out the outermost level of containing methods)
*/
private static Map<String, String[]> getFlattenedJSONCG(CallGraph cg, CallGraph2JSON cg2JSON) {
Map<String, Map<String, String[]>> parsed = getParsedJSONCG(cg, cg2JSON);
return flattenParsedCG(parsed);
}
private static Map<String, String[]> flattenParsedCG(Map<String, Map<String, String[]>> parsed) {
Map<String, String[]> result = HashMapFactory.make();
for (Map<String, String[]> siteInfo : parsed.values()) {
result.putAll(siteInfo);
}
return result;
}
private static Map<String, Map<String, String[]>> getParsedJSONCG(
CallGraph cg, CallGraph2JSON cg2JSON) {
String json = cg2JSON.serialize(cg);
// System.err.println(json);
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, Map<String, String[]>>>() {}.getType();
return gson.fromJson(json, mapType);
}
private CallGraph buildCallGraph(String script) throws WalaException, CancelException {
URL scriptURL = TestCallGraph2JSON.class.getClassLoader().getResource(script);
return util.buildCG(
scriptURL, BuilderType.OPTIMISTIC_WORKLIST, null, false, DefaultSourceExtractor::new)
.getCallGraph();
}
/**
* We need this method since column offsets can differ across platforms, so we can't do an exact
* position match
*/
private static String[] getTargetsStartingWith(Map<String, String[]> parsedJSON, String prefix) {
for (Entry<String, String[]> entry : parsedJSON.entrySet()) {
if (entry.getKey().startsWith(prefix)) {
return entry.getValue();
}
}
throw new RuntimeException(prefix + " not a key prefix");
}
/**
* We need this method since column offsets can differ across platforms, so we can't do an exact
* position match
*/
private static IsIterableContaining<String> hasItemStartingWith(String prefix) {
return new IsIterableContaining<>(startsWith(prefix));
}
}
| 6,466
| 38.919753
| 99
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestCorrelatedPairExtractionRhino.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.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.ipa.callgraph.correlations.CorrelationFinder;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.translator.RhinoToAstTranslator;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.classLoader.SourceModule;
import java.io.IOException;
public class TestCorrelatedPairExtractionRhino extends TestCorrelatedPairExtraction {
@Override
protected CorrelationFinder makeCorrelationFinder() {
return new CorrelationFinder(new CAstRhinoTranslatorFactory());
}
@Override
protected CAstEntity parseJS(CAstImpl ast, SourceModule module) throws IOException {
RhinoToAstTranslator translator =
new RhinoToAstTranslator(ast, module, module.getName(), false);
CAstEntity entity = null;
try {
entity = translator.translateToCAst();
} catch (Error e) {
e.printStackTrace();
assert false;
}
return entity;
}
}
| 1,455
| 32.860465
| 86
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestFlowGraphJSON.java
|
package com.ibm.wala.cast.js.test;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertArrayEquals;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ibm.wala.cast.js.callgraph.fieldbased.FieldBasedCallGraphBuilder.CallGraphResult;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil;
import com.ibm.wala.cast.js.util.FieldBasedCGUtil.BuilderType;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class TestFlowGraphJSON {
private static final String SCRIPT = "tests/fieldbased/flowgraph_constraints.js";
private Map<String, String[]> parsedJSON;
@Before
public void setUp() throws Exception {
parsedJSON = getParsedFlowGraphJSON(SCRIPT);
}
@Test
public void testNamedIIFE() {
assertArrayEquals(
new String[] {
"Var(flowgraph_constraints.js@2, [f1])", "Var(flowgraph_constraints.js@1, %ssa_val 28)"
},
parsedJSON.get("Func(flowgraph_constraints.js@2)"));
}
@Test
public void testParamAndReturn() {
assertArrayEquals(
new String[] {"Var(flowgraph_constraints.js@8, [p])"},
parsedJSON.get("Param(Func(flowgraph_constraints.js@8), 2)"));
assertArrayEquals(
new String[] {"Ret(Func(flowgraph_constraints.js@8))"},
parsedJSON.get("Var(flowgraph_constraints.js@8, [p])"));
assertThat(
Arrays.asList(parsedJSON.get("Var(flowgraph_constraints.js@12, [x])")),
containsInAnyOrder(
"Param(Func(flowgraph_constraints.js@8), 2)",
"Args(Func(flowgraph_constraints.js@8))"));
assertThat(
Arrays.asList(parsedJSON.get("Var(flowgraph_constraints.js@17, [x])")),
containsInAnyOrder(
"Param(Func(flowgraph_constraints.js@8), 2)",
"Args(Func(flowgraph_constraints.js@8))"));
assertThat(
Arrays.asList(parsedJSON.get("Ret(Func(flowgraph_constraints.js@8))")),
containsInAnyOrder(
"Var(flowgraph_constraints.js@17, [y])", "Var(flowgraph_constraints.js@12, [y])"));
}
@Test
public void testCallAndApply() {
assertThat(
Arrays.asList(
parsedJSON.get("Var(flowgraph_constraints.js@29, [nested, x, $$destructure$rcvr7])")),
hasItems(
"ReflectiveCallee(flowgraph_constraints.js@33)",
"ReflectiveCallee(flowgraph_constraints.js@32)",
"Param(Func(flowgraph_constraints.js@30), 2)"));
assertThat(
Arrays.asList(parsedJSON.get("Ret(Func(flowgraph_constraints.js@30))")),
containsInAnyOrder(
"Var(flowgraph_constraints.js@29, [res1])",
"Var(flowgraph_constraints.js@29, [res2])"));
}
private static Map<String, String[]> getParsedFlowGraphJSON(String script)
throws WalaException, CancelException {
URL scriptURL = TestCallGraph2JSON.class.getClassLoader().getResource(script);
FieldBasedCGUtil util = new FieldBasedCGUtil(new CAstRhinoTranslatorFactory());
CallGraphResult callGraphResult =
util.buildCG(
scriptURL, BuilderType.OPTIMISTIC_WORKLIST, null, false, DefaultSourceExtractor::new);
FlowGraph fg = callGraphResult.getFlowGraph();
String json = fg.toJSON();
// Strip out character offsets, as they differ on Windows and make it hard to write assertions.
json = json.replaceAll(":[0-9]+-[0-9]+", "");
// System.err.println("CALL GRAPH:");
// System.err.println(callGraphResult.getCallGraph());
// System.err.println(json);
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, String[]>>() {}.getType();
return gson.fromJson(json, mapType);
}
}
| 4,163
| 39.038462
| 99
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestForInBodyExtractionRhino.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.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.translator.RhinoToAstTranslator;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.classLoader.SourceModule;
import java.io.IOException;
public class TestForInBodyExtractionRhino extends TestForInBodyExtraction {
@Override
protected CAstEntity parseJS(CAstImpl ast, SourceModule module) throws IOException {
RhinoToAstTranslator translator =
new RhinoToAstTranslator(ast, module, module.getName(), false);
CAstEntity entity = null;
try {
entity = translator.translateToCAst();
} catch (Error e) {
e.printStackTrace();
assert false;
}
return entity;
}
}
| 1,163
| 31.333333
| 86
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestForInLoopHackRhino.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.js.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestForInLoopHackRhino extends TestForInLoopHack {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
}
| 722
| 29.125
| 76
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestJQueryExamplesRhino.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.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestJQueryExamplesRhino extends TestJQueryExamples {
@Before
public void setUp() {
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
}
}
| 739
| 29.833333
| 75
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestJavaScriptSlicerRhino.java
|
package com.ibm.wala.cast.js.test;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestJavaScriptSlicerRhino extends TestJavaScriptSlicer {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
}
| 360
| 24.785714
| 76
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestLexicalModRefRhino.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.js.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestLexicalModRefRhino extends TestLexicalModRef {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
}
| 722
| 29.125
| 76
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestMediawikiCallGraphShapeRhino.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.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestMediawikiCallGraphShapeRhino extends TestMediawikiCallGraphShape {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
}
| 749
| 30.25
| 83
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestPrototypeCallGraphShapeRhino.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.translator.CAstRhinoTranslatorFactory;
import org.junit.Before;
public class TestPrototypeCallGraphShapeRhino extends TestPrototypeCallGraphShape {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
}
| 749
| 30.25
| 83
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestRhinoSourceMap.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 static com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.makeHierarchy;
import static com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.makeLoaders;
import static com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory;
import static com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil.makeScriptScope;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.cast.util.SourceBuffer;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.collections.HashMapFactory;
import java.io.IOException;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class TestRhinoSourceMap {
@Before
public void setUp() {
setTranslatorFactory(new CAstRhinoTranslatorFactory());
}
private static final String[][] jquery_spec_testSource =
new String[][] {
new String[] {
"Ltests/jquery_spec_test.js/anonymous__0/isEmptyDataObject",
"function isEmptyDataObject(obj) {\n"
+ " for (var name in obj) {\n"
+ " if (name !== \"toJSON\") {\n"
+ " return false;\n"
+ " }\n"
+ " }\n"
+ " return true;\n"
+ " }"
},
new String[] {
"Ltests/jquery_spec_test.js/anonymous__0/anonymous__59/anonymous__62/anonymous__63/anonymous__64/anonymous__65",
"function anonymous__65() {\n"
+ " returned = fn.apply(this, arguments);\n"
+ " if (returned && jQuery.isFunction(returned.promise)) {\n"
+ " returned.promise().then(newDefer.resolve, newDefer.reject);\n"
+ " } else {\n"
+ " newDefer[action](returned);\n"
+ " }\n"
+ " }"
},
new String[] {
"Ltests/jquery_spec_test.js/anonymous__0/anonymous__386/anonymous__392",
"function anonymous__392(map) {\n"
+ " if (map) {\n"
+ " var tmp;\n"
+ " if (state < 2) {\n"
+ " for (tmp in map) {\n"
+ " statusCode[tmp] = [ statusCode[tmp], map[tmp] ];\n"
+ " }\n"
+ " } else {\n"
+ " tmp = map[jqXHR.status];\n"
+ " jqXHR.then(tmp, tmp);\n"
+ " }\n"
+ " }\n"
+ " return this;\n"
+ " }"
},
new String[] {
"Ltests/jquery_spec_test.js/anonymous__0/getWindow",
"function getWindow(elem) {\n"
+ " return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;\n"
+ " }"
},
new String[] {
"Ltests/jquery_spec_test.js/anonymous__0/anonymous__1/anonymous__7",
"function anonymous__7(elems, name, selector) {\n"
+ " var ret = this.constructor();\n"
+ " if (jQuery.isArray(elems)) {\n"
+ " push.apply(ret, elems);\n"
+ " } else {\n"
+ " jQuery.merge(ret, elems);\n"
+ " }\n"
+ " ret.prevObject = this;\n"
+ " ret.context = this.context;\n"
+ " if (name === \"find\") {\n"
+ " ret.selector = this.selector + (this.selector ? \" \" : \"\") + selector;\n"
+ " } else if (name) {\n"
+ " ret.selector = this.selector + \".\" + name + \"(\" + selector + \")\";\n"
+ " }\n"
+ " return ret;\n"
+ " }"
},
new String[] {
"Ltests/jquery_spec_test.js/anonymous__0/anonymous__1/anonymous__17",
"function anonymous__17() {\n"
+ " var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false;\n"
+ " if (typeof target === \"boolean\") {\n"
+ " deep = target;\n"
+ " target = arguments[1] || {};\n"
+ " i = 2;\n"
+ " }\n"
+ " if (typeof target !== \"object\" && !jQuery.isFunction(target)) {\n"
+ " target = {};\n"
+ " }\n"
+ " if (length === i) {\n"
+ " target = this;\n"
+ " --i;\n"
+ " }\n"
+ " for (; i < length; i++) {\n"
+ " if ((options = arguments[i]) != null) {\n"
+ " for (name in options) {\n"
+ " (function _forin_body_extra_1(name) { var src = target[name];\n"
+ " var copy = options[name];\n"
+ " if (target === copy) {\n"
+ " return; //continue;\n"
+ " }\n"
+ " if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {\n"
+ " if (copyIsArray) {\n"
+ " copyIsArray = false;\n"
+ " clone = src && jQuery.isArray(src) ? src : [];\n"
+ " } else {\n"
+ " clone = src && jQuery.isPlainObject(src) ? src : {};\n"
+ " }\n"
+ " target[name] = jQuery.extend(deep, clone, copy);\n"
+ " } else if (copy !== undefined) {\n"
+ " target[name] = copy;\n"
+ " } })(name);\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " return target;\n"
+ " }"
}
};
@Test
public void testJquerySpecTestSourceMappings()
throws IllegalArgumentException, IOException, ClassHierarchyException {
checkFunctionBodies("jquery_spec_test.js", jquery_spec_testSource);
}
private static void checkFunctionBodies(String fileName, String[][] assertions)
throws IOException, ClassHierarchyException {
Map<String, String> sources = HashMapFactory.make();
for (String[] assertion : assertions) {
sources.put(assertion[0], assertion[1]);
}
JavaScriptLoaderFactory loaders = makeLoaders(null);
AnalysisScope scope = makeScriptScope("tests", fileName, loaders);
IClassHierarchy cha = makeHierarchy(scope, loaders);
for (IClass cls : cha) {
if (cls.getName().toString().contains(fileName)) {
AstMethod fun = (AstMethod) cls.getMethod(AstMethodReference.fnSelector);
// System.err.println(fun.getDeclaringClass().getName() + " " + fun.getSourcePosition());
SourceBuffer sb = new SourceBuffer(fun.getSourcePosition());
// System.err.println(sb);
if (sources.containsKey(fun.getDeclaringClass().getName().toString())) {
System.err.println(
"checking source of "
+ fun.getDeclaringClass().getName()
+ " at "
+ fun.getSourcePosition());
Assert.assertEquals(
sources.get(fun.getDeclaringClass().getName().toString()), sb.toString());
}
}
}
}
}
| 9,122
| 48.313514
| 158
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestSimpleCallGraphShapeRhino.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.JSCFABuilder;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
public class TestSimpleCallGraphShapeRhino extends TestSimpleCallGraphShape {
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
}
@Test
public void test214631()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCFABuilder b = JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "214631.js");
b.makeCallGraph(b.getOptions());
b.getPointerAnalysis();
// just make sure this does not crash
}
@Test
public void testRewriterDoesNotChangeLabelsBug()
throws IOException, IllegalArgumentException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "rewrite_does_not_change_lables_bug.js");
// all we need is for it to finish building CG successfully.
}
@Test
public void testRepr()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "repr.js");
}
@Test
public void testTranslateToCAstCrash1()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "rhino_crash1.js");
}
@Test
public void testTranslateToCAstCrash2()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "rhino_crash2.js");
}
@Test
public void testTranslateToCAstCrash3()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "rhino_crash3.js");
}
@Test
public void testNonLoopBreakLabel()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "non_loop_break.js");
}
@Test
public void testForInName()
throws IllegalArgumentException, IOException, CancelException, WalaException {
JSCallGraphBuilderUtil.makeScriptCG("tests", "for_in_name.js");
}
@Test(expected = WalaException.class)
public void testParseError()
throws IllegalArgumentException, IOException, CancelException, WalaException {
PropagationCallGraphBuilder B =
JSCallGraphBuilderUtil.makeScriptCGBuilder("tests", "portal-example-simple.html");
B.makeCallGraph(B.getOptions());
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(B.getClassHierarchy());
}
}
| 3,306
| 34.945652
| 90
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/test/TestSimplePageCallGraphShapeRhinoJericho.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.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.cast.js.html.jericho.JerichoHtmlParser;
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.Test;
public class TestSimplePageCallGraphShapeRhinoJericho extends TestSimplePageCallGraphShapeRhino {
@Test
public void testCrawl() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/crawl.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url, DefaultSourceExtractor.factory);
verifyGraphAssertions(CG, null);
}
@Test
public void testParseError() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/garbage.html");
JSCFABuilder B = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url, DefaultSourceExtractor.factory);
B.makeCallGraph(B.getOptions());
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(B.getClassHierarchy());
}
@Override
protected IHtmlParser getParser() {
return new JerichoHtmlParser();
}
}
| 1,754
| 37.152174
| 99
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/test/java/com/ibm/wala/cast/js/vis/JsViewerDriver.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.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.DomLessSourceExtractor;
import com.ibm.wala.cast.js.html.IdentityUrlResolver;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.html.MappedSourceModule;
import com.ibm.wala.cast.js.html.WebPageLoaderFactory;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.cast.js.html.jericho.JerichoHtmlParser;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
import com.ibm.wala.cast.js.util.JSCallGraphBuilderUtil;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.classLoader.SourceModule;
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.cha.ClassHierarchyException;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import java.net.URL;
import java.util.Set;
public class JsViewerDriver extends JSCallGraphBuilderUtil {
public static void main(String args[])
throws ClassHierarchyException, IllegalArgumentException, IOException, CancelException, Error,
WalaException {
if (args.length != 1) {
System.out.println("Usage: <URL of html page to analyze>");
System.exit(1);
}
boolean domless = false;
URL url = new URL(args[0]);
// computing CG + PA
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
JavaScriptLoader.addBootstrapFile(WebUtil.preamble);
SourceModule[] sources = getSources(domless, url);
JSCFABuilder builder =
makeCGBuilder(
new WebPageLoaderFactory(translatorFactory),
sources,
CGBuilderType.ZERO_ONE_CFA,
AstIRFactory.makeDefaultFactory());
builder.setBaseURL(url);
CallGraph cg = builder.makeCallGraph(builder.getOptions());
PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();
JsViewer ignored = new JsViewer(cg, pa);
}
private static SourceModule[] getSources(boolean domless, URL url) throws IOException, Error {
JSSourceExtractor sourceExtractor;
if (domless) {
sourceExtractor = new DomLessSourceExtractor();
} else {
sourceExtractor = new DefaultSourceExtractor();
}
Set<MappedSourceModule> sourcesMap =
sourceExtractor.extractSources(url, new JerichoHtmlParser(), new IdentityUrlResolver());
SourceModule[] sources = new SourceFileModule[sourcesMap.size()];
int i = 0;
for (SourceModule m : sourcesMap) {
sources[i++] = m;
}
return sources;
}
}
| 3,365
| 35.989011
| 100
|
java
|
WALA
|
WALA-master/cast/js/rhino/src/testFixtures/java/com/ibm/wala/cast/js/test/TestSimplePageCallGraphShapeRhino.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.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
import com.ibm.wala.cast.js.translator.CAstRhinoTranslatorFactory;
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.Test;
public abstract class TestSimplePageCallGraphShapeRhino extends TestSimplePageCallGraphShape {
private static final Object[][] assertionsForPage3 =
new Object[][] {
new Object[] {ROOT, new String[] {"page3.html"}},
new Object[] {"page3.html", new String[] {"page3.html/__WINDOW_MAIN__"}}
};
@Test
public void testPage3() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/page3.html");
CallGraph CG = JSCallGraphBuilderUtil.makeHTMLCG(url, DefaultSourceExtractor.factory);
verifyGraphAssertions(CG, assertionsForPage3);
}
@Test(expected = WalaException.class)
public void testJSParseError() throws IllegalArgumentException, CancelException, WalaException {
URL url = getClass().getClassLoader().getResource("pages/garbage2.html");
JSCFABuilder B = JSCallGraphBuilderUtil.makeHTMLCGBuilder(url, DefaultSourceExtractor.factory);
B.makeCallGraph(B.getOptions());
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(B.getClassHierarchy());
}
@Override
protected abstract IHtmlParser getParser();
@Override
@Before
public void setUp() {
super.setUp();
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(
new CAstRhinoTranslatorFactory());
WebUtil.setFactory(TestSimplePageCallGraphShapeRhino.this::getParser);
}
}
| 2,341
| 37.393443
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/analysis/typeInference/JSPrimitiveType.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.analysis.typeInference;
import com.ibm.wala.analysis.typeInference.PrimitiveType;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.types.TypeReference;
public class JSPrimitiveType extends PrimitiveType {
public static void init() {
new JSPrimitiveType(JavaScriptTypes.Undefined, -1);
new JSPrimitiveType(JavaScriptTypes.Null, -1);
new JSPrimitiveType(JavaScriptTypes.Boolean, -1);
new JSPrimitiveType(JavaScriptTypes.String, -1);
new JSPrimitiveType(JavaScriptTypes.Number, -1);
new JSPrimitiveType(JavaScriptTypes.Date, -1);
new JSPrimitiveType(JavaScriptTypes.RegExp, -1);
}
public JSPrimitiveType(TypeReference reference, int size) {
super(reference, size);
}
}
| 1,135
| 28.128205
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/analysis/typeInference/JSTypeInference.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.analysis.typeInference;
import com.ibm.wala.analysis.typeInference.ConeType;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.analysis.typeInference.TypeVariable;
import com.ibm.wala.cast.analysis.typeInference.AstTypeInference;
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.cast.js.types.JavaScriptTypes;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
public class JSTypeInference extends AstTypeInference {
public JSTypeInference(IR ir, IClassHierarchy cha) {
super(ir, new PointType(cha.lookupClass(JavaScriptTypes.Boolean)), true);
}
@Override
protected void initialize() {
class JSTypeOperatorFactory extends AstTypeOperatorFactory
implements com.ibm.wala.cast.js.ssa.JSInstructionVisitor {
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke inst) {
result = new DeclaredTypeOperator(new ConeType(cha.getRootClass()));
}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction inst) {
result = new DeclaredTypeOperator(new PointType(cha.lookupClass(JavaScriptTypes.String)));
}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf inst) {
result = new DeclaredTypeOperator(new PointType(cha.lookupClass(JavaScriptTypes.Boolean)));
}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {}
@Override
public void visitSetPrototype(SetPrototype instruction) {}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {
result = new DeclaredTypeOperator(new ConeType(cha.getRootClass()));
}
}
class JSTypeVarFactory extends TypeVarFactory {
private TypeAbstraction make(TypeReference typeRef) {
return new PointType(cha.lookupClass(typeRef));
}
@Override
public TypeVariable makeVariable(int vn) {
if (ir.getSymbolTable().isStringConstant(vn)) {
return new TypeVariable(make(JavaScriptTypes.String));
} else if (ir.getSymbolTable().isBooleanConstant(vn)) {
return new TypeVariable(make(JavaScriptTypes.Boolean));
} else if (ir.getSymbolTable().isNullConstant(vn)) {
return new TypeVariable(make(JavaScriptTypes.Null));
} else if (ir.getSymbolTable().isNumberConstant(vn)) {
return new TypeVariable(make(JavaScriptTypes.Number));
} else {
return super.makeVariable(vn);
}
}
}
init(ir, new JSTypeVarFactory(), new JSTypeOperatorFactory());
}
@Override
public TypeAbstraction getConstantType(int valueNumber) {
SymbolTable st = ir.getSymbolTable();
if (st.isStringConstant(valueNumber)) {
return new PointType(cha.lookupClass(JavaScriptTypes.String));
} else if (st.isBooleanConstant(valueNumber)) {
return new PointType(cha.lookupClass(JavaScriptTypes.Boolean));
} else if (st.isNullConstant(valueNumber)) {
return new PointType(cha.lookupClass(JavaScriptTypes.Null));
} else {
return new PointType(cha.lookupClass(JavaScriptTypes.Number));
}
}
}
| 4,116
| 36.427273
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/FieldBasedCallGraphBuilder.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.callgraph.fieldbased;
import com.ibm.wala.cast.ipa.callgraph.AstContextInsensitiveSSAContextInterpreter;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraphBuilder;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.CallVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.ObjectVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VarVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph;
import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptConstructTargetSelector;
import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptFunctionApplyContextInterpreter;
import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptFunctionApplyTargetSelector;
import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptFunctionDotCallTargetSelector;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions.JavaScriptConstructor;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
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.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.ContextInsensitiveSelector;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultSSAInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DelegatingSSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.nCFAContextSelector;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Iterator;
import java.util.Set;
/**
* Abstract call graph builder class for building a call graph from a field-based flow graph. The
* algorithm for building the flow graph is left unspecified, and is implemented differently by
* subclasses.
*
* @author mschaefer
*/
public abstract class FieldBasedCallGraphBuilder {
// class hierarchy of the program to be analysed
protected final IClassHierarchy cha;
// standard call graph machinery
protected final AnalysisOptions options;
protected final IAnalysisCacheView cache;
protected final JavaScriptConstructorFunctions constructors;
public final MethodTargetSelector targetSelector;
protected final boolean supportFullPointerAnalysis;
private static final boolean LOG_TIMINGS = true;
public FieldBasedCallGraphBuilder(
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView iAnalysisCacheView,
boolean supportFullPointerAnalysis) {
this.cha = cha;
this.options = options;
this.cache = iAnalysisCacheView;
this.constructors = new JavaScriptConstructorFunctions(cha);
this.targetSelector = setupMethodTargetSelector(constructors, options);
this.supportFullPointerAnalysis = supportFullPointerAnalysis;
}
private static MethodTargetSelector setupMethodTargetSelector(
JavaScriptConstructorFunctions constructors2, AnalysisOptions options) {
MethodTargetSelector result =
new JavaScriptConstructTargetSelector(constructors2, options.getMethodTargetSelector());
if (options instanceof JSAnalysisOptions && ((JSAnalysisOptions) options).handleCallApply()) {
result =
new JavaScriptFunctionApplyTargetSelector(
new JavaScriptFunctionDotCallTargetSelector(result));
}
return result;
}
protected FlowGraph flowGraphFactory() {
FlowGraphBuilder builder = new FlowGraphBuilder(cha, cache, supportFullPointerAnalysis);
return builder.buildFlowGraph();
}
/** Build a flow graph for the program to be analysed. */
public abstract FlowGraph buildFlowGraph(IProgressMonitor monitor) throws CancelException;
/** Full result of call graph computation */
public static class CallGraphResult {
private final JSCallGraph callGraph;
private final PointerAnalysis<ObjectVertex> pointerAnalysis;
private final FlowGraph flowGraph;
public CallGraphResult(
JSCallGraph callGraph, PointerAnalysis<ObjectVertex> pointerAnalysis, FlowGraph flowGraph) {
this.callGraph = callGraph;
this.pointerAnalysis = pointerAnalysis;
this.flowGraph = flowGraph;
}
public JSCallGraph getCallGraph() {
return callGraph;
}
public PointerAnalysis<ObjectVertex> getPointerAnalysis() {
return pointerAnalysis;
}
public FlowGraph getFlowGraph() {
return flowGraph;
}
}
/** Main entry point: builds a flow graph, then extracts a call graph and returns it. */
public CallGraphResult buildCallGraph(
Iterable<? extends Entrypoint> eps, IProgressMonitor monitor) throws CancelException {
long fgBegin, fgEnd, cgBegin, cgEnd;
if (LOG_TIMINGS) fgBegin = System.currentTimeMillis();
MonitorUtil.beginTask(monitor, "flow graph", 1);
FlowGraph flowGraph = buildFlowGraph(monitor);
MonitorUtil.done(monitor);
if (LOG_TIMINGS) {
fgEnd = System.currentTimeMillis();
System.out.println("flow graph construction took " + (fgEnd - fgBegin) / 1000.0 + " seconds");
cgBegin = System.currentTimeMillis();
}
MonitorUtil.beginTask(monitor, "extract call graph", 1);
JSCallGraph cg = extract(flowGraph, eps, monitor);
MonitorUtil.done(monitor);
if (LOG_TIMINGS) {
cgEnd = System.currentTimeMillis();
System.out.println("call graph extraction took " + (cgEnd - cgBegin) / 1000.0 + " seconds");
}
return new CallGraphResult(cg, flowGraph.getPointerAnalysis(cg, cache, monitor), flowGraph);
}
/** Extract a call graph from a given flow graph. */
public JSCallGraph extract(
FlowGraph flowgraph, Iterable<? extends Entrypoint> eps, IProgressMonitor monitor)
throws CancelException {
DelegatingSSAContextInterpreter interpreter =
new DelegatingSSAContextInterpreter(
new AstContextInsensitiveSSAContextInterpreter(options, cache),
new DefaultSSAInterpreter(options, cache));
return extract(interpreter, flowgraph, eps, monitor);
}
public JSCallGraph extract(
SSAContextInterpreter interpreter,
FlowGraph flowgraph,
Iterable<? extends Entrypoint> eps,
IProgressMonitor monitor)
throws CancelException {
// set up call graph
final JSCallGraph cg =
new JSCallGraph(JavaScriptLoader.JS.getFakeRootMethod(cha, options, cache), options, cache);
cg.init();
// setup context interpreters
if (options instanceof JSAnalysisOptions && ((JSAnalysisOptions) options).handleCallApply()) {
interpreter =
new DelegatingSSAContextInterpreter(
new JavaScriptFunctionApplyContextInterpreter(options, cache), interpreter);
}
cg.setInterpreter(interpreter);
// set up call edges from fake root to all script nodes
AbstractRootMethod fakeRootMethod = (AbstractRootMethod) cg.getFakeRootNode().getMethod();
CGNode fakeRootNode = cg.findOrCreateNode(fakeRootMethod, Everywhere.EVERYWHERE);
for (Entrypoint ep : eps) {
CGNode nd = cg.findOrCreateNode(ep.getMethod(), Everywhere.EVERYWHERE);
SSAAbstractInvokeInstruction invk = ep.addCall(fakeRootMethod);
fakeRootNode.addTarget(invk.getCallSite(), nd);
}
// register the fake root as the "true" entrypoint
cg.registerEntrypoint(fakeRootNode);
// now add genuine call edges
Set<Pair<CallVertex, FuncVertex>> edges = extractCallGraphEdges(flowgraph, monitor);
for (Pair<CallVertex, FuncVertex> edge : edges) {
CallVertex callVertex = edge.fst;
FuncVertex targetVertex = edge.snd;
IClass kaller = callVertex.getCaller().getConcreteType();
CGNode caller =
cg.findOrCreateNode(
kaller.getMethod(AstMethodReference.fnSelector), Everywhere.EVERYWHERE);
CallSiteReference site = callVertex.getSite();
IMethod target = targetSelector.getCalleeTarget(caller, site, targetVertex.getConcreteType());
boolean isFunctionPrototypeCall =
target != null
&& target
.getName()
.toString()
.startsWith(JavaScriptFunctionDotCallTargetSelector.SYNTHETIC_CALL_METHOD_PREFIX);
boolean isFunctionPrototypeApply =
target != null
&& target
.getName()
.toString()
.startsWith(JavaScriptFunctionApplyTargetSelector.SYNTHETIC_APPLY_METHOD_PREFIX);
if (isFunctionPrototypeCall || isFunctionPrototypeApply) {
handleFunctionCallOrApplyInvocation(
flowgraph, monitor, cg, callVertex, caller, site, target);
} else {
addEdgeToJSCallGraph(cg, site, target, caller);
if (target instanceof JavaScriptConstructor) {
IMethod fun =
((JavaScriptConstructor) target)
.constructedType()
.getMethod(AstMethodReference.fnSelector);
CGNode ctorCaller = cg.findOrCreateNode(target, Everywhere.EVERYWHERE);
CallSiteReference ref = null;
Iterator<CallSiteReference> sites = ctorCaller.iterateCallSites();
while (sites.hasNext()) {
CallSiteReference r = sites.next();
if (r.getDeclaredTarget().getSelector().equals(AstMethodReference.fnSelector)) {
ref = r;
break;
}
}
if (ref != null) {
addEdgeToJSCallGraph(cg, ref, fun, ctorCaller);
}
}
}
}
return cg;
}
public boolean handleFunctionCallOrApplyInvocation(
FlowGraph flowgraph,
IProgressMonitor monitor,
final JSCallGraph cg,
CallVertex callVertex,
CGNode caller,
CallSiteReference site,
IMethod target)
throws CancelException {
// use to get 1-level of call string for Function.prototype.call, to
// preserve the precision of the field-based call graph
final nCFAContextSelector functionPrototypeCallSelector =
new nCFAContextSelector(1, new ContextInsensitiveSelector());
Context calleeContext =
functionPrototypeCallSelector.getCalleeTarget(caller, site, target, null);
boolean ret = addCGEdgeWithContext(cg, site, target, caller, calleeContext);
CGNode functionPrototypeCallNode = cg.findOrCreateNode(target, calleeContext);
// need to create nodes for reflective targets of call, and then add them
// as callees of the synthetic method
OrdinalSet<FuncVertex> reflectiveTargets = getReflectiveTargets(flowgraph, callVertex, monitor);
// there should only be one call site in the synthetic method
// CallSiteReference reflectiveCallSite =
// cache.getIRFactory().makeIR(functionPrototypeCallNode.getMethod(), Everywhere.EVERYWHERE,
// options.getSSAOptions()).iterateCallSites().next();
CallSiteReference reflectiveCallSite =
functionPrototypeCallNode.getIR().iterateCallSites().next();
for (FuncVertex f : reflectiveTargets) {
IMethod reflectiveTgtMethod =
targetSelector.getCalleeTarget(
functionPrototypeCallNode, reflectiveCallSite, f.getConcreteType());
ret |=
addEdgeToJSCallGraph(
cg, reflectiveCallSite, reflectiveTgtMethod, functionPrototypeCallNode);
}
return ret;
}
public boolean addEdgeToJSCallGraph(
final JSCallGraph cg, CallSiteReference site, IMethod target, CGNode caller)
throws CancelException {
return addCGEdgeWithContext(cg, site, target, caller, Everywhere.EVERYWHERE);
}
Set<IClass> constructedTypes = HashSetFactory.make();
Everywhere targetContext = Everywhere.EVERYWHERE;
private static boolean addCGEdgeWithContext(
final JSCallGraph cg,
CallSiteReference site,
IMethod target,
CGNode caller,
Context targetContext)
throws CancelException {
boolean ret = false;
if (target != null) {
CGNode callee = cg.findOrCreateNode(target, targetContext);
// add nodes first, to be on the safe side
cg.addNode(caller);
cg.addNode(callee);
// add callee as successor of caller
ret = !cg.getPossibleTargets(caller, site).contains(callee);
if (ret) {
cg.addEdge(caller, callee);
caller.addTarget(site, callee);
}
}
return ret;
}
/**
* Given a callVertex that can invoke Function.prototype.call, get the FuncVertex nodes for the
* reflectively-invoked methods
*/
private static OrdinalSet<FuncVertex> getReflectiveTargets(
FlowGraph flowGraph, CallVertex callVertex, IProgressMonitor monitor) throws CancelException {
SSAAbstractInvokeInstruction invoke = callVertex.getInstruction();
VarVertex functionParam =
flowGraph.getVertexFactory().makeVarVertex(callVertex.getCaller(), invoke.getUse(1));
return flowGraph.getReachingSet(functionParam, monitor);
}
@SuppressWarnings("unused")
private static OrdinalSet<FuncVertex> getConstructorTargets(
FlowGraph flowGraph, CallVertex callVertex, IProgressMonitor monitor) throws CancelException {
SSAAbstractInvokeInstruction invoke = callVertex.getInstruction();
assert invoke.getDeclaredTarget().getName().equals(JavaScriptMethods.ctorAtom);
VarVertex objectParam =
flowGraph.getVertexFactory().makeVarVertex(callVertex.getCaller(), invoke.getUse(0));
return flowGraph.getReachingSet(objectParam, monitor);
}
/** Extract call edges from the flow graph into high-level representation. */
public Set<Pair<CallVertex, FuncVertex>> extractCallGraphEdges(
FlowGraph flowgraph, IProgressMonitor monitor) throws CancelException {
VertexFactory factory = flowgraph.getVertexFactory();
final Set<Pair<CallVertex, FuncVertex>> result = HashSetFactory.make();
// find all pairs <call, func> such that call is reachable from func in the flow graph
for (final CallVertex callVertex : factory.getCallVertices()) {
for (FuncVertex funcVertex : flowgraph.getReachingSet(callVertex, monitor)) {
result.add(Pair.make(callVertex, funcVertex));
}
}
return result;
}
}
| 15,690
| 40.510582
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/JSMethodInstructionVisitor.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.callgraph.fieldbased;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.js.ssa.JSAbstractInstructionVisitor;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SymbolTable;
/**
* A {@link JSAbstractInstructionVisitor} that is used to only visit instructions of a single
* method.
*
* @author mschaefer
*/
public class JSMethodInstructionVisitor extends JSAbstractInstructionVisitor {
protected final IMethod method;
protected final SymbolTable symtab;
protected final DefUse du;
public JSMethodInstructionVisitor(IMethod method, SymbolTable symtab, DefUse du) {
this.method = method;
this.symtab = symtab;
this.du = du;
}
/**
* Determine whether {@code invk} corresponds to a function declaration or function expression.
*
* <p>TODO: A bit hackish. Is there a more principled way to do this?
*/
protected boolean isFunctionConstructorInvoke(JavaScriptInvoke invk) {
/*
* Function objects are allocated by explicit constructor invocations like this:
*
* v8 = global:global Function
* v4 = construct v8@2 v6:#L<fullFunctionName> exception:<nd>
*/
if (invk.getDeclaredTarget().equals(JavaScriptMethods.ctorReference)) {
int fn = invk.getFunction();
SSAInstruction fndef = du.getDef(fn);
if (fndef instanceof AstGlobalRead) {
AstGlobalRead agr = (AstGlobalRead) fndef;
if (agr.getGlobalName().equals("global Function")) {
if (invk.getNumberOfPositionalParameters() != 2) {
return false;
}
// this may be a genuine use of "new Function()", not a declaration/expression
if (!symtab.isStringConstant(invk.getUse(1))
|| symtab.getStringValue(invk.getUse(1)).isEmpty()) {
return false;
}
return true;
}
}
}
return false;
}
}
| 2,472
| 32.876712
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/OptimisticCallgraphBuilder.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.callgraph.fieldbased;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.CallVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VarVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Set;
/**
* Optimistic call graph builder that propagates inter-procedural data flow iteratively as call
* edges are discovered. Slower, but potentially more sound than {@link
* PessimisticCallGraphBuilder}.
*
* @author mschaefer
*/
public class OptimisticCallgraphBuilder extends FieldBasedCallGraphBuilder {
/** The maximum number of iterations to perform. */
public int ITERATION_CUTOFF = Integer.MAX_VALUE;
private final boolean handleCallApply;
public OptimisticCallgraphBuilder(
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView iAnalysisCacheView,
boolean supportFullPointerAnalysis) {
super(cha, options, iAnalysisCacheView, supportFullPointerAnalysis);
handleCallApply =
options instanceof JSAnalysisOptions && ((JSAnalysisOptions) options).handleCallApply();
}
@Override
public FlowGraph buildFlowGraph(IProgressMonitor monitor) throws CancelException {
FlowGraph flowgraph = flowGraphFactory();
// keep track of which call edges we already know about
Set<Pair<CallVertex, FuncVertex>> knownEdges = HashSetFactory.make();
// flag for fixpoint iteration
boolean changed = true;
int iter = 0;
while (iter++ < ITERATION_CUTOFF && changed) {
MonitorUtil.throwExceptionIfCanceled(monitor);
changed = false;
// extract all call edges from the flow graph
Set<Pair<CallVertex, FuncVertex>> newEdges = this.extractCallGraphEdges(flowgraph, monitor);
for (Pair<CallVertex, FuncVertex> edge : newEdges) {
MonitorUtil.throwExceptionIfCanceled(monitor);
// set changed to true if this is a new edge
boolean newEdge = knownEdges.add(edge);
changed = changed || newEdge;
if (newEdge) {
// handle it
addEdge(flowgraph, edge.fst, edge.snd);
// special handling of invocations of Function.prototype.call
// TODO: since we've just added some edges to the flow graph, its transitive closure will
// be
// recomputed here, which is slow and unnecessary
if (handleCallApply
&& (edge.snd.getFullName().equals("Lprologue.js/Function_prototype_call")
|| edge.snd.getFullName().equals("Lprologue.js/Function_prototype_apply"))) {
addReflectiveCallEdge(flowgraph, edge.fst, monitor);
}
}
}
}
return flowgraph;
}
// add flow corresponding to a new call edge
private static void addEdge(FlowGraph flowgraph, CallVertex c, FuncVertex callee) {
VertexFactory factory = flowgraph.getVertexFactory();
JavaScriptInvoke invk = c.getInstruction();
FuncVertex caller = c.getCaller();
int offset = 0;
if (invk.getDeclaredTarget()
.getSelector()
.equals(JavaScriptMethods.ctorReference.getSelector())) {
offset = 1;
}
for (int i = 0; i < invk.getNumberOfPositionalParameters(); ++i) {
// only flow receiver into 'this' if invk is, in fact, a method call
flowgraph.addEdge(
factory.makeVarVertex(caller, invk.getUse(i)), factory.makeArgVertex(callee));
// if(i != 1 || !invk.getDeclaredTarget().getSelector().equals(AstMethodReference.fnSelector))
flowgraph.addEdge(
factory.makeVarVertex(caller, invk.getUse(i)),
factory.makeParamVertex(callee, i + offset));
}
// flow from return vertex to result vertex
flowgraph.addEdge(factory.makeRetVertex(callee), factory.makeVarVertex(caller, invk.getDef()));
}
// add data flow corresponding to a reflective invocation via Function.prototype.call
// NB: for f.call(...), f will _not_ appear as a call target, but the appropriate argument and
// return data flow will be set up
private static void addReflectiveCallEdge(
FlowGraph flowgraph, CallVertex c, IProgressMonitor monitor) throws CancelException {
VertexFactory factory = flowgraph.getVertexFactory();
FuncVertex caller = c.getCaller();
JavaScriptInvoke invk = c.getInstruction();
VarVertex receiverVertex = factory.makeVarVertex(caller, invk.getUse(1));
OrdinalSet<FuncVertex> realCallees = flowgraph.getReachingSet(receiverVertex, monitor);
System.err.println("callees " + realCallees + " for " + caller);
for (FuncVertex realCallee : realCallees) {
// flow from arguments to parameters
for (int i = 2; i < invk.getNumberOfPositionalParameters(); ++i)
flowgraph.addEdge(
factory.makeVarVertex(caller, invk.getUse(i)),
factory.makeParamVertex(realCallee, i - 1));
// flow from return vertex to result vertex
flowgraph.addEdge(
factory.makeRetVertex(realCallee), factory.makeVarVertex(caller, invk.getDef()));
}
}
}
| 6,187
| 39.710526
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/PessimisticCallGraphBuilder.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.callgraph.fieldbased;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod;
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.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.Iterator2Iterable;
/**
* Call graph builder for building pessimistic call graphs, where inter-procedural flows are not
* tracked except in the trivial case of local calls. This builder is fast, but in general less
* sound than {@link OptimisticCallgraphBuilder}.
*
* @author mschaefer
*/
public class PessimisticCallGraphBuilder extends FieldBasedCallGraphBuilder {
public PessimisticCallGraphBuilder(
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView iAnalysisCacheView,
boolean supportFullPointerAnalysis) {
super(cha, options, iAnalysisCacheView, supportFullPointerAnalysis);
}
@Override
public FlowGraph buildFlowGraph(IProgressMonitor monitor) {
FlowGraph flowgraph = flowGraphFactory();
resolveLocalCalls(flowgraph);
return flowgraph;
}
protected boolean filterFunction(IMethod function) {
return function.getDescriptor().equals(AstMethodReference.fnDesc);
}
// add inter-procedural flow for local calls
private void resolveLocalCalls(FlowGraph flowgraph) {
for (IClass klass : cha) {
for (IMethod method : klass.getDeclaredMethods()) {
if (filterFunction(method)) {
IR ir = cache.getIR(method);
ir.visitAllInstructions(
new LocalCallSSAVisitor(method, ir.getSymbolTable(), cache.getDefUse(ir), flowgraph));
}
}
}
}
/**
* This visitor looks for calls where the callee can be determined locally by a def-use graph, and
* adds inter-procedural edges.
*
* @author mschaefer
*/
private class LocalCallSSAVisitor extends JSMethodInstructionVisitor {
private final FlowGraph flowgraph;
private final VertexFactory factory;
private final FuncVertex caller;
public LocalCallSSAVisitor(IMethod method, SymbolTable symtab, DefUse du, FlowGraph flowgraph) {
super(method, symtab, du);
this.flowgraph = flowgraph;
this.factory = flowgraph.getVertexFactory();
this.caller = this.factory.makeFuncVertex(method.getDeclaringClass());
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke invk) {
// check whether this instruction corresponds to a function expression/declaration
if (isFunctionConstructorInvoke(invk)) {
int defn = invk.getDef();
// the name of the function
String fnName = symtab.getStringValue(invk.getUse(1));
IClass fnClass =
cha.lookupClass(TypeReference.findOrCreate(JavaScriptTypes.jsLoader, fnName));
if (fnClass == null) {
System.err.println(
"cannot find " + fnName + " at " + ((AstMethod) method).getSourcePosition());
return;
}
IMethod fn = fnClass.getMethod(AstMethodReference.fnSelector);
FuncVertex callee = factory.makeFuncVertex(fnClass);
// look at all uses
for (SSAInstruction use : Iterator2Iterable.make(du.getUses(defn))) {
// check whether this is a local call
if (use instanceof JavaScriptInvoke && ((JavaScriptInvoke) use).getFunction() == defn) {
JavaScriptInvoke use_invk = (JavaScriptInvoke) use;
// yes, so add edges from arguments to parameters...
for (int i = 2; i < use_invk.getNumberOfPositionalParameters(); ++i)
flowgraph.addEdge(
factory.makeVarVertex(caller, use_invk.getUse(i)),
factory.makeParamVertex(callee, i));
// ...and from return to result
flowgraph.addEdge(
factory.makeRetVertex(callee), factory.makeVarVertex(caller, use.getDef()));
// note: local calls are never qualified, so there is no flow into the receiver vertex
} else {
// no, it's a more complicated use, so add flows from/to unknown
for (int i = 1; i < fn.getNumberOfParameters(); ++i)
flowgraph.addEdge(factory.makeUnknownVertex(), factory.makeParamVertex(callee, i));
flowgraph.addEdge(factory.makeRetVertex(callee), factory.makeUnknownVertex());
}
}
} else {
// this is a genuine function call; find out where the function came from
SSAInstruction def = du.getDef(invk.getFunction());
// if it's not a local call, add flows from/to unknown
if (!(def instanceof JavaScriptInvoke)
|| !isFunctionConstructorInvoke((JavaScriptInvoke) def)) {
for (int i = 1; i < invk.getNumberOfPositionalParameters(); ++i)
flowgraph.addEdge(
factory.makeVarVertex(caller, invk.getUse(i)), factory.makeUnknownVertex());
flowgraph.addEdge(
factory.makeUnknownVertex(), factory.makeVarVertex(caller, invk.getDef()));
}
}
}
}
}
| 6,134
| 39.629139
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/WorklistBasedOptimisticCallgraphBuilder.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.callgraph.fieldbased;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraphBuilder;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.CallVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VarVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.Vertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.collections.Pair;
import java.util.Map;
import java.util.Set;
/**
* Optimistic call graph builder that propagates inter-procedural data flow iteratively as call
* edges are discovered. Slower, but potentially more sound than {@link
* PessimisticCallGraphBuilder}.
*
* <p>This variant uses a worklist algorithm, generally making it scale better than {@link
* OptimisticCallgraphBuilder}, which repeatedly runs the pessimistic algorithm.
*
* @author mschaefer
*/
public class WorklistBasedOptimisticCallgraphBuilder extends FieldBasedCallGraphBuilder {
/** The maximum number of iterations to perform. */
public int ITERATION_CUTOFF = Integer.MAX_VALUE;
private final boolean handleCallApply;
private FlowGraphBuilder builder;
private final int bound;
public WorklistBasedOptimisticCallgraphBuilder(
IClassHierarchy cha,
AnalysisOptions options,
IAnalysisCacheView cache,
boolean supportFullPointerAnalysis,
int bound) {
super(cha, options, cache, supportFullPointerAnalysis);
handleCallApply =
options instanceof JSAnalysisOptions && ((JSAnalysisOptions) options).handleCallApply();
this.bound = bound;
}
@Override
public FlowGraph buildFlowGraph(IProgressMonitor monitor) throws CancelException {
builder = new FlowGraphBuilder(cha, cache, false);
return builder.buildFlowGraph();
}
@Override
public Set<Pair<CallVertex, FuncVertex>> extractCallGraphEdges(
FlowGraph flowgraph, IProgressMonitor monitor) throws CancelException {
VertexFactory factory = flowgraph.getVertexFactory();
Set<Vertex> worklist = HashSetFactory.make();
Map<Vertex, Set<FuncVertex>> reachingFunctions = HashMapFactory.make();
Map<VarVertex, Pair<JavaScriptInvoke, Boolean>> reflectiveCalleeVertices =
HashMapFactory.make();
/* maps to maintain the list of reachable calls that are yet to be processed * */
Map<Vertex, Set<FuncVertex>> pendingCallWorklist = HashMapFactory.make();
Map<Vertex, Set<FuncVertex>> pendingReflectiveCallWorklist = HashMapFactory.make();
for (Vertex v : flowgraph) {
if (v instanceof FuncVertex) {
FuncVertex fv = (FuncVertex) v;
worklist.add(fv);
MapUtil.findOrCreateSet(reachingFunctions, fv).add(fv);
}
}
int cnt = 0;
/*
* if bound is missing, calledges are added until all worklists are empty else, the calledges
* are added until the bound value is hit *
*/
while ((bound == -1
&& (!worklist.isEmpty()
|| !pendingCallWorklist.isEmpty()
|| !pendingReflectiveCallWorklist.isEmpty()))
|| cnt < bound) {
if (worklist.isEmpty()) {
processPendingCallWorklist(
flowgraph,
pendingCallWorklist,
factory,
reachingFunctions,
reflectiveCalleeVertices,
worklist);
processPendingReflectiveCallWorklist(
flowgraph, pendingReflectiveCallWorklist, reflectiveCalleeVertices, worklist);
pendingCallWorklist.clear();
pendingReflectiveCallWorklist.clear();
}
while (!worklist.isEmpty()) {
MonitorUtil.throwExceptionIfCanceled(monitor);
Vertex v = worklist.iterator().next();
worklist.remove(v);
Set<FuncVertex> vReach = MapUtil.findOrCreateSet(reachingFunctions, v);
for (Vertex w : Iterator2Iterable.make(flowgraph.getSucc(v))) {
MonitorUtil.throwExceptionIfCanceled(monitor);
Set<FuncVertex> wReach = MapUtil.findOrCreateSet(reachingFunctions, w);
boolean changed = false;
if (w instanceof CallVertex) {
for (FuncVertex fv : vReach) {
if (wReach.add(fv)) {
changed = true;
MapUtil.findOrCreateSet(pendingCallWorklist, w).add(fv);
}
}
} else if (handleCallApply && reflectiveCalleeVertices.containsKey(w)) {
for (FuncVertex fv : vReach) {
if (wReach.add(fv)) {
changed = true;
MapUtil.findOrCreateSet(pendingReflectiveCallWorklist, (VarVertex) w).add(fv);
}
}
} else {
changed = wReach.addAll(vReach);
}
if (changed) worklist.add(w);
}
}
cnt += 1;
}
Set<Pair<CallVertex, FuncVertex>> res = HashSetFactory.make();
for (Map.Entry<Vertex, Set<FuncVertex>> entry : reachingFunctions.entrySet()) {
final Vertex v = entry.getKey();
if (v instanceof CallVertex)
for (FuncVertex fv : entry.getValue()) res.add(Pair.make((CallVertex) v, fv));
}
return res;
}
public void processPendingCallWorklist(
FlowGraph flowgraph,
Map<Vertex, Set<FuncVertex>> pendingCallWorklist,
VertexFactory factory,
Map<Vertex, Set<FuncVertex>> reachingFunctions,
Map<VarVertex, Pair<JavaScriptInvoke, Boolean>> reflectiveCalleeVertices,
Set<Vertex> worklist) {
for (Map.Entry<Vertex, Set<FuncVertex>> entry : pendingCallWorklist.entrySet()) {
CallVertex callVertex = (CallVertex) entry.getKey();
for (FuncVertex fv : entry.getValue()) {
addCallEdge(flowgraph, callVertex, fv, worklist);
String fullName = fv.getFullName();
if (handleCallApply
&& (fullName.equals("Lprologue.js/Function_prototype_call")
|| fullName.equals("Lprologue.js/Function_prototype_apply"))) {
JavaScriptInvoke invk = callVertex.getInstruction();
VarVertex reflectiveCalleeVertex =
factory.makeVarVertex(callVertex.getCaller(), invk.getUse(1));
flowgraph.addEdge(
reflectiveCalleeVertex,
factory.makeReflectiveCallVertex(callVertex.getCaller(), invk));
// we only add dataflow edges for Function.prototype.call
boolean isCall = fullName.equals("Lprologue.js/Function_prototype_call");
reflectiveCalleeVertices.put(reflectiveCalleeVertex, Pair.make(invk, isCall));
for (FuncVertex fw : MapUtil.findOrCreateSet(reachingFunctions, reflectiveCalleeVertex))
addReflectiveCallEdge(flowgraph, reflectiveCalleeVertex, invk, fw, worklist, isCall);
}
}
}
}
public void processPendingReflectiveCallWorklist(
FlowGraph flowgraph,
Map<Vertex, Set<FuncVertex>> pendingReflectiveCallWorklist,
Map<VarVertex, Pair<JavaScriptInvoke, Boolean>> reflectiveCalleeVertices,
Set<Vertex> worklist) {
for (Map.Entry<Vertex, Set<FuncVertex>> entry : pendingReflectiveCallWorklist.entrySet()) {
final Vertex v = entry.getKey();
Pair<JavaScriptInvoke, Boolean> invkAndIsCall = reflectiveCalleeVertices.get(v);
for (FuncVertex fv : entry.getValue()) {
addReflectiveCallEdge(
flowgraph, (VarVertex) v, invkAndIsCall.fst, fv, worklist, invkAndIsCall.snd);
}
}
}
// add flow corresponding to a new call edge
private void addCallEdge(
FlowGraph flowgraph, CallVertex c, FuncVertex callee, Set<Vertex> worklist) {
VertexFactory factory = flowgraph.getVertexFactory();
FuncVertex caller = c.getCaller();
JavaScriptInvoke invk = c.getInstruction();
int offset = 0;
if (invk.getDeclaredTarget()
.getSelector()
.equals(JavaScriptMethods.ctorReference.getSelector())) {
offset = 1;
}
for (int i = 0; i < invk.getNumberOfPositionalParameters(); ++i) {
// only flow receiver into 'this' if invk is, in fact, a method call
flowgraph.addEdge(
factory.makeVarVertex(caller, invk.getUse(i)), factory.makeArgVertex(callee));
if (i != 1 || !invk.getDeclaredTarget().getSelector().equals(AstMethodReference.fnSelector))
addFlowEdge(
flowgraph,
factory.makeVarVertex(caller, invk.getUse(i)),
factory.makeParamVertex(callee, i + offset),
worklist);
}
// flow from return vertex to result vertex
addFlowEdge(
flowgraph,
factory.makeRetVertex(callee),
factory.makeVarVertex(caller, invk.getDef()),
worklist);
}
public void addFlowEdge(FlowGraph flowgraph, Vertex from, Vertex to, Set<Vertex> worklist) {
flowgraph.addEdge(from, to);
worklist.add(from);
}
// add data flow corresponding to a reflective invocation via Function.prototype.call
// NB: for f.call(...), f will _not_ appear as a call target, but the appropriate argument and
// return data flow will be set up
private void addReflectiveCallEdge(
FlowGraph flowgraph,
VarVertex reflectiveCallee,
JavaScriptInvoke invk,
FuncVertex realCallee,
Set<Vertex> worklist,
boolean isFunctionPrototypeCall) {
VertexFactory factory = flowgraph.getVertexFactory();
FuncVertex caller = reflectiveCallee.getFunction();
if (isFunctionPrototypeCall) {
// flow from arguments to parameters
for (int i = 2; i < invk.getNumberOfPositionalParameters(); ++i) {
addFlowEdge(
flowgraph,
factory.makeVarVertex(caller, invk.getUse(i)),
factory.makeParamVertex(realCallee, i - 1),
worklist);
}
}
// flow from return vertex to result vertex
addFlowEdge(
flowgraph,
factory.makeRetVertex(realCallee),
factory.makeVarVertex(caller, invk.getDef()),
worklist);
}
}
| 11,149
| 39.107914
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/FilteredFlowGraphBuilder.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.callgraph.fieldbased.flowgraph;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import java.util.function.Function;
public class FilteredFlowGraphBuilder extends FlowGraphBuilder {
private final Function<IMethod, Boolean> filter;
public FilteredFlowGraphBuilder(
IClassHierarchy cha,
IAnalysisCacheView cache,
boolean fullPointerAnalysis,
Function<IMethod, Boolean> filter) {
super(cha, cache, fullPointerAnalysis);
this.filter = filter;
}
@Override
public void visitFunction(FlowGraph flowgraph, IMethod method) {
if (filter.apply(method)) {
super.visitFunction(flowgraph, method);
}
}
}
| 1,149
| 28.487179
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/FlowGraph.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.callgraph.fieldbased.flowgraph;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ibm.wala.analysis.pointers.HeapGraph;
import com.ibm.wala.cast.ipa.callgraph.AstHeapModel;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.ir.ssa.AstPropertyWrite;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.AbstractVertexVisitor;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.CreationSiteVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.ObjectVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.PropVertex;
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.callgraph.fieldbased.flowgraph.vertices.UnknownVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VarVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.Vertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.ssa.JavaScriptPropertyWrite;
import com.ibm.wala.cast.js.ssa.SetPrototype;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.ProgramCounter;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
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.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey.TypeFilter;
import com.ibm.wala.ipa.callgraph.propagation.HeapModel;
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.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.CompoundIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.GraphReachability;
import com.ibm.wala.util.graph.GraphSlicer;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.graph.impl.ExtensionGraph;
import com.ibm.wala.util.graph.impl.InvertedGraph;
import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph;
import com.ibm.wala.util.graph.traverse.DFS;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A flow graph models data flow between vertices representing local variables, properties, return
* values, and so forth.
*
* @author mschaefer
*/
public class FlowGraph implements Iterable<Vertex> {
// the actual flow graph representation
private final NumberedGraph<Vertex> graph;
// a factory that allows us to build canonical vertices
private final VertexFactory factory;
// the transitive closure of the inverse of this.graph,
// but without paths going through the Unknown vertex
private GraphReachability<Vertex, FuncVertex> optimistic_closure;
public FlowGraph() {
this.graph = new SlowSparseNumberedGraph<>(1);
this.factory = new VertexFactory();
}
// (re-)compute optimistic_closure
private void compute_optimistic_closure(IProgressMonitor monitor) throws CancelException {
if (optimistic_closure != null) return;
optimistic_closure = computeClosure(graph, monitor, FuncVertex.class);
}
private static <T> GraphReachability<Vertex, T> computeClosure(
NumberedGraph<Vertex> graph, IProgressMonitor monitor, final Class<?> type)
throws CancelException {
// prune flowgraph by taking out 'unknown' vertex
Graph<Vertex> pruned_flowgraph =
GraphSlicer.prune(
graph,
t ->
t.accept(
new AbstractVertexVisitor<>() {
@Override
public Boolean visitVertex() {
return true;
}
@Override
public Boolean visitUnknownVertex(UnknownVertex unknownVertex) {
return false;
}
}));
// compute transitive closure
GraphReachability<Vertex, T> optimistic_closure =
new GraphReachability<>(new InvertedGraph<>(pruned_flowgraph), type::isInstance);
optimistic_closure.solve(monitor);
return optimistic_closure;
}
public VertexFactory getVertexFactory() {
return factory;
}
/**
* Adds an edge from vertex {@code from} to vertex {@code to}, adding the vertices to the graph if
* they are not in there yet.
*/
public void addEdge(Vertex from, Vertex to) {
if (!graph.containsNode(from)) graph.addNode(from);
if (!graph.containsNode(to)) graph.addNode(to);
if (!graph.hasEdge(from, to)) {
optimistic_closure = null;
graph.addEdge(from, to);
}
}
/**
* Computes the set of vertices that may reach {@code dest} along paths not containing an {@link
* UnknownVertex}.
*/
public OrdinalSet<FuncVertex> getReachingSet(Vertex dest, IProgressMonitor monitor)
throws CancelException {
if (!graph.containsNode(dest)) return OrdinalSet.empty();
compute_optimistic_closure(monitor);
return optimistic_closure.getReachableSet(dest);
}
public Iterator<Vertex> getSucc(Vertex v) {
return graph.getSuccNodes(v);
}
@Override
public Iterator<Vertex> iterator() {
return graph.iterator();
}
public PointerAnalysis<ObjectVertex> getPointerAnalysis(
final CallGraph cg, final IAnalysisCacheView cache, final IProgressMonitor monitor)
throws CancelException {
return new PointerAnalysis<>() {
private final Map<Pair<PrototypeField, ObjectVertex>, PrototypeFieldVertex> proto =
HashMapFactory.make();
private GraphReachability<Vertex, ObjectVertex> pointerAnalysis =
computeClosure(graph, monitor, ObjectVertex.class);
private final ExtensionGraph<Vertex> dataflow = new ExtensionGraph<>(graph);
private IR getIR(final IAnalysisCacheView cache, FuncVertex func) {
return cache.getIR(func.getConcreteType().getMethod(AstMethodReference.fnSelector));
}
private PointerKey propertyKey(String property, ObjectVertex o) {
if ("__proto__".equals(property) || "prototype".equals(property)) {
return get(PrototypeField.valueOf(property), o);
} else {
return factory.makePropVertex(property);
}
}
{
PropVertex proto = factory.makePropVertex("prototype");
if (graph.containsNode(proto)) {
for (Vertex p : Iterator2Iterable.make(graph.getPredNodes(proto))) {
if (p instanceof VarVertex) {
int rval = ((VarVertex) p).getValueNumber();
FuncVertex func = ((VarVertex) p).getFunction();
DefUse du = cache.getDefUse(getIR(cache, func));
for (SSAInstruction inst : Iterator2Iterable.make(du.getUses(rval))) {
if (inst instanceof JavaScriptPropertyWrite) {
int obj = ((AstPropertyWrite) inst).getObjectRef();
VarVertex object = factory.makeVarVertex(func, obj);
for (ObjectVertex o : getPointsToSet(object)) {
PrototypeFieldVertex prototype = get(PrototypeField.prototype, o);
if (!dataflow.containsNode(prototype)) {
dataflow.addNode(prototype);
}
dataflow.addEdge(p, prototype);
}
}
}
}
}
}
pointerAnalysis = computeClosure(dataflow, monitor, ObjectVertex.class);
}
private PrototypeFieldVertex get(PrototypeField f, ObjectVertex o) {
Pair<PrototypeField, ObjectVertex> key = Pair.make(f, o);
if (!proto.containsKey(key)) {
proto.put(key, new PrototypeFieldVertex(f, o));
}
return proto.get(key);
}
private FuncVertex getVertex(CGNode n) {
IMethod m = n.getMethod();
if (m.getSelector().equals(AstMethodReference.fnSelector)) {
IClass fun = m.getDeclaringClass();
return factory.makeFuncVertex(fun);
} else {
return null;
}
}
@Override
public OrdinalSet<ObjectVertex> getPointsToSet(PointerKey key) {
if (dataflow.containsNode((Vertex) key)) {
return pointerAnalysis.getReachableSet(key);
} else {
return OrdinalSet.empty();
}
}
@Override
public Collection<ObjectVertex> getInstanceKeys() {
Set<ObjectVertex> result = HashSetFactory.make();
for (CreationSiteVertex cs : factory.creationSites()) {
if (cg.getNode(cs.getMethod(), Everywhere.EVERYWHERE) != null) {
result.add(cs);
}
}
result.addAll(factory.getFuncVertices());
result.add(factory.global());
return result;
}
@Override
public boolean isFiltered(PointerKey pk) {
return false;
}
@Override
public OrdinalSetMapping<ObjectVertex> getInstanceKeyMapping() {
assert false;
return null;
}
@Override
public Iterable<PointerKey> getPointerKeys() {
return () ->
new CompoundIterator<>(
factory.getArgVertices().iterator(),
new CompoundIterator<>(
factory.getRetVertices().iterator(),
new CompoundIterator<PointerKey>(
factory.getVarVertices().iterator(),
factory.getPropVertices().iterator())));
}
@Override
public HeapModel getHeapModel() {
return new AstHeapModel() {
@Override
public PointerKey getPointerKeyForLocal(CGNode node, int valueNumber) {
FuncVertex function = getVertex(node);
if (function != null) {
return factory.makeVarVertex(function, valueNumber);
} else {
assert false;
return null;
}
}
@Override
public PointerKey getPointerKeyForReturnValue(CGNode node) {
FuncVertex function = getVertex(node);
if (function != null) {
return factory.makeRetVertex(function);
} else {
assert false;
return null;
}
}
@Override
public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField field) {
String f = field.getName().toString();
if ("__proto__".equals(f) || "prototype".equals(f)) {
return get(PrototypeField.valueOf(f), (ObjectVertex) I);
} else {
return factory.makePropVertex(f);
}
}
@Override
public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) {
// TODO Auto-generated method stub
return null;
}
@Override
public InstanceKey getInstanceKeyForMultiNewArray(
CGNode node, NewSiteReference allocation, int dim) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) {
// TODO Auto-generated method stub
return null;
}
@Override
public InstanceKey getInstanceKeyForPEI(
CGNode node, ProgramCounter instr, TypeReference type) {
// TODO Auto-generated method stub
return null;
}
@Override
public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) {
// TODO Auto-generated method stub
return null;
}
@Override
public FilteredPointerKey getFilteredPointerKeyForLocal(
CGNode node, int valueNumber, TypeFilter filter) {
// TODO Auto-generated method stub
return null;
}
@Override
public PointerKey getPointerKeyForExceptionalReturnValue(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public PointerKey getPointerKeyForStaticField(IField f) {
// TODO Auto-generated method stub
return null;
}
@Override
public PointerKey getPointerKeyForArrayContents(InstanceKey I) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator<PointerKey> iteratePointerKeys() {
// TODO Auto-generated method stub
return null;
}
@Override
public IClassHierarchy getClassHierarchy() {
assert false;
return null;
}
@Override
public PointerKey getPointerKeyForArrayLength(InstanceKey I) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator<PointerKey> getPointerKeysForReflectedFieldRead(
InstanceKey I, InstanceKey F) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator<PointerKey> getPointerKeysForReflectedFieldWrite(
InstanceKey I, InstanceKey F) {
// TODO Auto-generated method stub
return null;
}
@Override
public PointerKey getPointerKeyForObjectCatalog(InstanceKey I) {
// TODO Auto-generated method stub
return null;
}
};
}
private HeapGraph<ObjectVertex> heapGraph;
@Override
public HeapGraph<ObjectVertex> getHeapGraph() {
if (heapGraph == null) {
final PointerAnalysis<ObjectVertex> pa = this;
class FieldBasedHeapGraph extends SlowSparseNumberedGraph<Object>
implements HeapGraph<ObjectVertex> {
private static final long serialVersionUID = -3544629644808422215L;
private <X> X ensureNode(X n) {
if (!containsNode(n)) {
addNode(n);
}
return n;
}
private PropVertex getCoreProto(TypeReference coreType) {
if (coreType.equals(JavaScriptTypes.Object)) {
return factory.makePropVertex("Object$proto$__WALA__");
} else if (coreType.equals(JavaScriptTypes.Function)) {
return factory.makePropVertex("Function$proto$__WALA__");
} else if (coreType.equals(JavaScriptTypes.Number)
|| coreType.equals(JavaScriptTypes.NumberObject)) {
return factory.makePropVertex("Number$proto$__WALA__");
} else if (coreType.equals(JavaScriptTypes.Array)) {
return factory.makePropVertex("Array$proto$__WALA__");
} else if (coreType.equals(JavaScriptTypes.String)
|| coreType.equals(JavaScriptTypes.StringObject)) {
return factory.makePropVertex("String$proto$__WALA__");
} else if (coreType.equals(JavaScriptTypes.Date)) {
return factory.makePropVertex("Date$proto$__WALA__");
} else if (coreType.equals(JavaScriptTypes.RegExp)
|| coreType.equals(JavaScriptTypes.RegExpObject)) {
return factory.makePropVertex("RegExp$proto$__WALA__");
} else {
return null;
}
}
{
for (PropVertex property : factory.getPropVertices()) {
// edges from objects to properties assigned to them
for (Vertex p : Iterator2Iterable.make(dataflow.getPredNodes(property))) {
if (p instanceof VarVertex) {
int rval = ((VarVertex) p).getValueNumber();
FuncVertex func = ((VarVertex) p).getFunction();
DefUse du = cache.getDefUse(getIR(cache, func));
for (SSAInstruction inst : Iterator2Iterable.make(du.getUses(rval))) {
if (inst instanceof JavaScriptPropertyWrite) {
int obj = ((AstPropertyWrite) inst).getObjectRef();
VarVertex object = factory.makeVarVertex(func, obj);
for (ObjectVertex o : getPointsToSet(object)) {
addEdge(
ensureNode(o), ensureNode(propertyKey(property.getPropName(), o)));
for (ObjectVertex v : getPointsToSet(property)) {
addEdge(
ensureNode(propertyKey(property.getPropName(), o)), ensureNode(v));
}
}
} else if (inst instanceof AstGlobalWrite) {
addEdge(ensureNode(factory.global()), ensureNode(property));
for (ObjectVertex v : getPointsToSet(property)) {
addEdge(ensureNode(property), ensureNode(v));
}
} else if (inst instanceof SetPrototype) {
int obj = inst.getUse(0);
for (ObjectVertex o : getPointsToSet(factory.makeVarVertex(func, obj))) {
for (ObjectVertex v : getPointsToSet(property)) {
addEdge(ensureNode(o), ensureNode(get(PrototypeField.prototype, o)));
addEdge(ensureNode(get(PrototypeField.prototype, o)), ensureNode(v));
}
}
} else {
System.err.println("ignoring " + inst);
}
}
}
}
}
// prototype dataflow for function creations
for (FuncVertex f : factory.getFuncVertices()) {
ensureNode(get(PrototypeField.__proto__, f));
addEdge(
ensureNode(getCoreProto(JavaScriptTypes.Function)),
ensureNode(get(PrototypeField.prototype, f)));
}
// prototype dataflow for object creations
for (CreationSiteVertex cs : factory.creationSites()) {
if (cg.getNode(cs.getMethod(), Everywhere.EVERYWHERE) != null) {
for (Pair<CGNode, NewSiteReference> site :
Iterator2Iterable.make(cs.getCreationSites(cg))) {
IR ir = site.fst.getIR();
SSAInstruction creation = ir.getInstructions()[site.snd.getProgramCounter()];
if (creation instanceof JavaScriptInvoke) {
for (ObjectVertex f :
getPointsToSet(
factory.makeVarVertex(getVertex(site.fst), creation.getUse(0)))) {
for (ObjectVertex o :
getPointsToSet(
factory.makeVarVertex(getVertex(site.fst), creation.getDef(0)))) {
addEdge(
ensureNode(get(PrototypeField.prototype, f)),
ensureNode(get(PrototypeField.__proto__, o)));
}
}
} else if (creation instanceof SSANewInstruction) {
PointerKey proto =
getCoreProto(((SSANewInstruction) creation).getConcreteType());
if (proto != null) {
for (ObjectVertex f : getPointsToSet(proto)) {
for (ObjectVertex o :
getPointsToSet(
factory.makeVarVertex(getVertex(site.fst), creation.getDef(0)))) {
addEdge(ensureNode(get(PrototypeField.__proto__, o)), ensureNode(f));
}
}
}
}
}
}
}
}
@Override
public Collection<Object> getReachableInstances(Set<Object> roots) {
return DFS.getReachableNodes(this, roots, ObjectVertex.class::isInstance);
}
@Override
public HeapModel getHeapModel() {
return pa.getHeapModel();
}
@Override
public PointerAnalysis<ObjectVertex> getPointerAnalysis() {
return pa;
}
}
heapGraph = new FieldBasedHeapGraph();
}
return heapGraph;
}
@Override
public IClassHierarchy getClassHierarchy() {
assert false;
return null;
}
};
}
/**
* Converts flow graph to a JSON representation. Keys of the JSON object are vertices, with each
* vertex mapped to its successors. Vertices are serialized using their {@link
* Vertex#toSourceLevelString(IAnalysisCacheView)} method to include information about
* source-level variables whenever possible.
*/
public String toJSON() {
IAnalysisCacheView cache = new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory());
Map<String, Set<String>> edges = HashMapFactory.make();
for (Vertex node : graph) {
String nodeStr = node.toSourceLevelString(cache);
Set<String> succs = MapUtil.findOrCreateSet(edges, nodeStr);
for (Vertex succ : Iterator2Iterable.make(graph.getSuccNodes(node))) {
succs.add(succ.toSourceLevelString(cache));
}
}
// filter out empty entries
Map<String, Set<String>> filtered = HashMapFactory.make();
for (Map.Entry<String, Set<String>> entry : edges.entrySet()) {
if (!entry.getValue().isEmpty()) {
filtered.put(entry.getKey(), entry.getValue());
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(filtered);
}
}
| 23,872
| 37.75487
| 104
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/FlowGraphBuilder.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.callgraph.fieldbased.flowgraph;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
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.js.callgraph.fieldbased.JSMethodInstructionVisitor;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.CreationSiteVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VarVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.Vertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.cast.js.ssa.SetPrototype;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.js.util.Util;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.AstMethod.LexicalInformation;
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.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
/**
* Class for building intra-procedural flow graphs for a given class hierarchy.
*
* @author mschaefer
*/
public class FlowGraphBuilder {
private final IClassHierarchy cha;
private final IAnalysisCacheView cache;
private final boolean supportFullPointerAnalysis;
public FlowGraphBuilder(
IClassHierarchy cha, IAnalysisCacheView cache, boolean supportPointerAnalysis) {
this.cha = cha;
this.cache = cache;
this.supportFullPointerAnalysis = supportPointerAnalysis;
}
/**
* This is the main entry point of the flow graph builder.
*
* <p>It creates a new, empty flow graph, adds nodes for a small number of special primitive
* functions such as {@code Object} and {@code Function} and sets up flow edges to make them flow
* into the corresponding global variables. Then it iterates over all functions in the class
* hierarchy and all their IR instructions, and adds the flow edges induced by these instructions.
*
* @return the completed flow graph
*/
public FlowGraph buildFlowGraph() {
FlowGraph flowgraph = new FlowGraph();
addPrimitives(flowgraph);
visitProgram(flowgraph);
return flowgraph;
}
public void visitProgram(FlowGraph flowgraph) {
for (IClass klass : cha) {
for (IMethod method : klass.getDeclaredMethods()) {
if (method.getDescriptor().equals(AstMethodReference.fnDesc)) {
visitFunction(flowgraph, method);
}
}
}
}
public void visitFunction(FlowGraph flowgraph, IMethod method) {
{
IR ir = cache.getIR(method);
FlowGraphSSAVisitor visitor = new FlowGraphSSAVisitor(ir, flowgraph);
// first visit normal instructions
SSAInstruction[] normalInstructions = ir.getInstructions();
for (int i = 0; i < normalInstructions.length; ++i)
if (normalInstructions[i] != null) {
visitor.instructionIndex = i;
normalInstructions[i].visit(visitor);
}
// now visit phis and catches
visitor.instructionIndex = -1;
for (SSAInstruction inst : Iterator2Iterable.make(ir.iteratePhis())) inst.visit(visitor);
for (SSAInstruction inst : Iterator2Iterable.make(ir.iterateCatchInstructions()))
inst.visit(visitor);
}
}
// primitive functions that are treated specially
private static final String[] primitiveFunctions = {
"Object", "Function", "Array", "StringObject", "NumberObject", "BooleanObject", "RegExp"
};
/**
* Add flows from the special primitive functions to the corresponding global variables.
*
* @param flowgraph the flow graph under construction
*/
private void addPrimitives(FlowGraph flowgraph) {
VertexFactory factory = flowgraph.getVertexFactory();
for (String pf : primitiveFunctions) {
TypeReference typeref = TypeReference.findOrCreate(JavaScriptTypes.jsLoader, 'L' + pf);
IClass klass = cha.lookupClass(typeref);
String prop = pf.endsWith("Object") ? pf.substring(0, pf.length() - 6) : pf;
flowgraph.addEdge(factory.makeFuncVertex(klass), factory.makePropVertex(prop));
}
}
/**
* Visitor class that does the heavy lifting (such as it is) of flow graph construction, adding
* flow graph edges for every instruction in the method IR.
*
* <p>The only slightly tricky thing are assignments to exposed variables inside their defining
* function. In the IR, they initially appear as normal SSA variable assignments, without any
* indication of their lexical nature. The normal call graph construction logic does something
* convoluted to fix this up later when an actual lexical access is encountered.
*
* <p>We use a much simpler approach. Whenever we see an assignment <code>v<sub>i</sub> = e</code>
* , we ask the enclosing function whether <code>v<sub>i</sub></code> is an exposed variable. If
* it is, we determine its source-level names <code>
* x<sub>1</sub>, x<sub>2</sub>, ..., x<sub>n</sub></code>, and then add edges corresponding to
* lexical writes of <code>v<sub>i</sub></code> into all the <code>x<sub>j</sub></code>.
*
* @author mschaefer
*/
private class FlowGraphSSAVisitor extends JSMethodInstructionVisitor {
// index of the instruction currently visited; -1 if the instruction isn't a normal instruction
public int instructionIndex = -1;
// flow graph being built
private final FlowGraph flowgraph;
// vertex factory to use for constructing new vertices
private final VertexFactory factory;
// lexical information about the current function
private final LexicalInformation lexicalInfo;
// the set of SSA variables in the current function that are accessed by nested functions
private final IntSet exposedVars;
// the IR of the current function
private final IR ir;
// the function vertex corresponding to the current function
private final FuncVertex func;
public FlowGraphSSAVisitor(IR ir, FlowGraph flowgraph) {
super(ir.getMethod(), ir.getSymbolTable(), cache.getDefUse(ir));
this.ir = ir;
this.flowgraph = flowgraph;
this.factory = flowgraph.getVertexFactory();
this.func = factory.makeFuncVertex(ir.getMethod().getDeclaringClass());
if (method instanceof AstMethod) {
this.lexicalInfo = ((AstMethod) method).lexicalInfo();
this.exposedVars = lexicalInfo.getAllExposedUses();
} else {
this.lexicalInfo = null;
this.exposedVars = EmptyIntSet.instance;
}
}
// add extra flow from v_def to every lexical variable it may correspond to at source-level
private void handleLexicalDef(int def) {
assert def != -1;
if (instructionIndex != -1 && exposedVars.contains(def)) {
VarVertex v = factory.makeVarVertex(func, def);
for (String localName : ir.getLocalNames(instructionIndex, def))
flowgraph.addEdge(
v, factory.makeLexicalAccessVertex(lexicalInfo.getScopingName(), localName));
}
}
@Override
public void visitPhi(SSAPhiInstruction phi) {
int n = phi.getNumberOfUses();
VarVertex w = factory.makeVarVertex(func, phi.getDef());
for (int i = 0; i < n; ++i) {
VarVertex v = factory.makeVarVertex(func, phi.getUse(i));
flowgraph.addEdge(v, w);
}
}
@Override
public void visitPrototypeLookup(PrototypeLookup proto) {
// treat it simply as an assignment
flowgraph.addEdge(
factory.makeVarVertex(func, proto.getUse(0)),
factory.makeVarVertex(func, proto.getDef()));
handleLexicalDef(proto.getDef());
}
private void visitPut(int val, String propName) {
Vertex v = factory.makeVarVertex(func, val), w = factory.makePropVertex(propName);
flowgraph.addEdge(v, w);
}
@Override
public void visitPut(SSAPutInstruction put) {
visitPut(put.getVal(), put.getDeclaredField().getName().toString());
}
@Override
public void visitSetPrototype(SetPrototype instruction) {
visitPut(instruction.getUse(1), "prototype");
}
@Override
public void visitAstGlobalWrite(AstGlobalWrite instruction) {
String propName = instruction.getDeclaredField().getName().toString();
// hack to account for global variables
assert propName.startsWith("global ");
propName = propName.substring("global ".length());
visitPut(instruction.getVal(), propName);
}
@Override
public void visitPropertyWrite(AstPropertyWrite pw) {
int p = pw.getMemberRef();
if (symtab.isConstant(p)) {
String pn = JSCallGraphUtil.simulateToStringForPropertyNames(symtab.getConstantValue(p));
Vertex v = factory.makeVarVertex(func, pw.getValue()), w = factory.makePropVertex(pn);
flowgraph.addEdge(v, w);
}
}
@Override
public void visitAstLexicalWrite(AstLexicalWrite lw) {
for (Access acc : lw.getAccesses()) {
Vertex v = factory.makeVarVertex(func, acc.valueNumber),
w = factory.makeLexicalAccessVertex(acc.variableDefiner, acc.variableName);
flowgraph.addEdge(v, w);
}
}
@Override
public void visitGet(SSAGetInstruction get) {
String propName = get.getDeclaredField().getName().toString();
if (propName.startsWith("global ")) propName = propName.substring("global ".length());
Vertex v = factory.makePropVertex(propName), w = factory.makeVarVertex(func, get.getDef());
flowgraph.addEdge(v, w);
handleLexicalDef(get.getDef());
}
@Override
public void visitAstGlobalRead(AstGlobalRead instruction) {
if (supportFullPointerAnalysis
&& instruction
.getGlobalName()
.endsWith(JSSSAPropagationCallGraphBuilder.GLOBAL_OBJ_VAR_NAME)) {
Vertex lval = factory.makeVarVertex(func, instruction.getDef());
flowgraph.addEdge(factory.global(), lval);
} else {
visitGet(instruction);
}
}
@Override
public void visitPropertyRead(AstPropertyRead pr) {
int p = pr.getMemberRef();
if (symtab.isConstant(p)) {
String pn = JSCallGraphUtil.simulateToStringForPropertyNames(symtab.getConstantValue(p));
Vertex v = factory.makePropVertex(pn), w = factory.makeVarVertex(func, pr.getDef());
flowgraph.addEdge(v, w);
}
IntSet argVns = Util.getArgumentsArrayVns(ir, du);
if (argVns.contains(pr.getObjectRef())) {
Vertex v = factory.makeArgVertex(func), w = factory.makeVarVertex(func, pr.getDef());
flowgraph.addEdge(v, w);
}
handleLexicalDef(pr.getDef());
}
@Override
public void visitAstLexicalRead(AstLexicalRead lr) {
for (Access acc : lr.getAccesses()) {
Vertex v = factory.makeLexicalAccessVertex(acc.variableDefiner, acc.variableName),
w = factory.makeVarVertex(func, acc.valueNumber);
flowgraph.addEdge(v, w);
handleLexicalDef(acc.valueNumber);
}
}
@Override
public void visitReturn(SSAReturnInstruction ret) {
if (ret.getResult() != -1) { // non-void return
Vertex v = factory.makeVarVertex(func, ret.getResult()), w = factory.makeRetVertex(func);
flowgraph.addEdge(v, w);
}
}
@Override
public void visitThrow(SSAThrowInstruction thr) {
Vertex v = factory.makeVarVertex(func, thr.getException()), w = factory.makeUnknownVertex();
flowgraph.addEdge(v, w);
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction katch) {
Vertex v = factory.makeUnknownVertex(), w = factory.makeVarVertex(func, katch.getDef());
flowgraph.addEdge(v, w);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke invk) {
flowgraph.addEdge(
factory.makeUnknownVertex(), factory.makeVarVertex(func, invk.getException()));
// check whether this invoke corresponds to a function expression/declaration
// flow callee variable into callee vertex
if (invk.getDeclaredTarget().equals(JavaScriptMethods.ctorReference)) {
flowgraph.addEdge(
factory.makeVarVertex(func, invk.getFunction()), factory.makeCallVertex(func, invk));
if (isFunctionConstructorInvoke(invk)) {
// second parameter is function name
String fn_name = symtab.getStringValue(invk.getUse(1));
// find the function being defined here
IClass klass =
cha.lookupClass(TypeReference.findOrCreate(JavaScriptTypes.jsLoader, fn_name));
if (klass == null) {
System.err.println(
"cannot find "
+ fn_name
+ " at "
+ ((AstMethod) ir.getMethod())
.getSourcePosition(
ir.getCallInstructionIndices(invk.getCallSite()).intIterator().next()));
return;
}
IMethod fn = klass.getMethod(AstMethodReference.fnSelector);
FuncVertex fnVertex = factory.makeFuncVertex(klass);
// function flows into its own v1 variable
flowgraph.addEdge(fnVertex, factory.makeVarVertex(fnVertex, 1));
// flow parameters into local variables
for (int i = 1; i < fn.getNumberOfParameters(); ++i)
flowgraph.addEdge(
factory.makeParamVertex(fnVertex, i), factory.makeVarVertex(fnVertex, i + 1));
// flow function into result variable
flowgraph.addEdge(fnVertex, factory.makeVarVertex(func, invk.getDef()));
} else if (supportFullPointerAnalysis) {
CreationSiteVertex cs =
factory.makeCreationSiteVertex(method, invk.iIndex(), JavaScriptTypes.Object);
// flow creation site into result of new call
flowgraph.addEdge(cs, factory.makeVarVertex(func, invk.getDef()));
// also passed as 'this' to constructor
if (invk.getNumberOfPositionalParameters() > 1) {
flowgraph.addEdge(cs, factory.makeVarVertex(func, invk.getUse(0)));
}
}
} else {
// check whether it is a method call
if (invk.getDeclaredTarget().equals(JavaScriptMethods.dispatchReference)) {
// we only handle method calls with constant names
if (symtab.isConstant(invk.getFunction())) {
String pn =
JSCallGraphUtil.simulateToStringForPropertyNames(
symtab.getConstantValue(invk.getFunction()));
// flow callee property into callee vertex
flowgraph.addEdge(factory.makePropVertex(pn), factory.makeCallVertex(func, invk));
}
} else {
// this case is simpler: just flow callee variable into callee vertex
flowgraph.addEdge(
factory.makeVarVertex(func, invk.getFunction()), factory.makeCallVertex(func, invk));
}
}
handleLexicalDef(invk.getDef());
}
@Override
public void visitNew(SSANewInstruction invk) {
if (supportFullPointerAnalysis) {
// special case for supporting full pointer analysis
// some core objects in the prologue (and the arguments array objects) get created with
// 'new'
CreationSiteVertex cs =
factory.makeCreationSiteVertex(method, invk.iIndex(), invk.getConcreteType());
// flow creation site into result of new call
flowgraph.addEdge(cs, factory.makeVarVertex(func, invk.getDef()));
}
}
}
}
| 17,123
| 38.09589
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/AbstractVertexVisitor.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.callgraph.fieldbased.flowgraph.vertices;
/**
* Visitor class for {@link Vertex}.
*
* @author mschaefer
*/
public class AbstractVertexVisitor<T> implements VertexVisitor<T> {
public T visitVertex() {
return null;
}
@Override
public T visitVarVertex(VarVertex varVertex) {
return visitVertex();
}
@Override
public T visitPropVertex(PropVertex propVertex) {
return visitVertex();
}
@Override
public T visitUnknownVertex(UnknownVertex unknownVertex) {
return visitVertex();
}
@Override
public T visitFuncVertex(FuncVertex funcVertex) {
return visitVertex();
}
@Override
public T visitCreationSiteVertex(CreationSiteVertex csVertex) {
return visitVertex();
}
@Override
public T visitParamVertex(ParamVertex paramVertex) {
return visitVertex();
}
@Override
public T visitRetVertex(RetVertex retVertex) {
return visitVertex();
}
@Override
public T visitArgVertex(ArgVertex argVertex) {
return visitVertex();
}
@Override
public T visitCalleeVertex(CallVertex calleeVertex) {
return visitVertex();
}
@Override
public T visitLexicalAccessVertex(LexicalVarVertex lexicalAccessVertex) {
return visitVertex();
}
@Override
public T visitGlobalVertex(GlobalVertex globalVertex) {
return visitVertex();
}
@Override
public T visitPrototypeVertex(PrototypeFieldVertex protoVertex) {
return visitVertex();
}
@Override
public T visitReflectiveCallVertex(ReflectiveCallVertex reflectiveCallVertex) {
return visitVertex();
}
}
| 1,965
| 21.340909
| 81
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/ArgVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
/**
* A return vertex represents the 'arguments' array of a given function.
*
* @author Julian Dolby (dolby@us.ibm.com)
*/
public class ArgVertex extends Vertex implements PointerKey {
private final FuncVertex func;
ArgVertex(FuncVertex func) {
this.func = func;
}
public FuncVertex getFunc() {
return func;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitArgVertex(this);
}
@Override
public String toString() {
return "Args(" + func + ')';
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
return "Args(" + func.toSourceLevelString(cache) + ')';
}
}
| 1,223
| 25.042553
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/CallVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
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.IClass;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
/**
* A call vertex represents the possible callees of a function call or {@code new} expression.
*
* @author mschaefer
*/
public class CallVertex extends Vertex {
// method containing the call
private final FuncVertex func;
// PC of the call site
private final CallSiteReference site;
// the call instruction itself
private final JavaScriptInvoke invk;
CallVertex(FuncVertex func, CallSiteReference site, JavaScriptInvoke invk) {
this.func = func;
this.site = site;
this.invk = invk;
}
public FuncVertex getCaller() {
return func;
}
public CallSiteReference getSite() {
return site;
}
public JavaScriptInvoke getInstruction() {
return invk;
}
/** Does this call vertex correspond to a {@code new} instruction? */
public boolean isNew() {
return site.getDeclaredTarget() == JavaScriptMethods.ctorReference;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitCalleeVertex(this);
}
@Override
public String toString() {
return "Callee(" + func + ", " + site + ')';
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
IClass concreteType = func.getConcreteType();
AstMethod method = (AstMethod) concreteType.getMethod(AstMethodReference.fnSelector);
return "Callee(" + method.getSourcePosition(site.getProgramCounter()).prettyPrint() + ")";
}
}
| 2,195
| 27.894737
| 94
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/CreationSiteVertex.java
|
package com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.collections.Pair;
import java.util.Iterator;
public class CreationSiteVertex extends Vertex implements ObjectVertex {
private final IMethod node;
private final int instructionIndex;
private final TypeReference createdType;
public CreationSiteVertex(IMethod node, int instructionIndex, TypeReference createdType) {
super();
this.node = node;
this.instructionIndex = instructionIndex;
this.createdType = createdType;
}
@Override
public IClass getConcreteType() {
return node.getClassHierarchy().lookupClass(createdType);
}
public IMethod getMethod() {
return node;
}
@Override
public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) {
CGNode cgn = CG.getNode(node, Everywhere.EVERYWHERE);
assert cgn != null : node;
return NonNullSingletonIterator.make(
Pair.make(cgn, NewSiteReference.make(instructionIndex, createdType)));
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitCreationSiteVertex(this);
}
}
| 1,511
| 30.5
| 92
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/FuncVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions.JavaScriptConstructor;
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.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
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.types.MethodReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.collections.Pair;
import java.util.Iterator;
import java.util.Set;
/**
* A function vertex represents a function object (or, more precisely, all function objects arising
* from a single function expression or declaration).
*
* @author mschaefer
*/
public class FuncVertex extends Vertex implements ObjectVertex {
// the IClass representing this function in the class hierarchy
protected final IClass klass;
FuncVertex(IClass method) {
this.klass = method;
}
public String getFullName() {
return klass.getName().toString();
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitFuncVertex(this);
}
@Override
public String toString() {
String methodName = klass.getName().toString();
return "Func(" + methodName.substring(methodName.lastIndexOf('/') + 1) + ')';
}
@Override
public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) {
MethodReference ctorRef = JavaScriptMethods.makeCtorReference(JavaScriptTypes.Function);
Set<CGNode> f = CG.getNodes(ctorRef);
CGNode ctor = null;
for (CGNode n : f) {
JavaScriptConstructor c = (JavaScriptConstructor) n.getMethod();
if (c.constructedType().equals(klass)) {
ctor = n;
break;
}
}
// built in objects
if (ctor == null) {
return EmptyIterator.instance();
}
Iterator<CGNode> callers = CG.getPredNodes(ctor);
CGNode caller = callers.next();
assert !callers.hasNext();
Iterator<CallSiteReference> sites = CG.getPossibleSites(caller, ctor);
CallSiteReference site = sites.next();
assert !sites.hasNext()
: caller + " --> " + ctor + " @ " + site + " and " + sites.next() + '\n' + caller.getIR();
return NonNullSingletonIterator.make(
Pair.make(caller, NewSiteReference.make(site.getProgramCounter(), klass.getReference())));
}
@Override
public IClass getConcreteType() {
return klass;
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
AstMethod method = (AstMethod) klass.getMethod(AstMethodReference.fnSelector);
if (method != null) {
return "Func(" + method.getSourcePosition().prettyPrint() + ")";
} else {
return toString();
}
}
}
| 3,478
| 31.820755
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/GlobalVertex.java
|
package com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.Pair;
import java.util.Iterator;
public class GlobalVertex extends Vertex implements ObjectVertex {
private GlobalVertex() {}
public static final GlobalVertex global = new GlobalVertex();
public static GlobalVertex instance() {
return global;
}
@Override
public IClass getConcreteType() {
return null;
}
@Override
public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) {
return EmptyIterator.instance();
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitGlobalVertex(this);
}
}
| 918
| 24.527778
| 82
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/LexicalVarVertex.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.callgraph.fieldbased.flowgraph.vertices;
/**
* A lexical access vertex represents a lexical variable, i.e., a local variable that is accessed
* from within a nested function. It is identified by the name of its defining function, and its own
* name.
*
* @author mschaefer
*/
public class LexicalVarVertex extends Vertex {
// name of the function defining this lexical variable
private final String definer;
// name of the lexical variable itself
private final String name;
LexicalVarVertex(String definer, String name) {
this.definer = definer;
this.name = name;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitLexicalAccessVertex(this);
}
@Override
public String toString() {
return "LexVar(" + definer.substring(definer.lastIndexOf('/') + 1) + ", " + name + ')';
}
}
| 1,256
| 28.928571
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/ObjectVertex.java
|
package com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
public interface ObjectVertex extends InstanceKey {}
| 184
| 29.833333
| 69
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/ParamVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
/**
* A parameter vertex represents a positional parameter of a function. It doesn't necessarily need
* to correspond to a named parameter.
*
* <p>Numbering of positional parameters is 1-based, with parameter 0 being the {@code this} value.
*
* <p>A named parameter is an ordinary SSA variable, hence it is represented as a {@link VarVertex}.
* The flow graph builder sets up edges between parameter vertices and their corresponding variable
* vertices for named parameters.
*
* @author mschaefer
*/
public class ParamVertex extends Vertex {
private final FuncVertex func;
private final int index;
ParamVertex(FuncVertex func, int index) {
this.func = func;
this.index = index;
}
public FuncVertex getFunc() {
return func;
}
public int getIndex() {
return index;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitParamVertex(this);
}
@Override
public String toString() {
return "Param(" + func + ", " + index + ')';
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
return "Param(" + func.toSourceLevelString(cache) + ", " + index + ')';
}
}
| 1,676
| 27.423729
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/PropVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
/**
* A property vertex represents all properties with a given name.
*
* @author mschaefer
*/
public class PropVertex extends Vertex implements PointerKey {
private final String propName;
PropVertex(String propName) {
this.propName = propName;
}
public String getPropName() {
return propName;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitPropVertex(this);
}
@Override
public String toString() {
return "Prop(" + propName + ')';
}
}
| 1,018
| 23.853659
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/PrototypeFieldVertex.java
|
package com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
public class PrototypeFieldVertex extends Vertex implements PointerKey {
public enum PrototypeField {
__proto__,
prototype
}
private final PrototypeField field;
private final ObjectVertex type;
public PrototypeFieldVertex(PrototypeField field, ObjectVertex type) {
this.field = field;
this.type = type;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitPrototypeVertex(this);
}
@Override
public String toString() {
return field + ":" + type;
}
}
| 659
| 21
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/ReflectiveCallVertex.java
|
package com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
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.IClass;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
public class ReflectiveCallVertex extends Vertex {
// method containing the call
private final FuncVertex caller;
// PC of the call site
private final CallSiteReference site;
// the call instruction itself
private final JavaScriptInvoke invk;
public ReflectiveCallVertex(FuncVertex caller, CallSiteReference site, JavaScriptInvoke invk) {
this.caller = caller;
this.site = site;
this.invk = invk;
}
public FuncVertex getCaller() {
return caller;
}
public CallSiteReference getSite() {
return site;
}
public JavaScriptInvoke getInstruction() {
return invk;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitReflectiveCallVertex(this);
}
@Override
public String toString() {
return "ReflectiveCallee(" + caller + ", " + site + ')';
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
IClass concreteType = caller.getConcreteType();
AstMethod method = (AstMethod) concreteType.getMethod(AstMethodReference.fnSelector);
return "ReflectiveCallee("
+ method.getSourcePosition(site.getProgramCounter()).prettyPrint()
+ ")";
}
}
| 1,550
| 25.741379
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/RetVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
/**
* A return vertex represents all return values of a given function.
*
* @author mschaefer
*/
public class RetVertex extends Vertex implements PointerKey {
private final FuncVertex func;
RetVertex(FuncVertex func) {
this.func = func;
}
public FuncVertex getFunc() {
return func;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitRetVertex(this);
}
@Override
public String toString() {
return "Ret(" + func + ')';
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
return "Ret(" + func.toSourceLevelString(cache) + ')';
}
}
| 1,195
| 24.446809
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/UnknownVertex.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.callgraph.fieldbased.flowgraph.vertices;
/**
* The unknown vertex is used to model complicated data flow. For instance, thrown exceptions flow
* into Unknown, and catch blocks read their values from it.
*
* @author mschaefer
*/
public class UnknownVertex extends Vertex {
public static final UnknownVertex INSTANCE = new UnknownVertex();
private UnknownVertex() {}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitUnknownVertex(this);
}
@Override
public String toString() {
return "Unknown";
}
}
| 962
| 27.323529
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/VarVertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.util.debug.Assertions;
import java.util.Arrays;
/**
* A variable vertex represents an SSA variable inside a given function.
*
* @author mschaefer
*/
public final class VarVertex extends Vertex implements PointerKey {
private final FuncVertex func;
private final int valueNumber;
VarVertex(FuncVertex func, int valueNumber) {
Assertions.productionAssertion(valueNumber >= 0, "Invalid value number for VarVertex");
this.func = func;
this.valueNumber = valueNumber;
}
public FuncVertex getFunction() {
return func;
}
public int getValueNumber() {
return valueNumber;
}
@Override
public <T> T accept(VertexVisitor<T> visitor) {
return visitor.visitVarVertex(this);
}
@Override
public String toString() {
return "Var(" + func + ", " + valueNumber + ')';
}
@Override
public String toSourceLevelString(IAnalysisCacheView cache) {
// we want to get a variable name rather than a value number
IClass concreteType = func.getConcreteType();
AstMethod method = (AstMethod) concreteType.getMethod(AstMethodReference.fnSelector);
IR ir = cache.getIR(method);
String methodPos = method.getSourcePosition().prettyPrint();
// we rely on the fact that the CAst IR ignores the index position!
String[] localNames = ir.getLocalNames(0, valueNumber);
StringBuilder result = new StringBuilder("Var(").append(methodPos).append(", ");
if (localNames != null && localNames.length > 0) {
result.append(Arrays.toString(localNames));
} else {
result.append("%ssa_val ").append(valueNumber);
}
result.append(")");
return result.toString();
}
}
| 2,392
| 31.337838
| 91
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/Vertex.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
/**
* Class representing a flow graph vertex. Vertices should never be instantiated directly, but
* rather generated through a {@link VertexFactory}.
*
* @author mschaefer
*/
public abstract class Vertex {
public abstract <T> T accept(VertexVisitor<T> visitor);
/**
* If possible, returns a String representation of {@code this} that refers to source-level
* entities rather thatn WALA-internal ones (e.g., source-level variable names rather than SSA
* value numbers). By default, just returns the results of {@link #toString()}
*/
public String toSourceLevelString(@SuppressWarnings("unused") IAnalysisCacheView cache) {
return toString();
}
}
| 1,176
| 34.666667
| 96
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/VertexFactory.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.callgraph.fieldbased.flowgraph.vertices;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import java.util.Collection;
import java.util.Map;
/**
* A vertex factory is associated with a flow graph. It manages its vertex set, making sure that
* vertices aren't unnecessarily created twice.
*
* @author mschaefer
*/
public class VertexFactory {
private final Map<Pair<FuncVertex, CallSiteReference>, CallVertex> callVertexCache =
HashMapFactory.make();
private final Map<Pair<FuncVertex, CallSiteReference>, ReflectiveCallVertex>
reflectiveCallVertexCache = HashMapFactory.make();
private final Map<IClass, FuncVertex> funcVertexCache = HashMapFactory.make();
private final Map<Pair<FuncVertex, Integer>, ParamVertex> paramVertexCache =
HashMapFactory.make();
private final Map<String, PropVertex> propVertexCache = HashMapFactory.make();
private final Map<FuncVertex, RetVertex> retVertexCache = HashMapFactory.make();
private final Map<FuncVertex, ArgVertex> argVertexCache = HashMapFactory.make();
private final Map<Pair<FuncVertex, Integer>, VarVertex> varVertexCache = HashMapFactory.make();
private final Map<Pair<String, String>, LexicalVarVertex> lexicalAccessVertexCache =
HashMapFactory.make();
private final Map<Pair<IMethod, Integer>, CreationSiteVertex> creationSites =
HashMapFactory.make();
public CallVertex makeCallVertex(FuncVertex func, JavaScriptInvoke invk) {
CallSiteReference site = invk.getCallSite();
Pair<FuncVertex, CallSiteReference> key = Pair.make(func, site);
CallVertex value = callVertexCache.get(key);
if (value == null) callVertexCache.put(key, value = new CallVertex(func, site, invk));
return value;
}
public ReflectiveCallVertex makeReflectiveCallVertex(FuncVertex func, JavaScriptInvoke invk) {
CallSiteReference site = invk.getCallSite();
Pair<FuncVertex, CallSiteReference> key = Pair.make(func, site);
ReflectiveCallVertex value = reflectiveCallVertexCache.get(key);
if (value == null) {
reflectiveCallVertexCache.put(key, value = new ReflectiveCallVertex(func, site, invk));
}
return value;
}
public Iterable<CallVertex> getCallVertices() {
return callVertexCache.values();
}
public CreationSiteVertex makeCreationSiteVertex(
IMethod method, int instruction, TypeReference createdType) {
Pair<IMethod, Integer> key = Pair.make(method, instruction);
CreationSiteVertex value = creationSites.get(key);
if (value == null) {
creationSites.put(key, value = new CreationSiteVertex(method, instruction, createdType));
}
return value;
}
public Collection<CreationSiteVertex> creationSites() {
return creationSites.values();
}
public FuncVertex makeFuncVertex(IClass klass) {
FuncVertex value = funcVertexCache.get(klass);
if (value == null) funcVertexCache.put(klass, value = new FuncVertex(klass));
return value;
}
public Collection<FuncVertex> getFuncVertices() {
return funcVertexCache.values();
}
public ParamVertex makeParamVertex(FuncVertex func, int index) {
Pair<FuncVertex, Integer> key = Pair.make(func, index);
ParamVertex value = paramVertexCache.get(key);
if (value == null) paramVertexCache.put(key, value = new ParamVertex(func, index));
return value;
}
public PropVertex makePropVertex(String name) {
PropVertex value = propVertexCache.get(name);
if (value == null) propVertexCache.put(name, value = new PropVertex(name));
return value;
}
public Iterable<PropVertex> getPropVertices() {
return propVertexCache.values();
}
public RetVertex makeRetVertex(FuncVertex func) {
RetVertex value = retVertexCache.get(func);
if (value == null) retVertexCache.put(func, value = new RetVertex(func));
return value;
}
public Iterable<RetVertex> getRetVertices() {
return retVertexCache.values();
}
public ArgVertex makeArgVertex(FuncVertex func) {
ArgVertex value = argVertexCache.get(func);
if (value == null) argVertexCache.put(func, value = new ArgVertex(func));
return value;
}
public Iterable<ArgVertex> getArgVertices() {
return argVertexCache.values();
}
public UnknownVertex makeUnknownVertex() {
return UnknownVertex.INSTANCE;
}
public VarVertex makeVarVertex(FuncVertex func, int valueNumber) {
Pair<FuncVertex, Integer> key = Pair.make(func, valueNumber);
VarVertex value = varVertexCache.get(key);
if (value == null) varVertexCache.put(key, value = new VarVertex(func, valueNumber));
return value;
}
public Iterable<VarVertex> getVarVertices() {
return varVertexCache.values();
}
public LexicalVarVertex makeLexicalAccessVertex(String definer, String name) {
Pair<String, String> key = Pair.make(definer, name);
LexicalVarVertex value = lexicalAccessVertexCache.get(key);
if (value == null)
lexicalAccessVertexCache.put(key, value = new LexicalVarVertex(definer, name));
return value;
}
private final GlobalVertex global = GlobalVertex.instance();
public GlobalVertex global() {
return global;
}
}
| 5,795
| 35.683544
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/callgraph/fieldbased/flowgraph/vertices/VertexVisitor.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.callgraph.fieldbased.flowgraph.vertices;
public interface VertexVisitor<T> {
T visitVarVertex(VarVertex varVertex);
T visitPropVertex(PropVertex propVertex);
T visitUnknownVertex(UnknownVertex unknownVertex);
T visitFuncVertex(FuncVertex funcVertex);
T visitCreationSiteVertex(CreationSiteVertex csVertex);
T visitParamVertex(ParamVertex paramVertex);
T visitRetVertex(RetVertex retVertex);
T visitCalleeVertex(CallVertex calleeVertex);
T visitLexicalAccessVertex(LexicalVarVertex lexicalAccessVertex);
T visitArgVertex(ArgVertex argVertex);
T visitGlobalVertex(GlobalVertex globalVertex);
T visitPrototypeVertex(PrototypeFieldVertex protoVertex);
T visitReflectiveCallVertex(ReflectiveCallVertex reflectiveCallVertex);
}
| 1,165
| 28.15
| 73
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/cfg/JSInducedCFG.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.cfg;
import com.ibm.wala.cast.ir.cfg.AstInducedCFG;
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.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ssa.SSAInstruction;
public class JSInducedCFG extends AstInducedCFG {
public JSInducedCFG(SSAInstruction[] instructions, IMethod method, Context context) {
super(instructions, method, context);
}
class JSPEIVisitor extends AstPEIVisitor implements JSInstructionVisitor {
JSPEIVisitor(boolean[] r) {
super(r);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke inst) {
breakBasicBlock();
}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction inst) {}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf instruction) {}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {
breakBasicBlock();
}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {}
@Override
public void visitSetPrototype(SetPrototype instruction) {}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {}
}
class JSBranchVisitor extends AstBranchVisitor implements JSInstructionVisitor {
JSBranchVisitor(boolean[] r) {
super(r);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke inst) {}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction inst) {}
@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) {}
}
@Override
protected BranchVisitor makeBranchVisitor(boolean[] r) {
return new JSBranchVisitor(r);
}
@Override
protected PEIVisitor makePEIVisitor(boolean[] r) {
return new JSPEIVisitor(r);
}
}
| 2,921
| 27.647059
| 87
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/client/JavaScriptAnalysisEngine.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.client;
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.flowgraph.vertices.ObjectVertex;
import com.ibm.wala.cast.js.client.impl.ZeroCFABuilderFactory;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
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.JavaScriptEntryPoints;
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.js.types.JavaScriptTypes;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.client.AbstractAnalysisEngine;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException;
import com.ibm.wala.ipa.callgraph.Entrypoint;
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.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.cha.SeqClassHierarchyFactory;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collections;
import java.util.Set;
import java.util.jar.JarFile;
public abstract class JavaScriptAnalysisEngine<I extends InstanceKey>
extends AbstractAnalysisEngine<I, CallGraphBuilder<I>, Void> {
protected JavaScriptLoaderFactory loaderFactory;
protected JavaScriptTranslatorFactory translatorFactory;
@Override
public void buildAnalysisScope() {
loaderFactory = new JavaScriptLoaderFactory(translatorFactory);
SourceModule[] files = moduleFiles.toArray(new SourceModule[0]);
scope = new CAstAnalysisScope(files, loaderFactory, Collections.singleton(JavaScriptLoader.JS));
}
@Override
public IClassHierarchy buildClassHierarchy() {
try {
return setClassHierarchy(
SeqClassHierarchyFactory.make(getScope(), loaderFactory, JavaScriptLoader.JS));
} catch (ClassHierarchyException e) {
Assertions.UNREACHABLE(e.toString());
return null;
}
}
public void setTranslatorFactory(JavaScriptTranslatorFactory factory) {
this.translatorFactory = factory;
}
@Override
public void setJ2SELibraries(JarFile[] libs) {
Assertions.UNREACHABLE("Illegal to call setJ2SELibraries");
}
@Override
public void setJ2SELibraries(Module[] libs) {
Assertions.UNREACHABLE("Illegal to call setJ2SELibraries");
}
@Override
protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) {
return new JavaScriptEntryPoints(cha, cha.getLoader(JavaScriptTypes.jsLoader));
}
@Override
public IAnalysisCacheView makeDefaultCache() {
return new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory());
}
@Override
public JSAnalysisOptions getDefaultOptions(Iterable<Entrypoint> roots) {
final JSAnalysisOptions options = new JSAnalysisOptions(scope, roots);
options.setUseConstantSpecificKeys(true);
options.setUseStacksForLexicalScoping(true);
return options;
}
public static class FieldBasedJavaScriptAnalysisEngine
extends JavaScriptAnalysisEngine<ObjectVertex> {
public enum BuilderType {
PESSIMISTIC,
OPTIMISTIC,
REFLECTIVE
}
private BuilderType builderType = BuilderType.OPTIMISTIC;
/** @return the builderType */
public BuilderType getBuilderType() {
return builderType;
}
/** @param builderType the builderType to set */
public void setBuilderType(BuilderType builderType) {
this.builderType = builderType;
}
@Override
public JSAnalysisOptions getDefaultOptions(Iterable<Entrypoint> roots) {
return JSCallGraphUtil.makeOptions(scope, getClassHierarchy(), roots);
}
@Override
protected CallGraphBuilder<ObjectVertex> getCallGraphBuilder(
final IClassHierarchy cha, AnalysisOptions options, final IAnalysisCacheView cache) {
Set<Entrypoint> roots = HashSetFactory.make();
for (Entrypoint e : options.getEntrypoints()) {
roots.add(e);
}
if (builderType.equals(BuilderType.OPTIMISTIC)) {
((JSAnalysisOptions) options).setHandleCallApply(false);
}
final FieldBasedCallGraphBuilder builder =
builderType.equals(BuilderType.PESSIMISTIC)
? new PessimisticCallGraphBuilder(
getClassHierarchy(), options, makeDefaultCache(), true)
: new OptimisticCallgraphBuilder(
getClassHierarchy(), options, makeDefaultCache(), true);
return new CallGraphBuilder<>() {
private PointerAnalysis<ObjectVertex> ptr;
@Override
public CallGraph makeCallGraph(AnalysisOptions options, IProgressMonitor monitor)
throws IllegalArgumentException, CallGraphBuilderCancelException {
CallGraphResult result;
try {
result = builder.buildCallGraph(options.getEntrypoints(), monitor);
} catch (CancelException e) {
throw CallGraphBuilderCancelException.createCallGraphBuilderCancelException(
e, null, null);
}
ptr = result.getPointerAnalysis();
return result.getCallGraph();
}
@Override
public PointerAnalysis<ObjectVertex> getPointerAnalysis() {
return ptr;
}
@Override
public IAnalysisCacheView getAnalysisCache() {
return cache;
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
};
}
}
public static class PropagationJavaScriptAnalysisEngine
extends JavaScriptAnalysisEngine<InstanceKey> {
@Override
protected JSZeroOrOneXCFABuilder getCallGraphBuilder(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
return new ZeroCFABuilderFactory().make((JSAnalysisOptions) options, cache, cha);
}
}
}
| 7,247
| 34.881188
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/client/impl/OneCFABuilderFactory.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.client.impl;
import com.ibm.wala.cast.ipa.callgraph.StandardFunctionTargetSelector;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ipa.callgraph.JSZeroOrOneXCFABuilder;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.cha.IClassHierarchy;
/**
* @author Julian Dolby (dolby@us.ibm.com)
* <p>A factory to create call graph builders using 0-CFA
*/
public class OneCFABuilderFactory {
public CallGraphBuilder<InstanceKey> make(
JSAnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) {
com.ibm.wala.ipa.callgraph.impl.Util.addDefaultSelectors(options, cha);
options.setSelector(new StandardFunctionTargetSelector(cha, options.getMethodTargetSelector()));
return new JSZeroOrOneXCFABuilder(
cha, options, cache, null, null, ZeroXInstanceKeys.NONE, true);
}
}
| 1,468
| 38.702703
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/client/impl/ZeroCFABuilderFactory.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.client.impl;
import com.ibm.wala.cast.ipa.callgraph.StandardFunctionTargetSelector;
import com.ibm.wala.cast.js.ipa.callgraph.JSAnalysisOptions;
import com.ibm.wala.cast.js.ipa.callgraph.JSZeroOrOneXCFABuilder;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.cha.IClassHierarchy;
/**
* @author Julian Dolby (dolby@us.ibm.com)
* <p>A factory to create call graph builders using 0-CFA
*/
public class ZeroCFABuilderFactory {
public JSZeroOrOneXCFABuilder make(
JSAnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) {
com.ibm.wala.ipa.callgraph.impl.Util.addDefaultSelectors(options, cha);
options.setSelector(new StandardFunctionTargetSelector(cha, options.getMethodTargetSelector()));
return new JSZeroOrOneXCFABuilder(
cha, options, cache, null, null, ZeroXInstanceKeys.NONE, false);
}
}
| 1,352
| 37.657143
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/CompositeFileMapping.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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import java.util.ArrayList;
import java.util.List;
public class CompositeFileMapping implements FileMapping {
private final List<FileMapping> mappings = new ArrayList<>(2);
public CompositeFileMapping(FileMapping a, FileMapping b) {
addMapping(a);
addMapping(b);
}
private void addMapping(FileMapping fm) {
if (fm instanceof CompositeFileMapping) {
mappings.addAll(((CompositeFileMapping) fm).mappings);
} else {
mappings.add(fm);
}
}
@Override
public IncludedPosition getIncludedPosition(Position line) {
for (FileMapping fm : mappings) {
IncludedPosition result = fm.getIncludedPosition(line);
if (result != null) {
return result;
}
}
return null;
}
@Override
public String toString() {
return mappings.toString();
}
}
| 1,288
| 25.306122
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/DefaultSourceExtractor.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Supplier;
public class DefaultSourceExtractor extends DomLessSourceExtractor {
public static Supplier<JSSourceExtractor> factory = DefaultSourceExtractor::new;
protected static class HtmlCallBack extends DomLessSourceExtractor.HtmlCallback {
private final HashMap<String, String> constructors = HashMapFactory.make();
private final ArrayDeque<String> stack = new ArrayDeque<>();
private final ArrayDeque<ITag> forms = new ArrayDeque<>();
private final Set<Pair<ITag, String>> sets = new HashSet<>();
public HtmlCallBack(URL entrypointUrl, IUrlResolver urlResolver) {
super(entrypointUrl, urlResolver);
constructors.put("FORM", "DOMHTMLFormElement");
constructors.put("TABLE", "DOMHTMLTableElement");
}
@Override
public void handleEndTag(ITag tag) {
super.handleEndTag(tag);
endElement(stack.pop());
if (tag.getName().equalsIgnoreCase("FORM")) {
forms.pop();
}
for (Entry<String, Pair<String, Position>> e : tag.getAllAttributes().entrySet()) {
String a = e.getKey();
String v = e.getValue().fst;
if (v != null && v.startsWith("javascript:")) {
try {
writeEntrypoint(
" " + v.substring(11),
e.getValue().snd,
new URL(tag.getElementPosition().getURL().toString() + '#' + a),
true);
} catch (MalformedURLException ex) {
writeEntrypoint(v.substring(11), e.getValue().snd, entrypointUrl, false);
}
}
}
}
@Override
protected void handleDOM(ITag tag, String funcName) {
String cons = constructors.get(tag.getName().toUpperCase());
if (cons == null) cons = "DOMHTMLElement";
writeElement(tag, cons, funcName);
newLine();
}
protected void printlnIndented(String line, ITag relatedTag) {
printlnIndented(line, relatedTag == null ? null : relatedTag.getElementPosition());
}
private void printlnIndented(String line, Position pos) {
StringBuilder indentedLine = new StringBuilder(" ".repeat(stack.size()));
indentedLine.append(line);
if (pos == null) {
domRegion.println(indentedLine.toString());
} else {
domRegion.println(indentedLine.toString(), pos, entrypointUrl, false);
}
}
private void newLine() {
domRegion.println("");
}
private static String makeRef(String object, String property) {
assert object != null && property != null;
return object + "[\"" + property + "\"]";
}
protected void writeElement(ITag tag, String cons, String varName) {
Map<String, Pair<String, Position>> attrs = tag.getAllAttributes();
printlnIndented("function make_" + varName + "(parent) {", tag);
stack.push(varName);
printlnIndented("this.temp = " + cons + ';', tag);
printlnIndented("this.temp(\"" + tag.getName() + "\");", tag);
for (Map.Entry<String, Pair<String, Position>> e : attrs.entrySet()) {
String attr = e.getKey();
String value = e.getValue().fst;
writeAttribute(tag, attr, value, "this", varName);
}
if (tag.getName().equalsIgnoreCase("FORM")) {
forms.push(tag);
printlnIndented(" document.forms[document.formCount++] = this;", tag);
printlnIndented(" var currentForm = this;", tag);
}
if (tag.getName().equalsIgnoreCase("INPUT")) {
String prop = attrs.containsKey("name") ? attrs.get("name").fst : null;
String type = attrs.containsKey("type") ? attrs.get("type").fst : null;
if (type != null && prop != null) {
// input tags do not need to be in a form
if (!forms.isEmpty()) {
if (type.equalsIgnoreCase("RADIO")) {
if (sets.add(Pair.make(forms.peek(), prop))) {
printlnIndented(" " + makeRef("currentForm", prop) + " = new Array();", tag);
printlnIndented(" " + makeRef("currentForm", prop + "Counter") + " = 0;", tag);
}
printlnIndented(
" " + makeRef(makeRef("currentForm", prop), prop + "Counter++") + " = this;",
tag);
} else {
printlnIndented(" " + makeRef("currentForm", prop) + " = this;", tag);
}
}
}
inputElementCallback();
}
assert varName != null && !varName.isEmpty();
printlnIndented(varName + " = this;", tag);
printlnIndented("document." + varName + " = this;", tag);
printlnIndented("parent.appendChild(this);", tag);
}
protected void inputElementCallback() {
// this space intentionally left blank
}
protected void writeAttribute(
ITag tag, String attr, String value, String varName, String varName2) {
writePortletAttribute(tag, attr, value, varName);
writeEventAttribute(tag, attr, value, varName, varName2);
}
protected void writeEventAttribute(
ITag tag, String attr, String value, String varName, String varName2) {
// There should probably be more checking to see what the attributes are since we allow things
// like: ; to be used as attributes now.
if (attr.length() >= 2 && attr.substring(0, 2).equals("on")) {
printlnIndented(
varName
+ '.'
+ attr
+ " = function "
+ tag.getName().toLowerCase()
+ '_'
+ attr
+ "(event) {"
+ value
+ "};",
tag);
writeEntrypoint(
varName2 + '.' + attr + "(null);", tag.getElementPosition(), entrypointUrl, false);
} else if (value != null) {
Pair<String, Character> x = quotify(value);
value = x.fst;
char quote = x.snd;
if (attr.equals(attr.toUpperCase())) {
attr = attr.toLowerCase();
}
printlnIndented(varName + "['" + attr + "'] = " + quote + value + quote + ';', tag);
}
}
protected void writePortletAttribute(ITag tag, String attr, String value, String varName) {
if (attr.equals("portletid")) {
switch (value.substring(value.length() - 4)) {
case "vice":
newLine();
newLine();
printlnIndented(
"function cVice() { var contextVice = " + varName + "; }\ncVice();\n", tag);
break;
case "root":
newLine();
newLine();
printlnIndented(
"function cRoot() { var contextRoot = " + varName + "; }\ncRoot();\n", tag);
break;
}
}
}
protected void endElement(String name) {
printlnIndented("};", (Position) null);
if (stack.isEmpty()) {
printlnIndented("new make_" + name + "(document);\n\n", (Position) null);
} else {
printlnIndented("new make_" + name + "(this);\n", (Position) null);
}
}
}
@Override
protected IGeneratorCallback createHtmlCallback(URL entrypointUrl, IUrlResolver urlResolver) {
return new HtmlCallBack(entrypointUrl, urlResolver);
}
}
| 8,010
| 33.982533
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/DomLessSourceExtractor.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.html.jericho.JerichoHtmlParser;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.util.collections.Pair;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
/** extracts JavaScript source code from HTML, with no model of the actual DOM data structure */
public class DomLessSourceExtractor extends JSSourceExtractor {
private static final Pattern LEGAL_JS_IDENTIFIER_REGEXP =
Pattern.compile("^[a-zA-Z$_][a-zA-Z\\d$_]*$");
private static final Pattern LEGAL_JS_KEYWORD_REGEXP =
Pattern.compile(
"^((break)|(case)|(catch)|(continue)|(debugger)|(default)|(delete)|(do)|(else)|(finally)|(for)|(function)|(if)|(in)|(instanceof)|(new)|(return)|(switch)|(this)|(throw)|(try)|(typeof)|(var)|(void)|(while)|(with))$");
public static Supplier<JSSourceExtractor> factory = DomLessSourceExtractor::new;
protected interface IGeneratorCallback extends IHtmlCallback {
void writeToFinalRegion(SourceRegion finalRegion);
}
protected static class HtmlCallback implements IGeneratorCallback {
public static final boolean DEBUG = false;
protected final URL entrypointUrl;
protected final IUrlResolver urlResolver;
protected final SourceRegion scriptRegion;
protected final SourceRegion domRegion;
protected final SourceRegion entrypointRegion;
private ITag currentScriptTag;
private ITag currentCommentTag;
private int nodeCounter = 0;
private int scriptNodeCounter = 0;
public HtmlCallback(URL entrypointUrl, IUrlResolver urlResolver) {
this.entrypointUrl = entrypointUrl;
this.urlResolver = urlResolver;
this.scriptRegion = new SourceRegion();
this.domRegion = new SourceRegion();
this.entrypointRegion = new SourceRegion();
addDefaultHandlerInvocations();
}
protected void writeEntrypoint(String ep) {
entrypointRegion.println(ep);
}
protected void addDefaultHandlerInvocations() {
// always invoke window.onload
writeEntrypoint("window.onload();");
}
protected Position makePos(ITag governingTag) {
return governingTag.getElementPosition();
}
@Override
public void handleEndTag(ITag tag) {
if (tag.getName().equalsIgnoreCase("script")) {
assert currentScriptTag != null;
currentScriptTag = null;
} else if (currentScriptTag != null && tag.getName().equals("!--")) {
assert currentCommentTag != null;
currentCommentTag = null;
}
}
@Override
public void handleText(Position p, String text) {
if (currentScriptTag != null && currentCommentTag == null) {
if (text.startsWith("<![CDATA[")) {
assert text.endsWith("]]>");
text = text.substring(9, text.length() - 11);
}
URL url = entrypointUrl;
try {
url = new URL(entrypointUrl, "#" + scriptNodeCounter);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
scriptRegion.println(text, currentScriptTag.getContentPosition(), url, true);
}
}
@Override
public void handleStartTag(ITag tag) {
if (tag.getName().equalsIgnoreCase("script")) {
handleScript(tag);
assert currentScriptTag == null;
currentScriptTag = tag;
scriptNodeCounter++;
} else if (currentScriptTag != null && tag.getName().equals("!--")) {
currentCommentTag = tag;
}
handleDOM(tag);
}
private static boolean isUsableIdentifier(String x) {
return x != null
&& LEGAL_JS_IDENTIFIER_REGEXP.matcher(x).matches()
&& !LEGAL_JS_KEYWORD_REGEXP.matcher(x).matches();
}
/**
* Model the HTML DOM
*
* @param tag - the HTML tag to module
*/
protected void handleDOM(ITag tag) {
// Get the name of the modeling function either from the id attribute or a
// running counter
Pair<String, Position> idAttribute = tag.getAttributeByName("id");
String funcName;
if (idAttribute != null && isUsableIdentifier(idAttribute.fst)) {
funcName = idAttribute.fst;
} else {
funcName = "node" + nodeCounter++;
}
handleDOM(tag, funcName);
}
protected void handleDOM(ITag tag, String funcName) {
Map<String, Pair<String, Position>> attributeSet = tag.getAllAttributes();
for (Entry<String, Pair<String, Position>> a : attributeSet.entrySet()) {
handleAttribute(a, funcName, tag);
}
}
private void handleAttribute(
Entry<String, Pair<String, Position>> a, String funcName, ITag tag) {
URL url = entrypointUrl;
try {
url = new URL(entrypointUrl, "#" + tag.getElementPosition().getFirstOffset());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
if (DEBUG) {
e.printStackTrace();
}
}
Position pos = a.getValue().snd;
String attName = a.getKey();
String attValue = a.getValue().fst;
if (attName.toLowerCase().startsWith("on")
|| (attValue != null && attValue.toLowerCase().startsWith("javascript:"))) {
String fName = tag.getName().toLowerCase() + '_' + attName + '_' + funcName;
String signatureLine = "function " + fName + "(event) {";
// Defines the function
domRegion.println(signatureLine + '\n' + extructJS(attValue) + "\n}", pos, url, true);
// Run it
writeEntrypoint('\t' + fName + "(null);", pos, url, true);
}
}
protected void writeEntrypoint(String text, Position pos, URL url, boolean b) {
entrypointRegion.println(text, pos, url, b);
}
protected static Pair<String, Character> quotify(String value) {
char quote;
if (value.indexOf('"') < 0) {
quote = '"';
} else if (value.indexOf('\'') < 0) {
quote = '"';
} else {
quote = '"';
value = value.replaceAll("\"", "\\\"");
}
if (value.indexOf('\n') >= 0) {
value = value.replaceAll("\n", "\\n");
}
return Pair.make(value, quote);
}
private static String extructJS(String attValue) {
if (attValue == null) {
return "";
}
String content;
if (attValue.toLowerCase().equals("javascript:")) {
content = attValue.substring("javascript:".length());
} else {
content = attValue;
}
return content;
}
protected void handleScript(ITag tag) {
Pair<String, Position> content = tag.getAttributeByName("src");
try {
if (content != null) {
// script is out-of-line
getScriptFromUrl(content.fst, tag);
}
} catch (IOException e) {
if (DEBUG) {
System.err.println("Error reading script file: " + e.getMessage());
}
}
}
private void getScriptFromUrl(String urlAsString, ITag scriptTag)
throws IOException, MalformedURLException {
URL scriptSrc = new URL(entrypointUrl, urlAsString);
BOMInputStream bs;
try {
bs =
new BOMInputStream(
scriptSrc.openConnection().getInputStream(),
false,
ByteOrderMark.UTF_8,
ByteOrderMark.UTF_16LE,
ByteOrderMark.UTF_16BE,
ByteOrderMark.UTF_32LE,
ByteOrderMark.UTF_32BE);
if (bs.hasBOM()) {
System.err.println("removing BOM " + bs.getBOM());
}
} catch (Exception e) {
// it looks like this happens when we can't resolve the url?
if (DEBUG) {
System.err.println("Error reading script: " + scriptSrc);
System.err.println(e);
e.printStackTrace(System.err);
}
return;
}
try (final Reader scriptInputStream = new InputStreamReader(bs);
final BufferedReader scriptReader = new BufferedReader(scriptInputStream); ) {
String line;
StringBuilder x = new StringBuilder();
while ((line = scriptReader.readLine()) != null) {
x.append(line).append('\n');
}
scriptRegion.println(x.toString(), scriptTag.getElementPosition(), scriptSrc, false);
}
}
protected String getScriptName(URL url) {
String file = url.getFile();
int lastIdxOfSlash = file.lastIndexOf('/');
file = (lastIdxOfSlash == -1) ? file : file.substring(lastIdxOfSlash + 1);
return file;
}
protected void writeEventLoopHeader(SourceRegion finalRegion) {
finalRegion.println("while (true){ // event loop model");
}
@Override
public void writeToFinalRegion(SourceRegion finalRegion) {
// wrapping the embedded scripts with a fake method of the window. Required for making this ==
// window.
finalRegion.println("window.__MAIN__ = function __WINDOW_MAIN__(){");
finalRegion.write(scriptRegion);
finalRegion.write(domRegion);
finalRegion.println(" document.URL = new String(\"" + entrypointUrl + "\");");
writeEventLoopHeader(finalRegion);
finalRegion.write(entrypointRegion);
finalRegion.println("} // event loop model");
finalRegion.println("} // end of window.__MAIN__");
finalRegion.println("window.__MAIN__();");
}
}
/** for storing the name of the temp file created by extractSources() */
private File tempFile;
@Override
public Set<MappedSourceModule> extractSources(
URL entrypointUrl, IHtmlParser htmlParser, IUrlResolver urlResolver, Reader inputStreamReader)
throws IOException, Error {
IGeneratorCallback htmlCallback;
htmlCallback = createHtmlCallback(entrypointUrl, urlResolver);
htmlParser.parse(entrypointUrl, inputStreamReader, htmlCallback, entrypointUrl.getFile());
SourceRegion finalRegion = new SourceRegion();
htmlCallback.writeToFinalRegion(finalRegion);
// writing the final region into one SourceFileModule.
File outputFile = createOutputFile(entrypointUrl, DELETE_UPON_EXIT, USE_TEMP_NAME);
tempFile = outputFile;
FileMapping fileMapping;
try (final PrintWriter printer = new PrintWriter(new FileWriter(outputFile))) {
fileMapping = finalRegion.writeToFile(printer);
}
if (fileMapping == null) {
fileMapping = new EmptyFileMapping();
}
MappedSourceModule singleFileModule =
new MappedSourceFileModule(outputFile, outputFile.getName(), fileMapping);
return Collections.singleton(singleFileModule);
}
protected IGeneratorCallback createHtmlCallback(URL entrypointUrl, IUrlResolver urlResolver) {
return new HtmlCallback(entrypointUrl, urlResolver);
}
public static Path OUTPUT_FILE_DIRECTORY = Paths.get("");
private static File createOutputFile(URL url, boolean delete, boolean useTempName)
throws IOException {
File outputFile;
String fileName = new File(url.getPath()).getName();
if (fileName.length() < 5) {
fileName = "xxxx" + fileName;
}
fileName = OUTPUT_FILE_DIRECTORY.resolve(fileName).toString();
if (useTempName) {
outputFile = File.createTempFile(fileName, ".js");
} else {
outputFile = new File(fileName);
}
if (outputFile.exists()) {
outputFile.delete();
}
if (delete) {
outputFile.deleteOnExit();
}
return outputFile;
}
public static void main(String[] args) throws IOException, Error {
// DomLessSourceExtractor domLessScopeGenerator = new DomLessSourceExtractor();
JSSourceExtractor domLessScopeGenerator = new DefaultSourceExtractor();
JSSourceExtractor.DELETE_UPON_EXIT = false;
URL entrypointUrl = new URL(args[0]);
IHtmlParser htmlParser = new JerichoHtmlParser();
IUrlResolver urlResolver = new IdentityUrlResolver();
@SuppressWarnings("resource")
Set<MappedSourceModule> res =
domLessScopeGenerator.extractSources(
entrypointUrl, htmlParser, urlResolver, WebUtil.getStream(entrypointUrl));
MappedSourceModule entry = res.iterator().next();
System.out.println(entry);
System.out.println(entry.getMapping());
}
@Override
public File getTempFile() {
return tempFile;
}
}
| 13,260
| 32.743003
| 225
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/EmptyFileMapping.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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
public class EmptyFileMapping implements FileMapping {
@Override
public IncludedPosition getIncludedPosition(Position line) {
return null;
}
}
| 621
| 27.272727
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/FileMapping.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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
public interface FileMapping {
/** @return Null if no mapping for the given line. */
IncludedPosition getIncludedPosition(Position line);
}
| 612
| 29.65
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/IHtmlCallback.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
/**
* Callback which is implemented by users of the IHtmlParser. The parser traverses the dom-nodes in
* an in-order.
*
* @author danielk
* @author yinnonh
*/
public interface IHtmlCallback {
void handleStartTag(ITag tag);
void handleText(Position pos, String text);
void handleEndTag(ITag tag);
}
| 787
| 25.266667
| 99
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/IHtmlParser.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import java.io.Reader;
import java.net.URL;
/**
* @author danielk
* @author yinnonh Parses an HTML file using call backs
*/
public interface IHtmlParser {
/** Parses a given HTML, calling the given callback. */
void parse(URL url, Reader reader, IHtmlCallback callback, String fileName) throws Error;
}
| 786
| 29.269231
| 91
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/IHtmlParserFactory.java
|
/*
* Copyright (c) 2002 - 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.html;
@FunctionalInterface
public interface IHtmlParserFactory {
IHtmlParser getParser();
}
| 501
| 25.421053
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/ITag.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.util.collections.Pair;
import java.util.Map;
/**
* @author danielk Data structure representing an HTML tag, with its attributes and content. Used by
* the HTML parser when calling the callback.
*/
public interface ITag {
/** @return tag's name (e.g., "HEAD" / "HTML" / "FORM") */
String getName();
/**
* Retrieves a specific attribute
*
* @return null if there is no such attribute
*/
Pair<String, Position> getAttributeByName(String name);
Map<String, Pair<String, Position>> getAllAttributes();
/**
* Returns the starting line number of the tag.
*
* @return null if no known
*/
Position getElementPosition();
Position getContentPosition();
}
| 1,190
| 26.068182
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/IUrlResolver.java
|
/*
* Copyright (c) 2002 - 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.html;
import java.net.URL;
/**
* Used for handling resources that were copied from the web to local files (and still contain
* references to the web)
*
* @author yinnonh
* @author danielk
*/
public interface IUrlResolver {
/** From Internet to local */
URL resolve(URL input);
/** From local to Internet */
URL deResolve(URL input);
}
| 756
| 25.103448
| 94
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/IdentityUrlResolver.java
|
/*
* Copyright (c) 2002 - 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.html;
import java.net.URL;
public class IdentityUrlResolver implements IUrlResolver {
@Override
public URL resolve(URL input) {
return input;
}
@Override
public URL deResolve(URL input) {
return input;
}
}
| 634
| 22.518519
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/IncludedPosition.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
/**
* A {@link Position} for source code that has been included in some enclosing file, e.g.,
* JavaScript code included in an HTML file via a script node.
*/
public interface IncludedPosition extends Position {
/**
* get the position of the containing script within the enclosing file. E.g., for a position in
* JavaScript code included in an HTML file, returns the position of the relevant {@code <script>}
* tag in the HTML
*/
Position getIncludePosition();
}
| 957
| 33.214286
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/JSSourceExtractor.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.Set;
/**
* Extracts scripts from a given URL of an HTML. Retrieves also attached js files. Provides file and
* line mapping for each extracted SourceFileModule back to the original file and line number.
*
* @author yinnonh
* @author danielk
*/
public abstract class JSSourceExtractor {
public static boolean DELETE_UPON_EXIT = true;
public static boolean USE_TEMP_NAME = true;
/**
* Returns the temporary file created by a call to {@link #extractSources(URL, IHtmlParser,
* IUrlResolver, Reader)} which holds all the discovered JS source. If no such file exists,
* returns {@code null}
*/
public abstract File getTempFile();
public Set<MappedSourceModule> extractSources(
URL entrypointUrl, IHtmlParser htmlParser, IUrlResolver urlResolver)
throws IOException, Error {
try (Reader r = WebUtil.getStream(entrypointUrl)) {
return extractSources(entrypointUrl, htmlParser, urlResolver, r);
}
}
public abstract Set<MappedSourceModule> extractSources(
URL entrypointUrl, IHtmlParser htmlParser, IUrlResolver urlResolver, Reader reader)
throws IOException, Error;
}
| 1,720
| 32.096154
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/MappedSourceFileModule.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.classLoader.SourceFileModule;
import java.io.File;
public class MappedSourceFileModule extends SourceFileModule implements MappedSourceModule {
private final FileMapping fileMapping;
public MappedSourceFileModule(File f, String fileName, FileMapping fileMapping) {
super(f, fileName, null);
this.fileMapping = fileMapping;
}
public MappedSourceFileModule(File f, SourceFileModule clonedFrom, FileMapping fileMapping) {
super(f, clonedFrom);
this.fileMapping = fileMapping;
}
@Override
public FileMapping getMapping() {
return fileMapping;
}
}
| 1,014
| 28.852941
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/MappedSourceModule.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.classLoader.SourceModule;
public interface MappedSourceModule extends SourceModule {
FileMapping getMapping();
}
| 548
| 27.894737
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/NestedRangeMapping.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.html;
import com.ibm.wala.cast.js.html.RangeFileMapping.Range;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.impl.AbstractSourcePosition;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
public class NestedRangeMapping implements FileMapping {
private final Range range;
private final FileMapping innerMapping;
public NestedRangeMapping(
int rangeStart,
int rangeEnd,
int rangeStartingLine,
int rangeEndingLine,
FileMapping innerMapping) {
assert innerMapping != null;
this.range = new Range(rangeStart, rangeEnd, rangeStartingLine, rangeEndingLine);
this.innerMapping = innerMapping;
}
@Override
public IncludedPosition getIncludedPosition(final Position pos) {
if (range.includes(pos)) {
return innerMapping.getIncludedPosition(
new AbstractSourcePosition() {
@Override
public int getFirstLine() {
return pos.getFirstLine() - range.getStartingLine() + 1;
}
@Override
public int getLastLine() {
return pos.getLastLine() == -1
? -1
: (pos.getLastLine() - range.getStartingLine() + 1);
}
@Override
public int getFirstCol() {
return pos.getFirstCol();
}
@Override
public int getLastCol() {
return pos.getLastCol();
}
@Override
public int getFirstOffset() {
return pos.getFirstOffset() == -1 ? -1 : (pos.getFirstOffset() - range.getStart());
}
@Override
public int getLastOffset() {
return pos.getLastOffset() == -1 ? -1 : (pos.getLastOffset() - range.getStart());
}
@Override
public URL getURL() {
return pos.getURL();
}
@Override
public Reader getReader() throws IOException {
return pos.getReader();
}
});
} else {
return null;
}
}
@Override
public String toString() {
return range + "(" + innerMapping + ')';
}
}
| 2,638
| 27.684783
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/RangeFileMapping.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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.impl.AbstractSourcePosition;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
public class RangeFileMapping implements FileMapping {
public static final class Range {
private final int rangeStart;
private final int rangeEnd;
private final int rangeStartingLine;
private final int rangeEndingLine;
public boolean includes(Position offset) {
return offset.getFirstOffset() != -1
? rangeStart <= offset.getFirstOffset() && offset.getLastOffset() <= rangeEnd
: rangeStartingLine <= offset.getFirstLine()
&& (offset.getLastLine() == -1 ? offset.getFirstLine() : offset.getLastLine())
<= rangeEndingLine;
}
public Range(int rangeStart, int rangeEnd, int rangeStartingLine, int rangeEndingLine) {
super();
this.rangeStart = rangeStart;
this.rangeEnd = rangeEnd;
this.rangeStartingLine = rangeStartingLine;
this.rangeEndingLine = rangeEndingLine;
}
public int getStart() {
return rangeStart;
}
public int getEnd() {
return rangeEnd;
}
public int getStartingLine() {
return rangeStartingLine;
}
public int getEndingLine() {
return rangeEndingLine;
}
@Override
public String toString() {
return "{" + rangeStart + "->" + rangeEnd + '}';
}
}
private final Range range;
private final URL includedURL;
private final Position includePosition;
public RangeFileMapping(
int rangeStart,
int rangeEnd,
int rangeStartingLine,
int rangeEndingLine,
Position parentPosition,
URL url) {
assert parentPosition != null;
this.range = new Range(rangeStart, rangeEnd, rangeStartingLine, rangeEndingLine);
this.includePosition = parentPosition;
includedURL = url;
}
@Override
public String toString() {
return range + ":" + includePosition;
}
@Override
public IncludedPosition getIncludedPosition(final Position offset) {
if (range.includes(offset)) {
class Pos extends AbstractSourcePosition implements IncludedPosition {
@Override
public int getFirstLine() {
// line numbers are decreed to start at 1, rather than 0
return offset.getFirstLine() - range.getStartingLine() + 1;
}
@Override
public int getLastLine() {
return offset.getLastLine() == -1
? -1
: offset.getLastLine() - range.getStartingLine() + 1;
}
@Override
public int getFirstCol() {
return offset.getFirstCol();
}
@Override
public int getLastCol() {
return offset.getLastCol();
}
@Override
public int getFirstOffset() {
return offset.getFirstOffset() == -1 ? -1 : offset.getFirstOffset() - range.getStart();
}
@Override
public int getLastOffset() {
return offset.getLastOffset() == -1 ? -1 : offset.getLastOffset() - range.getStart();
}
@Override
public URL getURL() {
return includedURL;
}
@Override
public Reader getReader() throws IOException {
return RangeFileMapping.this.getInputStream();
}
@Override
public Position getIncludePosition() {
return includePosition;
}
@Override
public String toString() {
return "[include:" + includePosition + ']' + super.toString();
}
}
return new Pos();
} else {
return null;
}
}
public Reader getInputStream() throws IOException {
return new InputStreamReader(includedURL.openStream());
}
}
| 4,244
| 26.211538
| 97
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/SourceRegion.java
|
/*
* Copyright (c) 2002 - 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.html;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
/**
* Represents a region of source code, with source locations. Regions can be added to other {@link
* SourceRegion}s, with nested source location information maintained.
*/
public class SourceRegion {
private final StringBuilder source = new StringBuilder();
/** source location information */
private FileMapping fileMapping;
private int currentLine = 1;
public SourceRegion() {}
public void print(final String text, Position originalPos, URL url, boolean bogusURL) {
int startOffset = source.length();
source.append(text);
int endOffset = source.length();
int numberOfLineDrops = getNumberOfLineDrops(text);
if (originalPos != null) {
RangeFileMapping map;
if (bogusURL) {
map =
new RangeFileMapping(
startOffset,
endOffset,
currentLine,
currentLine + numberOfLineDrops,
originalPos,
url) {
@Override
public Reader getInputStream() throws IOException {
return new StringReader(text);
}
};
} else {
map =
new RangeFileMapping(
startOffset,
endOffset,
currentLine,
currentLine + numberOfLineDrops,
originalPos,
url);
}
if (fileMapping == null) {
fileMapping = map;
} else {
fileMapping = new CompositeFileMapping(map, fileMapping);
}
}
currentLine += numberOfLineDrops;
}
public void println(String text, Position originalPos, URL url, boolean bogusURL) {
print(text + '\n', originalPos, url, bogusURL);
}
public void print(String text) {
print(text, null, null, true);
}
public void println(String text) {
print(text + '\n');
}
public FileMapping writeToFile(PrintWriter ps) {
ps.print(source);
ps.flush();
return fileMapping;
}
public void write(SourceRegion otherRegion) {
int rangeStart = source.length();
String text = otherRegion.source.toString();
source.append(text);
int rangeEnd = source.length();
int numberOfLineDrops = getNumberOfLineDrops(text);
if (otherRegion.fileMapping != null) {
FileMapping map =
new NestedRangeMapping(
rangeStart,
rangeEnd,
currentLine,
currentLine + numberOfLineDrops,
otherRegion.fileMapping);
if (fileMapping == null) {
fileMapping = map;
} else {
fileMapping = new CompositeFileMapping(map, fileMapping);
}
}
currentLine += numberOfLineDrops;
}
public void dump(PrintWriter ps) {
ps.println(source);
}
private static int getNumberOfLineDrops(String text) {
int ret = 0;
int i = text.indexOf('\n');
while (i != -1) {
ret++;
if (i < text.length() - 1) {
i = text.indexOf('\n', i + 1);
} else {
break; // CR was the the last character.
}
}
return ret;
}
}
| 3,692
| 25.378571
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/UrlManipulator.java
|
/*
* Copyright (c) 2002 - 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.html;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlManipulator {
/**
* @param urlFound the link as appear
* @param context the URL in which the link appeared
*/
public static URL relativeToAbsoluteUrl(String urlFound, URL context)
throws MalformedURLException {
urlFound = urlFound.replace("\\", "/").toLowerCase();
URL absoluteUrl;
if (!isAbsoluteUrl(urlFound)) {
if (urlFound.startsWith("//")) {
// create URL taking only the protocol from the context
String origHostAndPath = urlFound.substring(2); // removing "//"
String host;
String path;
int indexOf = origHostAndPath.indexOf('/');
if (indexOf > 0) {
host = origHostAndPath.substring(0, indexOf);
path = origHostAndPath.substring(indexOf);
} else {
host = origHostAndPath;
path = "";
}
absoluteUrl = new URL(context.getProtocol(), host, path);
} else if (urlFound.startsWith("/")) {
// create URL taking the protocol and the host from the context
absoluteUrl = new URL(context.getProtocol(), context.getHost(), urlFound);
} else {
// "concat" URL to context
int backDir = 0; // removing directories due to "../"
while (urlFound.startsWith("../")) {
urlFound = urlFound.substring(3);
backDir++;
}
StringBuilder contextPath = new StringBuilder();
String path = context.getPath().replace("\\", "/");
boolean isContextDirectory = path.endsWith("/");
String[] split = path.split("/");
// we are also removing last element in case of a directory
int rightTrimFromPath = (isContextDirectory ? 0 : 1) + backDir;
for (int i = 0; i < split.length - rightTrimFromPath; i++) {
contextPath.append(split[i]);
contextPath.append('/');
}
absoluteUrl = new URL(context.getProtocol(), context.getHost(), contextPath + urlFound);
}
} else {
absoluteUrl = new URL(urlFound);
}
return absoluteUrl;
}
private static boolean isAbsoluteUrl(String orig) {
return orig.startsWith("http");
}
}
| 2,620
| 33.946667
| 96
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/WebPageLoaderFactory.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.html;
import com.ibm.wala.cast.ir.translator.TranslatorToIR;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
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.tree.CAst;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.cast.tree.visit.CAstVisitor;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.Pair;
import java.util.Set;
public class WebPageLoaderFactory extends JavaScriptLoaderFactory {
public WebPageLoaderFactory(JavaScriptTranslatorFactory factory) {
super(factory);
}
public WebPageLoaderFactory(
JavaScriptTranslatorFactory factory, CAstRewriterFactory<?, ?> preprocessor) {
super(factory, preprocessor);
}
@Override
protected IClassLoader makeTheLoader(IClassHierarchy cha) {
return new JavaScriptLoader(cha, translatorFactory, preprocessor) {
@Override
protected TranslatorToIR initTranslator(Set<Pair<CAstEntity, ModuleEntry>> topLevelEntitie) {
return new JSAstTranslator(this) {
private final CAst Ast = new CAstImpl();
private boolean isNestedWithinScriptBody(WalkContext context) {
return isScriptBody(context) || context.getName().contains("__WINDOW_MAIN__");
}
private boolean isScriptBody(WalkContext context) {
return context.top().getName().equals("__WINDOW_MAIN__");
}
@Override
protected int doGlobalRead(
CAstNode n, WalkContext context, String name, TypeReference type) {
int result = context.currentScope().allocateTempValue();
if (isNestedWithinScriptBody(context)
&& !"$$undefined".equals(name)
&& !"window".equals(name)
&& !name.startsWith("$$destructure")) {
// check if field is defined on 'window'
int windowVal =
isScriptBody(context)
? super.doLocalRead(context, "this", JavaScriptTypes.Root)
: super.doGlobalRead(n, context, "window", type);
int isDefined = context.currentScope().allocateTempValue();
context.currentScope().getConstantValue(name);
doIsFieldDefined(context, isDefined, windowVal, Ast.makeConstant(name));
context
.cfg()
.addInstruction(
insts.ConditionalBranchInstruction(
context.cfg().getCurrentInstruction(),
translateConditionOpcode(CAstOperator.OP_NE),
null,
isDefined,
context.currentScope().getConstantValue(0),
-1));
PreBasicBlock srcB = context.cfg().getCurrentBlock();
// field lookup of value
context.cfg().newBlock(true);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.GetInstruction(
context.cfg().getCurrentInstruction(), result, windowVal, name));
context.cfg().newBlock(true);
context
.cfg()
.addInstruction(insts.GotoInstruction(context.cfg().getCurrentInstruction(), -1));
PreBasicBlock trueB = context.cfg().getCurrentBlock();
// read global
context.cfg().newBlock(false);
PreBasicBlock falseB = context.cfg().getCurrentBlock();
int sr = super.doGlobalRead(n, context, name, type);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.AssignInstruction(context.cfg().getCurrentInstruction(), result, sr));
// end
context.cfg().newBlock(true);
context.cfg().addEdge(trueB, context.cfg().getCurrentBlock());
context.cfg().addEdge(srcB, falseB);
return result;
} else {
return super.doGlobalRead(n, context, name, type);
}
}
@Override
protected void doLocalWrite(
WalkContext context, String nm, TypeReference type, int rval) {
if (isNestedWithinScriptBody(context)
&& !"$$undefined".equals(nm)
&& !"window".equals(nm)
&& !nm.startsWith("$$destructure")) {
int windowVal = super.doLocalRead(context, "this", type);
context.currentScope().getConstantValue(nm);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.PutInstruction(
context.cfg().getCurrentInstruction(), windowVal, rval, nm));
}
super.doLocalWrite(context, nm, type, rval);
}
@Override
protected void leaveFunctionStmt(
CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) {
super.leaveFunctionStmt(n, context, visitor);
if (isScriptBody(context)) {
CAstEntity fn = (CAstEntity) n.getChild(0).getValue();
int fnValue = context.currentScope().lookup(fn.getName()).valueNumber();
assert fnValue > 0;
int windowVal = super.doLocalRead(context, "this", JavaScriptTypes.Function);
context
.cfg()
.addInstruction(
((JSInstructionFactory) insts)
.PutInstruction(
context.cfg().getCurrentInstruction(),
windowVal,
fnValue,
fn.getName()));
}
}
};
}
};
}
}
| 6,957
| 39.453488
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/WebUtil.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.html;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.html.jericho.JerichoHtmlParser;
import com.ibm.wala.util.collections.Pair;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Set;
import java.util.function.Supplier;
public class WebUtil {
public static final String preamble = "preamble.js";
private static IHtmlParserFactory factory = JerichoHtmlParser::new;
public static void setFactory(IHtmlParserFactory factory) {
WebUtil.factory = factory;
}
public static Pair<Set<MappedSourceModule>, File> extractScriptFromHTML(
URL url, Supplier<JSSourceExtractor> fSourceExtractor) throws Error {
try (Reader r = getStream(url)) {
return extractScriptFromHTML(url, fSourceExtractor, r);
} catch (IOException e) {
throw new RuntimeException("trouble with " + url, e);
}
}
/**
* @return a pair (S,F), where S is a set of extracted sources, and F is the temp file holding the
* combined sources (or {@code null} if no such file exists)
*/
public static Pair<Set<MappedSourceModule>, File> extractScriptFromHTML(
URL url, Supplier<JSSourceExtractor> fSourceExtractor, Reader r) throws Error {
try {
JSSourceExtractor extractor = fSourceExtractor.get();
Set<MappedSourceModule> sources =
extractor.extractSources(url, factory.getParser(), new IdentityUrlResolver(), r);
return Pair.make(sources, extractor.getTempFile());
} catch (IOException e) {
throw new RuntimeException("trouble with " + url, e);
}
}
public static void main(String[] args) throws MalformedURLException, Error {
System.err.println(
extractScriptFromHTML(
new URL(args[0]),
Boolean.parseBoolean(args[1])
? DefaultSourceExtractor.factory
: DomLessSourceExtractor.factory));
}
public static Reader getStream(URL url) throws IOException {
URLConnection conn = url.openConnection();
conn.setDefaultUseCaches(false);
conn.setUseCaches(false);
return new InputStreamReader(conn.getInputStream());
}
}
| 2,689
| 33.487179
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/jericho/JerichoHtmlParser.java
|
/*
* Copyright (c) 2002 - 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.html.jericho;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.js.html.IHtmlCallback;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.List;
import java.util.Set;
import net.htmlparser.jericho.Config;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Logger;
import net.htmlparser.jericho.LoggerProvider;
import net.htmlparser.jericho.Source;
/** @author danielk Uses the Jericho parser to go over the HTML */
public class JerichoHtmlParser implements IHtmlParser {
static Set<Warning> warnings = HashSetFactory.make();
static {
class CAstLoggerProvider implements LoggerProvider {
@Override
public Logger getLogger(String arg0) {
class CAstLogger implements Logger {
@Override
public void debug(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void error(final String arg0) {
warnings.add(
new Warning() {
@Override
public String getMsg() {
return arg0;
}
});
}
@Override
public void info(String arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean isDebugEnabled() {
return true;
}
@Override
public boolean isErrorEnabled() {
return true;
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public void warn(String arg0) {
// TODO Auto-generated method stub
}
}
return new CAstLogger();
}
}
Config.LoggerProvider = new CAstLoggerProvider();
}
@Override
public void parse(URL url, Reader reader, IHtmlCallback callback, String fileName)
throws TranslatorToCAst.Error {
warnings.clear();
Parser parser = new Parser(callback, fileName);
Source src;
try {
src = new Source(reader);
src.setLogger(Config.LoggerProvider.getLogger(fileName));
List<Element> childElements = src.getChildElements();
for (Element e : childElements) {
parser.parse(e);
}
if (!warnings.isEmpty()) {
throw new TranslatorToCAst.Error(warnings);
}
} catch (IOException e) {
System.err.println("Error parsing file: " + e.getMessage());
}
}
/** @author danielk Inner class does the actual traversal of the HTML using recursion */
private static class Parser {
private final IHtmlCallback handler;
private final String fileName;
public Parser(IHtmlCallback handler, String fileName) {
this.handler = handler;
this.fileName = fileName;
}
private void parse(Element root) {
JerichoTag tag = new JerichoTag(root, fileName);
handler.handleStartTag(tag);
handler.handleText(tag.getElementPosition(), tag.getBodyText().snd);
List<Element> childElements = root.getChildElements();
for (Element child : childElements) {
parse(child);
}
handler.handleEndTag(tag);
}
}
}
| 3,897
| 27.246377
| 90
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/html/jericho/JerichoTag.java
|
/*
* Copyright (c) 2002 - 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.html.jericho;
import com.ibm.wala.cast.js.html.ITag;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.impl.AbstractSourcePosition;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.Segment;
/**
* ITag impel for Jericho generated tags
*
* @author danielk
*/
public class JerichoTag implements ITag {
private final Element innerElement;
private final String sourceFile;
private Map<String, Pair<String, Position>> allAttributes = null;
public JerichoTag(Element root, String sourceFile) {
this.innerElement = root;
this.sourceFile = sourceFile;
}
private Position getPosition(final Segment e) {
return new AbstractSourcePosition() {
@Override
public int getFirstLine() {
return e.getSource().getRowColumnVector(e.getBegin()).getRow();
}
@Override
public int getLastLine() {
return e.getSource().getRowColumnVector(e.getEnd()).getRow();
}
@Override
public int getFirstCol() {
return -1;
// return e.getSource().getRowColumnVector(e.getBegin()).getColumn();
}
@Override
public int getLastCol() {
return -1;
// return e.getSource().getRowColumnVector(e.getEnd()).getColumn();
}
@Override
public int getFirstOffset() {
return e.getBegin();
}
@Override
public int getLastOffset() {
return e.getEnd();
}
@Override
public URL getURL() {
try {
return new URL("file://" + sourceFile);
} catch (MalformedURLException e) {
return null;
}
}
@Override
public Reader getReader() throws IOException {
return new FileReader(sourceFile);
}
};
}
private Map<String, Pair<String, Position>> makeAllAttributes() {
Map<String, Pair<String, Position>> result = HashMapFactory.make();
if (innerElement.getStartTag().getAttributes() != null) {
for (Attribute a : innerElement.getStartTag().getAttributes()) {
result.put(
a.getName().toLowerCase(), Pair.make(a.getValue(), getPosition(a.getValueSegment())));
}
}
return result;
}
@Override
public Map<String, Pair<String, Position>> getAllAttributes() {
if (allAttributes == null) {
allAttributes = makeAllAttributes();
}
return allAttributes;
}
@Override
public Pair<String, Position> getAttributeByName(String name) {
if (allAttributes == null) {
allAttributes = makeAllAttributes();
}
return allAttributes.get(name.toLowerCase());
}
public Pair<Integer, String> getBodyText() {
Segment content = innerElement.getContent();
Integer lineNum = innerElement.getSource().getRow(content.getBegin());
String nl = content.getSource().getNewLine();
String body = nl == null ? content.toString() : content.toString().replace(nl, "\n");
return Pair.make(lineNum, body);
}
public String getFilePath() {
return sourceFile;
}
@Override
public String getName() {
return innerElement.getName();
}
@Override
public String toString() {
return innerElement.toString();
}
@Override
public Position getElementPosition() {
return getPosition(innerElement);
}
@Override
public Position getContentPosition() {
return getPosition(innerElement.getContent());
}
}
| 4,114
| 25.720779
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/ArgumentSpecialization.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.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.translator.JSAstTranslator;
import com.ibm.wala.cast.js.translator.JSConstantFoldingRewriter;
import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation;
import com.ibm.wala.cast.loader.AstMethod.Retranslatable;
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.impl.CAstImpl;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NonCopyingContext;
import com.ibm.wala.cast.util.CAstPattern;
import com.ibm.wala.cast.util.CAstPattern.Segments;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
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.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextItem.Value;
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.InstanceKey;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.IntSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ArgumentSpecialization {
public static class ArgumentSpecializationContextIntepreter
extends AstContextInsensitiveSSAContextInterpreter {
public ArgumentSpecializationContextIntepreter(
AnalysisOptions options, IAnalysisCacheView cache) {
super(options, cache);
}
@Override
public IR getIR(CGNode node) {
if (node.getMethod() instanceof Retranslatable) {
return getAnalysisCache().getIR(node.getMethod(), node.getContext());
} else {
return super.getIR(node);
}
}
@Override
public DefUse getDU(CGNode node) {
if (node.getMethod() instanceof Retranslatable) {
return getAnalysisCache().getDefUse(getIR(node));
} else {
return super.getDU(node);
}
}
}
public static class ArgumentCountContext implements Context {
private final Context base;
private final int argumentCount;
public static ContextKey ARGUMENT_COUNT =
new ContextKey() {
@Override
public String toString() {
return "argument count key";
}
};
@Override
public int hashCode() {
return base.hashCode() + (argumentCount * 4073);
}
@Override
public boolean equals(Object o) {
return o.getClass() == this.getClass()
&& base.equals(((ArgumentCountContext) o).base)
&& argumentCount == ((ArgumentCountContext) o).argumentCount;
}
public ArgumentCountContext(int argumentCount, Context base) {
this.argumentCount = argumentCount;
this.base = base;
}
@Override
public ContextItem get(ContextKey name) {
return (name == ARGUMENT_COUNT) ? ContextItem.Value.make(argumentCount) : base.get(name);
}
@Override
public String toString() {
return base.toString() + "(nargs:" + argumentCount + ')';
}
}
public static class ArgumentCountContextSelector implements ContextSelector, ContextKey {
private final ContextSelector base;
public ArgumentCountContextSelector(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);
if (caller.getMethod() instanceof Retranslatable) {
int v = -1;
for (SSAAbstractInvokeInstruction x : caller.getIR().getCalls(site)) {
if (v == -1) {
v = x.getNumberOfPositionalParameters();
} else {
if (v != x.getNumberOfPositionalParameters()) {
return baseContext;
}
}
}
return new ArgumentCountContext(v, baseContext);
} else {
return baseContext;
}
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return base.getRelevantParameters(caller, site);
}
}
public static class ArgumentCountIRFactory extends AstIRFactory.AstDefaultIRFactory<IMethod> {
private static final CAstPattern directAccessPattern =
CAstPattern.parse(
"|(ARRAY_REF(VAR(\"arguments\"),<value>*)||OBJECT_REF(VAR(\"arguments\"),<value>*))|");
private static final CAstPattern destructuredAccessPattern =
CAstPattern.parse(
"BLOCK_EXPR(ASSIGN(VAR(/[$][$]destructure[$]rcvr[0-9]+/),VAR(\"arguments\")),ASSIGN(VAR(<name>/[$][$]destructure[$]elt[0-9]+/),<value>*))");
private static final CAstPattern destructuredCallPattern =
CAstPattern.parse(
"CALL(VAR(<name>/[$][$]destructure[$]elt[0-9]+/),\"dispatch\",VAR(<thisptr>/[$][$]destructure[$]rcvr[0-9]+/),<args>**)");
private final SSAOptions defaultOptions;
public ArgumentCountIRFactory(SSAOptions defaultOptions) {
this.defaultOptions = defaultOptions;
}
@Override
public boolean contextIsIrrelevant(IMethod method) {
return method instanceof Retranslatable ? false : super.contextIsIrrelevant(method);
}
@Override
public IR makeIR(final IMethod method, Context context, SSAOptions options) {
if (method instanceof Retranslatable) {
@SuppressWarnings("unchecked")
final Value<Integer> v = (Value<Integer>) context.get(ArgumentCountContext.ARGUMENT_COUNT);
final Retranslatable m = (Retranslatable) method;
if (v != null) {
final JavaScriptLoader myloader =
(JavaScriptLoader) method.getDeclaringClass().getClassLoader();
class FixedArgumentsRewriter extends CAstBasicRewriter<NonCopyingContext> {
private final CAstEntity e;
private final Map<String, CAstNode> argRefs = HashMapFactory.make();
public FixedArgumentsRewriter(CAst Ast) {
super(Ast, new NonCopyingContext(), false);
this.e = m.getEntity();
for (Segments s : CAstPattern.findAll(destructuredAccessPattern, m.getEntity())) {
argRefs.put(s.getSingle("name").getValue().toString(), s.getSingle("value"));
}
}
private CAstNode handleArgumentRef(CAstNode n) {
Object x = n.getValue();
if (x != null) {
if (x instanceof Number && ((Number) x).intValue() < v.getValue() - 2) {
int arg = ((Number) x).intValue() + 2;
if (arg < e.getArgumentCount()) {
return Ast.makeNode(CAstNode.VAR, Ast.makeConstant(e.getArgumentNames()[arg]));
} else {
return Ast.makeNode(CAstNode.VAR, Ast.makeConstant("$arg" + arg));
}
} else if (x instanceof String && "length".equals(x)) {
return Ast.makeConstant(v.getValue());
}
}
return null;
}
@Override
protected CAstNode copyNodes(
CAstNode root,
CAstControlFlowMap cfg,
NonCopyingContext context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
CAstNode result = null;
Segments s;
if ((s = CAstPattern.match(directAccessPattern, root)) != null) {
result = handleArgumentRef(s.getSingle("value"));
} else if ((s = CAstPattern.match(destructuredCallPattern, root)) != null) {
if (argRefs.containsKey(s.getSingle("name").getValue().toString())) {
List<CAstNode> x = new ArrayList<>();
CAstNode ref =
handleArgumentRef(argRefs.get(s.getSingle("name").getValue().toString()));
if (ref != null) {
x.add(ref);
x.add(Ast.makeConstant("do"));
x.add(Ast.makeNode(CAstNode.VAR, Ast.makeConstant("arguments")));
for (CAstNode c : s.getMultiple("args")) {
x.add(copyNodes(c, cfg, context, nodeMap));
}
result = Ast.makeNode(CAstNode.CALL, x);
}
}
} else if (root.getKind() == CAstNode.CONSTANT) {
result = Ast.makeConstant(root.getValue());
} else if (root.getKind() == CAstNode.OPERATOR) {
result = root;
}
if (result == null) {
final List<CAstNode> children =
copyChildrenArrayAndTargets(root, cfg, context, nodeMap);
CAstNode copy = Ast.makeNode(root.getKind(), children);
result = copy;
}
nodeMap.put(Pair.make(root, context.key()), result);
return result;
}
}
final FixedArgumentsRewriter args = new FixedArgumentsRewriter(new CAstImpl());
final JSConstantFoldingRewriter fold = new JSConstantFoldingRewriter(new CAstImpl());
class ArgumentativeTranslator extends JSAstTranslator {
public ArgumentativeTranslator(JavaScriptLoader loader) {
super(loader);
}
private CAstEntity codeBodyEntity;
private IMethod specializedCode;
@Override
protected int getArgumentCount(CAstEntity f) {
return Math.max(super.getArgumentCount(f), v.getValue());
}
@Override
protected String[] getArgumentNames(CAstEntity f) {
if (super.getArgumentCount(f) >= v.getValue()) {
return super.getArgumentNames(f);
} else {
String[] argNames = new String[v.getValue()];
System.arraycopy(
super.getArgumentNames(f), 0, argNames, 0, super.getArgumentCount(f));
for (int i = super.getArgumentCount(f); i < argNames.length; i++) {
argNames[i] = "$arg" + i;
}
return argNames;
}
}
@Override
protected String composeEntityName(WalkContext parent, CAstEntity f) {
if (f == codeBodyEntity) {
return super.composeEntityName(parent, f) + '_' + v.getValue();
} else {
return super.composeEntityName(parent, f);
}
}
@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 (N == codeBodyEntity) {
specializedCode =
myloader.makeCodeBodyCode(
cfg,
symtab,
hasCatchBlock,
caughtTypes,
hasMonitorOp,
LI,
debugInfo,
method.getDeclaringClass());
} else {
super.defineFunction(
N,
definingContext,
cfg,
symtab,
hasCatchBlock,
caughtTypes,
hasMonitorOp,
LI,
debugInfo);
}
}
@Override
public void translate(CAstEntity N, WalkContext context) {
if (N == m.getEntity()) {
codeBodyEntity = fold.rewrite(args.rewrite(N));
super.translate(codeBodyEntity, context);
} else {
super.translate(N, context);
}
}
}
ArgumentativeTranslator a = new ArgumentativeTranslator(myloader);
m.retranslate(a);
return super.makeIR(a.specializedCode, context, options);
}
}
return super.makeIR(method, context, options);
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> makeCFG(
IMethod method, Context context) {
return makeIR(method, context, defaultOptions).getControlFlowGraph();
}
}
}
| 14,002
| 36.143236
| 152
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSAnalysisOptions.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.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.Entrypoint;
/** call graph construction options specific to JavaScript. */
public class JSAnalysisOptions extends AnalysisOptions {
/**
* should the analysis model the semantics of Function.prototype.call / apply? Defaults to true.
*/
private boolean handleCallApply = true;
private boolean useLoadFileTargetSelector = true;
public JSAnalysisOptions(AnalysisScope scope, Iterable<? extends Entrypoint> e) {
super(scope, e);
}
/** should the analysis model the semantics of Function.prototype.call / apply? */
public boolean handleCallApply() {
return handleCallApply;
}
public void setHandleCallApply(boolean handleCallApply) {
this.handleCallApply = handleCallApply;
}
public boolean useLoadFileTargetSelector() {
return useLoadFileTargetSelector;
}
public void setUseLoadFileTargetSelector(boolean useIt) {
this.useLoadFileTargetSelector = useIt;
}
}
| 1,462
| 29.479167
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSCFABuilder.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.AstCFAPointerKeys;
import com.ibm.wala.cast.ipa.callgraph.ReflectedFieldPointerKey;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import java.util.Iterator;
/** Common utilities for CFA-style call graph builders. */
public abstract class JSCFABuilder extends JSSSAPropagationCallGraphBuilder {
public JSCFABuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(
JavaScriptLoader.JS.getFakeRootMethod(cha, options, cache),
options,
cache,
new AstCFAPointerKeys() {
private boolean isBogusKey(InstanceKey K) {
TypeReference t = K.getConcreteType().getReference();
return t == JavaScriptTypes.Null || t == JavaScriptTypes.Undefined;
}
@Override
public PointerKey getPointerKeyForObjectCatalog(InstanceKey I) {
if (isBogusKey(I)) {
return null;
} else {
return super.getPointerKeyForObjectCatalog(I);
}
}
@Override
public PointerKey getPointerKeyForInstanceField(InstanceKey I, IField f) {
if (isBogusKey(I)) {
return null;
} else {
return super.getPointerKeyForInstanceField(I, f);
}
}
@Override
public PointerKey getPointerKeyForArrayContents(InstanceKey I) {
if (isBogusKey(I)) {
return null;
} else {
return super.getPointerKeyForArrayContents(I);
}
}
@Override
public Iterator<PointerKey> getPointerKeysForReflectedFieldRead(
InstanceKey I, InstanceKey F) {
if (isBogusKey(I)) {
return EmptyIterator.instance();
} else {
return super.getPointerKeysForReflectedFieldRead(I, F);
}
}
@Override
public Iterator<PointerKey> getPointerKeysForReflectedFieldWrite(
InstanceKey I, InstanceKey F) {
if (isBogusKey(I)) {
return EmptyIterator.instance();
} else {
return super.getPointerKeysForReflectedFieldWrite(I, F);
}
}
@Override
protected PointerKey getInstanceFieldPointerKeyForConstant(
InstanceKey I, ConstantKey<?> F) {
Object v = F.getValue();
String strVal = JSCallGraphUtil.simulateToStringForPropertyNames(v);
// if we know the string representation of the constant, use it...
if (strVal != null) {
IField f = I.getConcreteType().getField(Atom.findOrCreateUnicodeAtom(strVal));
return getPointerKeyForInstanceField(I, f);
// ...otherwise it is some unknown string
} else {
return ReflectedFieldPointerKey.mapped(new ConcreteTypeKey(getFieldNameType(F)), I);
}
}
/**
* All values used as property names get implicitly converted to strings in JavaScript.
*/
@Override
protected IClass getFieldNameType(InstanceKey F) {
return F.getConcreteType().getClassHierarchy().lookupClass(JavaScriptTypes.String);
}
});
}
}
| 4,417
| 36.12605
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSCallGraph.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.AstCallGraph;
import com.ibm.wala.cast.js.cfg.JSInducedCFG;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
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.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
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.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Set;
public class JSCallGraph extends AstCallGraph {
public JSCallGraph(IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache) {
super(fakeRootClass, options, cache);
}
public static final MethodReference fakeRoot =
MethodReference.findOrCreate(
JavaScriptTypes.FakeRoot, FakeRootMethod.name, FakeRootMethod.descr);
public static class JSFakeRoot extends ScriptFakeRoot {
public JSFakeRoot(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(fakeRoot, cha.lookupClass(JavaScriptTypes.FakeRoot), cha, options, cache);
}
@Override
public InducedCFG makeControlFlowGraph(SSAInstruction[] instructions) {
return new JSInducedCFG(instructions, this, Everywhere.EVERYWHERE);
}
@Override
public SSAAbstractInvokeInstruction addDirectCall(
int function, int[] params, CallSiteReference site) {
CallSiteReference newSite =
new DynamicCallSiteReference(JavaScriptTypes.CodeBody, statements.size());
JavaScriptInvoke s =
new JavaScriptInvoke(
statements.size(), function, nextLocal++, params, nextLocal++, newSite);
statements.add(s);
return s;
}
}
@Override
protected CGNode makeFakeWorldClinitNode() {
return null;
}
@Override
protected CGNode makeFakeRootNode() throws com.ibm.wala.util.CancelException {
return findOrCreateNode(
new JSFakeRoot(cha, options, getAnalysisCache()), Everywhere.EVERYWHERE);
}
@Override
public Set<CGNode> getNodes(MethodReference m) {
if (m.getName().equals(JavaScriptMethods.ctorAtom)) {
// TODO cache this?
Set<CGNode> result = HashSetFactory.make(1);
for (CGNode n : this) {
IMethod method = n.getMethod();
if (method.getName().equals(JavaScriptMethods.ctorAtom)
&& method.getDeclaringClass().getReference().equals(m.getDeclaringClass())) {
result.add(n);
}
}
return result;
} else {
return super.getNodes(m);
}
}
}
| 3,432
| 33.676768
| 96
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSCallGraphUtil.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.CAstCallGraphUtil;
import com.ibm.wala.cast.ipa.callgraph.StandardFunctionTargetSelector;
import com.ibm.wala.cast.ir.translator.AstTranslator;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.loader.JavaScriptLoaderFactory;
import com.ibm.wala.cast.js.translator.JSAstTranslator;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
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.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.cast.tree.visit.CAstVisitor;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.cast.util.CAstPrinter;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.ClassLoaderFactory;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.Module;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.SourceModule;
import com.ibm.wala.classLoader.SourceURLModule;
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.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.ClassHierarchyClassTargetSelector;
import com.ibm.wala.ipa.callgraph.impl.ClassHierarchyMethodTargetSelector;
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.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.collections.NonNullSingletonIterator;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class JSCallGraphUtil extends com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil {
private static final boolean DEBUG = false;
/**
* the translator factory to be used for analysis TODO: pass the factory where needed instead of
* using a global?
*/
public static JavaScriptTranslatorFactory translatorFactory;
/**
* Set up the translator factory. This method should be called before invoking {@link
* #makeLoaders()}.
*/
public static void setTranslatorFactory(JavaScriptTranslatorFactory translatorFactory) {
JSCallGraphUtil.translatorFactory = translatorFactory;
}
public static JavaScriptTranslatorFactory getTranslatorFactory() {
return translatorFactory;
}
public static JSAnalysisOptions makeOptions(
AnalysisScope scope, IClassHierarchy cha, Iterable<Entrypoint> roots) {
final JSAnalysisOptions options = new JSAnalysisOptions(scope, /*
* AstIRFactory.
* makeDefaultFactory
* (keepIRs),
*/ roots);
options.setSelector(new ClassHierarchyMethodTargetSelector(cha));
options.setSelector(new ClassHierarchyClassTargetSelector(cha));
options.setSelector(new StandardFunctionTargetSelector(cha, options.getMethodTargetSelector()));
options.setUseConstantSpecificKeys(true);
options.setUseStacksForLexicalScoping(true);
return options;
}
/**
* @param preprocessor CAst rewriter to use for preprocessing JavaScript source files; may be null
*/
public static JavaScriptLoaderFactory makeLoaders(CAstRewriterFactory<?, ?> preprocessor) {
if (translatorFactory == null) {
throw new IllegalStateException(
"com.ibm.wala.cast.js.ipa.callgraph.Util.setTranslatorFactory() must be invoked before makeLoaders()");
}
return new JavaScriptLoaderFactory(translatorFactory, preprocessor);
}
public static JavaScriptLoaderFactory makeLoaders() {
return makeLoaders(null);
}
public static IClassHierarchy makeHierarchyForScripts(String... scriptFiles)
throws ClassHierarchyException {
JavaScriptLoaderFactory loaders = makeLoaders();
AnalysisScope scope = CAstCallGraphUtil.makeScope(scriptFiles, loaders, JavaScriptLoader.JS);
return makeHierarchy(scope, loaders);
}
public static IClassHierarchy makeHierarchy(AnalysisScope scope, ClassLoaderFactory loaders)
throws ClassHierarchyException {
return ClassHierarchyFactory.make(scope, loaders, JavaScriptLoader.JS);
}
public static JavaScriptEntryPoints makeScriptRoots(IClassHierarchy cha) {
return new JavaScriptEntryPoints(cha, cha.getLoader(JavaScriptTypes.jsLoader));
}
/**
* Get all the nodes in CG with name funName. If funName is of the form {@code "ctor:nm"}, return
* nodes corresponding to constructor function for {@code nm}. If funName is of the form {@code
* "suffix:nm"}, return nodes corresponding to functions whose names end with {@code nm}.
* Otherwise, return nodes for functions whose name matches funName exactly.
*/
public static Collection<CGNode> getNodes(CallGraph CG, String funName) {
boolean suffix = funName.startsWith("suffix:");
if (suffix) {
Set<CGNode> nodes = new HashSet<>();
String tail = funName.substring(7);
for (CGNode n : CG) {
if (n.getMethod().getReference().getDeclaringClass().getName().toString().endsWith(tail)) {
nodes.add(n);
}
}
return nodes;
}
MethodReference MR = getMethodReference(funName);
return CG.getNodes(MR);
}
public static MethodReference getMethodReference(String funName) {
boolean ctor = funName.startsWith("ctor:");
MethodReference MR;
if (ctor) {
TypeReference TR =
TypeReference.findOrCreate(
JavaScriptTypes.jsLoader, TypeName.string2TypeName('L' + funName.substring(5)));
MR = JavaScriptMethods.makeCtorReference(TR);
} else {
TypeReference TR =
TypeReference.findOrCreate(
JavaScriptTypes.jsLoader, TypeName.string2TypeName('L' + funName));
MR = AstMethodReference.fnReference(TR);
}
return MR;
}
/** @return The set of class names that where defined in the CHA as a result loading process. */
public static Set<String> loadAdditionalFile(IClassHierarchy cha, JavaScriptLoader cl, URL url)
throws IOException {
return loadAdditionalFile(cha, cl, new SourceURLModule(url));
}
public static Set<String> loadAdditionalFile(
IClassHierarchy cha, JavaScriptLoader cl, ModuleEntry M) throws IOException {
try {
TranslatorToCAst toCAst = getTranslatorFactory().make(new CAstImpl(), M);
final Set<String> names = new HashSet<>();
AstTranslator toIR =
new JSAstTranslator(cl) {
@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) {
String fnName = 'L' + composeEntityName(definingContext, N);
names.add(fnName);
super.defineFunction(
N,
definingContext,
cfg,
symtab,
hasCatchBlock,
caughtTypes,
hasMonitorOp,
LI,
debugInfo);
}
@Override
protected void leaveFunctionStmt(
CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) {
CAstEntity fn = (CAstEntity) n.getChild(0).getValue();
Scope cs = c.currentScope();
if (!cs.contains(fn.getName())
|| cs.lookup(fn.getName()).getDefiningScope().getEntity().getKind()
== CAstEntity.SCRIPT_ENTITY) {
int result = processFunctionExpr(n, c);
assignValue(n, c, cs.lookup(fn.getName()), fn.getName(), result);
} else {
super.leaveFunctionStmt(n, c, visitor);
}
}
};
CAstEntity tree;
try {
tree = toCAst.translateToCAst();
if (DEBUG) {
CAstPrinter.printTo(tree, new PrintWriter(System.err));
}
toIR.translate(tree, M);
for (String name : names) {
IClass fcls = cl.lookupClass(name, cha);
cha.addClass(fcls);
}
return names;
} catch (Error e) {
return Collections.emptySet();
}
} catch (RuntimeException e) {
return Collections.emptySet();
}
}
public static String simulateToStringForPropertyNames(Object v) {
// TODO this is very incomplete --MS
if (v instanceof String) {
return (String) v;
} else if (v instanceof Double) {
String result = v.toString();
if (Math.round((Double) v) == (Double) v) {
result = Long.toString(Math.round((Double) v));
}
return result;
} else if (v instanceof Boolean) {
if ((Boolean) v) {
return "true";
} else {
return "false";
}
} else {
return null;
}
}
public static class Bootstrap implements SourceModule {
private final String name;
private final InputStream stream;
private final URL url;
public Bootstrap(String name, InputStream stream, URL url) {
this.name = name;
this.stream = stream;
this.url = url;
}
@Override
public Iterator<? extends ModuleEntry> getEntries() {
return new NonNullSingletonIterator<>(this);
}
@Override
public boolean isClassFile() {
return false;
}
@Override
public boolean isSourceFile() {
return true;
}
@Override
public InputStream getInputStream() {
return stream;
}
@Override
public boolean isModuleFile() {
return false;
}
@Override
public Module asModule() {
return this;
}
@Override
public String getClassName() {
return getName();
}
@Override
public Module getContainer() {
return null;
}
@Override
public String getName() {
return name;
}
@Override
public Reader getInputReader() {
// TODO Auto-generated method stub
return null;
}
@Override
public URL getURL() {
return url;
}
}
@SuppressWarnings("resource")
public static Module getPrologueFile(final String name) {
return new Bootstrap(
name,
JSCallGraphUtil.class.getClassLoader().getResourceAsStream(name),
JSCallGraphUtil.class.getClassLoader().getResource(name));
}
}
| 12,009
| 33.119318
| 113
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSSSAPropagationCallGraphBuilder.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.analysis.typeInference.TypeInference;
import com.ibm.wala.cast.ipa.callgraph.AstSSAPropagationCallGraphBuilder;
import com.ibm.wala.cast.ipa.callgraph.GlobalObjectKey;
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.CAstBinaryOp;
import com.ibm.wala.cast.ir.ssa.CAstUnaryOp;
import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction;
import com.ibm.wala.cast.js.analysis.typeInference.JSTypeInference;
import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder.JSPointerAnalysisImpl.JSImplicitPointsToSetVisitor;
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.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.util.CancelRuntimeException;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.fixpoint.AbstractOperator;
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.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
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.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.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.BinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.IOperator;
import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.SSAAbstractBinaryInstruction;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Set;
/**
* Specialized pointer analysis constraint generation for JavaScript.
*
* <h2>Global object handling</h2>
*
* The global object is represented by a {@link GlobalObjectKey} stored in {@link #globalObject}.
* {@link AstGlobalRead} and {@link AstGlobalWrite} instructions are treated as accessing properties
* of the global object; see {@link JSConstraintVisitor#visitAstGlobalRead(AstGlobalRead)}, {@link
* JSConstraintVisitor#visitAstGlobalWrite(AstGlobalWrite)}, and {@link
* JSImplicitPointsToSetVisitor#visitAstGlobalRead(AstGlobalRead)}. Finally, we need to represent
* direct flow of the global object to handle receiver argument semantics (see {@link
* com.ibm.wala.cast.js.translator.RhinoToAstTranslator}). To do so, we create a reference to a
* global named {@link #GLOBAL_OBJ_VAR_NAME}, which is handled specially in {@link
* JSConstraintVisitor#visitAstGlobalRead(AstGlobalRead)}.
*/
@SuppressWarnings({"javadoc", "JavadocReference"})
public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraphBuilder {
public static final boolean DEBUG_LEXICAL = false;
public static final boolean DEBUG_TYPE_INFERENCE = false;
/** name to be used internally to pass around the global object */
public static final String GLOBAL_OBJ_VAR_NAME = "__WALA__int3rnal__global";
private final GlobalObjectKey globalObject;
@Override
public GlobalObjectKey getGlobalObject(Atom language) {
assert language.equals(JavaScriptTypes.jsName);
return globalObject;
}
/** is field a direct (WALA-internal) reference to the global object? */
private static boolean directGlobalObjectRef(FieldReference field) {
return field.getName().toString().endsWith(GLOBAL_OBJ_VAR_NAME);
}
private static FieldReference makeNonGlobalFieldReference(FieldReference field) {
String nonGlobalFieldName = field.getName().toString().substring(7);
field =
FieldReference.findOrCreate(
JavaScriptTypes.Root,
Atom.findOrCreateUnicodeAtom(nonGlobalFieldName),
JavaScriptTypes.Root);
return field;
}
private URL scriptBaseURL;
public URL getBaseURL() {
return scriptBaseURL;
}
public void setBaseURL(URL url) {
this.scriptBaseURL = url;
}
protected JSSSAPropagationCallGraphBuilder(
AbstractRootMethod abstractRootMethod,
AnalysisOptions options,
IAnalysisCacheView cache,
PointerKeyFactory pointerKeyFactory) {
super(abstractRootMethod, options, cache, pointerKeyFactory);
globalObject = new GlobalObjectKey(cha.lookupClass(JavaScriptTypes.Root));
}
@Override
protected boolean isConstantRef(SymbolTable symbolTable, int valueNumber) {
if (valueNumber == -1) {
return false;
}
return symbolTable.isConstant(valueNumber);
}
// ///////////////////////////////////////////////////////////////////////////
//
// language specialization interface
//
// ///////////////////////////////////////////////////////////////////////////
@Override
protected boolean useObjectCatalog() {
return true;
}
@Override
protected boolean isUncataloguedField(IClass type, String fieldName) {
if (!type.getReference().equals(JavaScriptTypes.Object)) {
return true;
}
return "prototype".equals(fieldName)
|| "constructor".equals(fieldName)
|| "arguments".equals(fieldName)
|| "class".equals(fieldName)
|| "$value".equals(fieldName)
|| "__proto__".equals(fieldName);
}
@Override
protected AbstractFieldPointerKey fieldKeyForUnknownWrites(AbstractFieldPointerKey fieldKey) {
// TODO: fix this. null is wrong.
return null;
// return ReflectedFieldPointerKey.mapped(new
// ConcreteTypeKey(cha.lookupClass(JavaScriptTypes.String)), fieldKey.getInstanceKey());
}
// ///////////////////////////////////////////////////////////////////////////
//
// top-level node constraint generation
//
// ///////////////////////////////////////////////////////////////////////////
private static final FieldReference prototypeRef;
static {
FieldReference x = null;
try {
byte[] utf8 = "__proto__".getBytes("UTF-8");
x =
FieldReference.findOrCreate(
JavaScriptTypes.Root, Atom.findOrCreate(utf8, 0, utf8.length), JavaScriptTypes.Root);
} catch (UnsupportedEncodingException e) {
assert false;
}
prototypeRef = x;
}
public PointerKey getPointerKeyForGlobalVar(String varName) {
FieldReference fieldRef =
FieldReference.findOrCreate(
JavaScriptTypes.Root, Atom.findOrCreateUnicodeAtom(varName), JavaScriptTypes.Root);
IField f = cha.resolveField(fieldRef);
assert f != null : "couldn't resolve " + varName;
return getPointerKeyForInstanceField(getGlobalObject(JavaScriptTypes.jsName), f);
}
@Override
protected ExplicitCallGraph createEmptyCallGraph(IMethod fakeRootClass, AnalysisOptions options) {
return new JSCallGraph(fakeRootClass, options, getAnalysisCache());
}
protected TypeInference makeTypeInference(IR ir, IClassHierarchy cha) {
TypeInference ti = new JSTypeInference(ir, cha);
if (DEBUG_TYPE_INFERENCE) {
System.err.println(("IR of " + ir.getMethod()));
System.err.println(ir);
System.err.println(("TypeInference of " + ir.getMethod()));
for (int i = 0; i <= ir.getSymbolTable().getMaxValueNumber(); i++) {
if (ti.isUndefined(i)) {
System.err.println((" value " + i + " is undefined"));
} else {
System.err.println((" value " + i + " has type " + ti.getType(i)));
}
}
}
return ti;
}
@Override
protected void addAssignmentsForCatchPointerKey(
PointerKey exceptionVar, Set<IClass> catchClasses, PointerKey e) {
system.newConstraint(exceptionVar, assignOperator, e);
}
public static class JSInterestingVisitor extends AstInterestingVisitor
implements com.ibm.wala.cast.js.ssa.JSInstructionVisitor {
public JSInterestingVisitor(int vn) {
super(vn);
}
@Override
public void visitBinaryOp(final SSABinaryOpInstruction instruction) {
bingo = true;
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke instruction) {
bingo = true;
}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction inst) {
bingo = true;
}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf instruction) {
bingo = true;
}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {}
@Override
public void visitSetPrototype(SetPrototype instruction) {
bingo = true;
}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {
bingo = true;
}
}
@Override
protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) {
return new JSInterestingVisitor(vn);
}
// ///////////////////////////////////////////////////////////////////////////
//
// specialized pointer analysis
//
// ///////////////////////////////////////////////////////////////////////////
public static class JSPointerAnalysisImpl
extends AstSSAPropagationCallGraphBuilder.AstPointerAnalysisImpl {
JSPointerAnalysisImpl(
PropagationCallGraphBuilder builder,
CallGraph cg,
PointsToMap pointsToMap,
MutableMapping<InstanceKey> instanceKeys,
PointerKeyFactory pointerKeys,
InstanceKeyFactory iKeyFactory) {
super(builder, cg, pointsToMap, instanceKeys, pointerKeys, iKeyFactory);
}
public static class JSImplicitPointsToSetVisitor extends AstImplicitPointsToSetVisitor
implements com.ibm.wala.cast.js.ssa.JSInstructionVisitor {
public JSImplicitPointsToSetVisitor(AstPointerAnalysisImpl analysis, LocalPointerKey lpk) {
super(analysis, lpk);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke 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 visitAstGlobalRead(AstGlobalRead instruction) {
JSPointerAnalysisImpl jsAnalysis = (JSPointerAnalysisImpl) analysis;
FieldReference field = makeNonGlobalFieldReference(instruction.getDeclaredField());
assert !directGlobalObjectRef(field);
IField f = jsAnalysis.builder.getCallGraph().getClassHierarchy().resolveField(field);
assert f != null;
MutableSparseIntSet S = MutableSparseIntSet.makeEmpty();
InstanceKey globalObj =
((AstSSAPropagationCallGraphBuilder) jsAnalysis.builder)
.getGlobalObject(JavaScriptTypes.jsName);
PointerKey fkey = analysis.getHeapModel().getPointerKeyForInstanceField(globalObj, f);
if (fkey != null) {
OrdinalSet<InstanceKey> pointees = analysis.getPointsToSet(fkey);
IntSet set = pointees.getBackingSet();
if (set != null) {
S.addAll(set);
}
}
pointsToSet = new OrdinalSet<>(S, analysis.getInstanceKeyMapping());
}
@Override
public void visitSetPrototype(SetPrototype instruction) {}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {}
}
@Override
protected ImplicitPointsToSetVisitor makeImplicitPointsToVisitor(LocalPointerKey lpk) {
return new JSImplicitPointsToSetVisitor(this, lpk);
}
}
@Override
protected PropagationSystem makeSystem(AnalysisOptions options) {
return new PropagationSystem(callGraph, pointerKeyFactory, instanceKeyFactory) {
@Override
public PointerAnalysis<InstanceKey> makePointerAnalysis(PropagationCallGraphBuilder builder) {
return new JSPointerAnalysisImpl(
builder, cg, pointsToMap, instanceKeys, pointerKeyFactory, instanceKeyFactory);
}
};
}
// ///////////////////////////////////////////////////////////////////////////
//
// IR visitor specialization for JavaScript
//
// ///////////////////////////////////////////////////////////////////////////
@Override
public JSConstraintVisitor makeVisitor(CGNode node) {
if (AstSSAPropagationCallGraphBuilder.DEBUG_PROPERTIES) {
final IMethod method = node.getMethod();
if (method instanceof AstMethod) {
System.err.println("\n\nNode: " + node);
final IR ir = node.getIR();
System.err.println("Position: " + getSomePositionForMethod(ir, (AstMethod) method));
// System.err.println(ir);
}
}
return new JSConstraintVisitor(this, node);
}
public static Position getSomePositionForMethod(IR ir, AstMethod method) {
SSAInstruction[] instructions = ir.getInstructions();
for (int i = 0; i < instructions.length; i++) {
Position p = method.getSourcePosition(i);
if (p != null) {
return p;
}
}
return null;
}
public static class JSConstraintVisitor extends AstConstraintVisitor
implements JSInstructionVisitor {
public JSConstraintVisitor(AstSSAPropagationCallGraphBuilder builder, CGNode node) {
super(builder, node);
}
@Override
public void visitUnaryOp(SSAUnaryOpInstruction inst) {
if (inst.getOpcode() == IUnaryOpInstruction.Operator.NEG) {
addLvalTypeKeyConstraint(inst, JavaScriptTypes.Boolean);
} else if (inst.getOpcode() == CAstUnaryOp.MINUS) {
addLvalTypeKeyConstraint(inst, JavaScriptTypes.Number);
}
}
/** add a constraint indicating that the value def'd by inst can point to a value of type t */
private void addLvalTypeKeyConstraint(SSAInstruction inst, TypeReference t) {
int lval = inst.getDef(0);
PointerKey lk = getPointerKeyForLocal(lval);
IClass bool = getClassHierarchy().lookupClass(t);
InstanceKey key = new ConcreteTypeKey(bool);
system.newConstraint(lk, key);
}
@Override
public void visitIsDefined(AstIsDefinedInstruction inst) {
addLvalTypeKeyConstraint(inst, JavaScriptTypes.Boolean);
}
@Override
public void visitJavaScriptInstanceOf(JavaScriptInstanceOf inst) {
addLvalTypeKeyConstraint(inst, JavaScriptTypes.Boolean);
}
@Override
public void visitEachElementHasNext(EachElementHasNextInstruction inst) {
addLvalTypeKeyConstraint(inst, JavaScriptTypes.Boolean);
}
@Override
public void visitTypeOf(JavaScriptTypeOfInstruction instruction) {
addLvalTypeKeyConstraint(instruction, JavaScriptTypes.String);
}
@Override
public void visitAstGlobalRead(AstGlobalRead instruction) {
int lval = instruction.getDef();
FieldReference field = makeNonGlobalFieldReference(instruction.getDeclaredField());
PointerKey def = getPointerKeyForLocal(lval);
assert def != null;
IField f = getClassHierarchy().resolveField(field);
assert f != null : "could not resolve referenced global " + field;
if (hasNoInterestingUses(lval)) {
system.recordImplicitPointsToSet(def);
} else {
InstanceKey globalObj = getBuilder().getGlobalObject(JavaScriptTypes.jsName);
if (directGlobalObjectRef(field)) {
// points-to set is just the global object
system.newConstraint(def, globalObj);
} else {
system.findOrCreateIndexForInstanceKey(globalObj);
PointerKey p = getPointerKeyForInstanceField(globalObj, f);
system.newConstraint(def, assignOperator, p);
}
}
}
@Override
public void visitAstGlobalWrite(AstGlobalWrite instruction) {
int rval = instruction.getVal();
FieldReference field = makeNonGlobalFieldReference(instruction.getDeclaredField());
IField f = getClassHierarchy().resolveField(field);
assert f != null : "could not resolve referenced global " + field;
assert !f.getFieldTypeReference().isPrimitiveType();
InstanceKey globalObj = getBuilder().getGlobalObject(JavaScriptTypes.jsName);
system.findOrCreateIndexForInstanceKey(globalObj);
PointerKey p = getPointerKeyForInstanceField(globalObj, f);
PointerKey rvalKey = getPointerKeyForLocal(rval);
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
for (InstanceKey element : ik) {
system.newConstraint(p, element);
}
} else {
system.newConstraint(p, assignOperator, rvalKey);
}
}
@Override
public void visitBinaryOp(final SSABinaryOpInstruction instruction) {
handleBinaryOp(instruction, node, symbolTable, du);
}
@Override
public void visitJavaScriptInvoke(JavaScriptInvoke instruction) {
if (instruction.getDeclaredTarget().equals(JavaScriptMethods.dispatchReference)) {
handleJavascriptDispatch(instruction);
} else {
visitInvokeInternal(instruction, new DefaultInvariantComputer());
}
}
private void handleJavascriptDispatch(
final JavaScriptInvoke instruction, final InstanceKey receiverType) {
int functionVn = instruction.getFunction();
ReflectedFieldAction fieldDispatchAction =
new ReflectedFieldAction() {
@Override
public void action(final AbstractFieldPointerKey fieldKey) {
class FieldValueDispatch extends UnaryOperator<PointsToSetVariable> {
private JavaScriptInvoke getInstruction() {
return instruction;
}
private InstanceKey getReceiver() {
return receiverType;
}
private AbstractFieldPointerKey getProperty() {
return fieldKey;
}
private CGNode getNode() {
return node;
}
private final MutableIntSet previous = IntSetUtil.make();
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable ptrs) {
if (ptrs.getValue() != null) {
ptrs.getValue()
.foreachExcluding(
previous,
x -> {
final InstanceKey functionObj = system.getInstanceKey(x);
visitInvokeInternal(
instruction,
new DefaultInvariantComputer() {
@Override
public InstanceKey[][] computeInvariantParameters(
SSAAbstractInvokeInstruction call) {
InstanceKey[][] x = super.computeInvariantParameters(call);
if (x == null) {
x = new InstanceKey[call.getNumberOfUses()][];
}
x[0] = new InstanceKey[] {functionObj};
x[1] = new InstanceKey[] {receiverType};
return x;
}
});
});
previous.addAll(ptrs.getValue());
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return instruction.hashCode() * fieldKey.hashCode() * receiverType.hashCode();
}
@Override
public boolean equals(Object o) {
return o instanceof FieldValueDispatch
&& ((FieldValueDispatch) o).getNode().equals(node)
&& ((FieldValueDispatch) o).getInstruction() == instruction
&& ((FieldValueDispatch) o).getProperty().equals(fieldKey)
&& ((FieldValueDispatch) o).getReceiver().equals(receiverType);
}
@Override
public String toString() {
return "sub-dispatch for " + instruction + ": " + receiverType + ", " + fieldKey;
}
}
system.newSideEffect(new FieldValueDispatch(), fieldKey);
}
@Override
public void dump(
AbstractFieldPointerKey fieldKey, boolean constObj, boolean constProp) {
System.err.println(
"dispatch to " + receiverType + '.' + fieldKey + " for " + instruction);
}
};
TransitivePrototypeKey prototypeObjs = new TransitivePrototypeKey(receiverType);
InstanceKey[] objKeys = new InstanceKey[] {receiverType};
if (contentsAreInvariant(symbolTable, du, functionVn)) {
InstanceKey[] fieldsKeys = getInvariantContents(functionVn);
newFieldOperationObjectAndFieldConstant(true, fieldDispatchAction, objKeys, fieldsKeys);
newFieldOperationOnlyFieldConstant(true, fieldDispatchAction, prototypeObjs, fieldsKeys);
} else {
PointerKey fieldKey = getPointerKeyForLocal(functionVn);
newFieldOperationOnlyObjectConstant(true, fieldDispatchAction, fieldKey, objKeys);
newFieldFullOperation(true, fieldDispatchAction, prototypeObjs, fieldKey);
}
}
private void handleJavascriptDispatch(final JavaScriptInvoke instruction) {
int receiverVn = instruction.getUse(1);
PointerKey receiverKey = getPointerKeyForLocal(receiverVn);
if (contentsAreInvariant(symbolTable, du, receiverVn)) {
system.recordImplicitPointsToSet(receiverKey);
InstanceKey[] ik = getInvariantContents(receiverVn);
for (InstanceKey element : ik) {
handleJavascriptDispatch(instruction, element);
}
} else {
class ReceiverForDispatchOp extends UnaryOperator<PointsToSetVariable> {
final MutableIntSet previous = IntSetUtil.make();
private CGNode getNode() {
return node;
}
private JavaScriptInvoke getInstruction() {
return instruction;
}
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
if (rhs.getValue() != null) {
rhs.getValue()
.foreachExcluding(
previous,
x -> {
try {
MonitorUtil.throwExceptionIfCanceled(getBuilder().monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
InstanceKey ik = system.getInstanceKey(x);
handleJavascriptDispatch(instruction, ik);
});
previous.addAll(rhs.getValue());
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return instruction.hashCode() * node.hashCode();
}
@Override
public boolean equals(Object o) {
return o instanceof ReceiverForDispatchOp
&& ((ReceiverForDispatchOp) o).getInstruction() == getInstruction()
&& ((ReceiverForDispatchOp) o).getNode() == getNode();
}
@Override
public String toString() {
return "receiver for dispatch: " + instruction;
}
}
system.newSideEffect(new ReceiverForDispatchOp(), receiverKey);
}
}
// ///////////////////////////////////////////////////////////////////////////
//
// string manipulation handling for binary operators
//
// ///////////////////////////////////////////////////////////////////////////
private void handleBinaryOp(
final SSABinaryOpInstruction instruction,
final CGNode node,
final SymbolTable symbolTable,
final DefUse du) {
int lval = instruction.getDef(0);
PointerKey lk = getPointerKeyForLocal(lval);
final PointsToSetVariable lv = system.findOrCreatePointsToSet(lk);
final int arg1 = instruction.getUse(0);
final int arg2 = instruction.getUse(1);
class BinaryOperator extends AbstractOperator<PointsToSetVariable> {
private CGNode getNode() {
return node;
}
private SSAAbstractBinaryInstruction getInstruction() {
return instruction;
}
@Override
public String toString() {
return "BinOp: " + getInstruction();
}
@Override
public int hashCode() {
return 17 * getInstruction().getUse(0) * getInstruction().getUse(1);
}
@Override
public boolean equals(Object o) {
if (o instanceof BinaryOperator) {
BinaryOperator op = (BinaryOperator) o;
return op.getNode().equals(getNode())
&& op.getInstruction().getUse(0) == getInstruction().getUse(0)
&& op.getInstruction().getUse(1) == getInstruction().getUse(1)
&& op.getInstruction().getDef(0) == getInstruction().getDef(0);
} else {
return false;
}
}
private InstanceKey[] getInstancesArray(int vn) {
if (contentsAreInvariant(symbolTable, du, vn)) {
return getInvariantContents(vn);
} else {
PointsToSetVariable v = system.findOrCreatePointsToSet(getPointerKeyForLocal(vn));
if (v.getValue() == null || v.size() == 0) {
return new InstanceKey[0];
} else {
final Set<InstanceKey> temp = HashSetFactory.make();
v.getValue().foreach(keyIndex -> temp.add(system.getInstanceKey(keyIndex)));
return temp.toArray(new InstanceKey[0]);
}
}
}
private boolean isStringConstant(InstanceKey k) {
return (k instanceof ConstantKey)
&& k.getConcreteType().getReference().equals(JavaScriptTypes.String);
}
private boolean addKey(InstanceKey k) {
int n = system.findOrCreateIndexForInstanceKey(k);
return lv.add(n);
}
@Override
public byte evaluate(PointsToSetVariable lhs, final PointsToSetVariable[] rhs) {
boolean doDefault = false;
byte changed = NOT_CHANGED;
InstanceKey[] iks1 = getInstancesArray(arg1);
InstanceKey[] iks2 = getInstancesArray(arg2);
IOperator op = instruction.getOperator();
if ((op == BinaryOpInstruction.Operator.ADD) && getOptions().getTraceStringConstants()) {
for (InstanceKey element : iks1) {
if (isStringConstant(element)) {
for (InstanceKey element2 : iks2) {
if (isStringConstant(element2)) {
try {
MonitorUtil.throwExceptionIfCanceled(builder.monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
String v1 = (String) ((ConstantKey<?>) element).getValue();
String v2 = (String) ((ConstantKey<?>) element2).getValue();
if (!v1.contains(v2) && !v2.contains(v1)) {
InstanceKey lvalKey = getInstanceKeyForConstant(v1 + v2);
if (addKey(lvalKey)) {
changed = CHANGED;
}
} else {
doDefault = true;
}
} else {
doDefault = true;
}
}
} else {
doDefault = true;
}
}
} else {
doDefault = true;
}
if (doDefault) {
for (InstanceKey element : iks1) {
for (InstanceKey element2 : iks2) {
try {
MonitorUtil.throwExceptionIfCanceled(builder.monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
if (handleBinaryOperatorArgs(element, element2)) {
changed = CHANGED;
}
}
}
}
if (iks1 == null || iks1.length == 0 || iks2 == null || iks2.length == 0) {
if (iks1 != null) {
for (InstanceKey ik : iks1) {
if (addKey(ik)) {
changed = CHANGED;
}
}
}
if (iks2 != null) {
for (InstanceKey ik : iks2) {
if (addKey(ik)) {
changed = CHANGED;
}
}
}
System.err.println(instruction);
}
if (op == CAstBinaryOp.STRICT_EQ || op == CAstBinaryOp.STRICT_NE) {
IClass bc = getClassHierarchy().lookupClass(JavaScriptTypes.Boolean);
InstanceKey bk = new ConcreteTypeKey(bc);
if (addKey(bk)) {
changed = CHANGED;
}
}
return changed;
}
private boolean isNumberType(Language l, TypeReference t) {
return l.isDoubleType(t) || l.isFloatType(t) || l.isIntType(t) || l.isLongType(t);
}
protected boolean handleBinaryOperatorArgs(InstanceKey left, InstanceKey right) {
Language l = node.getMethod().getDeclaringClass().getClassLoader().getLanguage();
if (l.isStringType(left.getConcreteType().getReference())
|| l.isStringType(right.getConcreteType().getReference())) {
return addKey(
new ConcreteTypeKey(node.getClassHierarchy().lookupClass(l.getStringType())));
} else if (isNumberType(l, left.getConcreteType().getReference())
&& isNumberType(l, right.getConcreteType().getReference())) {
if (left instanceof ConstantKey && right instanceof ConstantKey) {
return addKey(
new ConcreteTypeKey(
node.getClassHierarchy().lookupClass(JavaScriptTypes.Number)));
} else {
return addKey(left) || addKey(right);
}
} else {
return false;
}
}
}
BinaryOperator B = new BinaryOperator();
if (contentsAreInvariant(symbolTable, du, arg1)) {
if (contentsAreInvariant(symbolTable, du, arg2)) {
B.evaluate(null, null);
} else {
system.newConstraint(lk, B, getPointerKeyForLocal(arg2));
}
} else {
PointerKey k1 = getPointerKeyForLocal(arg1);
if (contentsAreInvariant(symbolTable, du, arg2)) {
system.newConstraint(lk, B, k1);
} else {
system.newConstraint(lk, B, k1, getPointerKeyForLocal(arg2));
}
}
}
@Override
public void visitCheckRef(JavaScriptCheckReference instruction) {
// TODO Auto-generated method stub
}
@Override
public void visitWithRegion(JavaScriptWithRegion instruction) {
// TODO Auto-generated method stub
}
private final UnaryOperator<PointsToSetVariable> transitivePrototypeOp =
new UnaryOperator<>() {
@Override
public byte evaluate(final PointsToSetVariable lhs, PointsToSetVariable rhs) {
class Op implements IntSetAction {
private boolean changed = false;
@Override
public void act(int x) {
InstanceKey protoObj = system.getInstanceKey(x);
PointerKey protoObjKey = new TransitivePrototypeKey(protoObj);
changed |=
system.newStatement(
lhs,
assignOperator,
system.findOrCreatePointsToSet(protoObjKey),
true,
true);
}
}
if (rhs.getValue() != null) {
Op op = new Op();
rhs.getValue().foreach(op);
return (op.changed ? CHANGED : NOT_CHANGED);
}
return NOT_CHANGED;
}
@Override
public int hashCode() {
return -896435647;
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public String toString() {
return "transitivePrototypeOp";
}
};
@Override
public void visitSetPrototype(SetPrototype instruction) {
visitPutInternal(instruction.getUse(1), instruction.getUse(0), false, prototypeRef);
assert contentsAreInvariant(symbolTable, du, instruction.getUse(0));
if (contentsAreInvariant(symbolTable, du, instruction.getUse(1))) {
for (InstanceKey newObj : getInvariantContents(instruction.getUse(0))) {
PointerKey newObjKey = new TransitivePrototypeKey(newObj);
for (InstanceKey protoObj : getInvariantContents(instruction.getUse(1))) {
system.newConstraint(newObjKey, protoObj);
system.newConstraint(newObjKey, assignOperator, new TransitivePrototypeKey(protoObj));
}
}
} else {
for (InstanceKey newObj : getInvariantContents(instruction.getUse(0))) {
PointerKey newObjKey = new TransitivePrototypeKey(newObj);
system.newConstraint(
newObjKey, assignOperator, getPointerKeyForLocal(instruction.getUse(1)));
system.newConstraint(
newObjKey, transitivePrototypeOp, getPointerKeyForLocal(instruction.getUse(1)));
}
}
}
@Override
public void visitPrototypeLookup(PrototypeLookup instruction) {
if (contentsAreInvariant(symbolTable, du, instruction.getUse(0))) {
for (InstanceKey rhsObj : getInvariantContents(instruction.getUse(0))) {
// property can come from object itself...
system.newConstraint(getPointerKeyForLocal(instruction.getDef(0)), rhsObj);
// ...or prototype objects
system.newConstraint(
getPointerKeyForLocal(instruction.getDef(0)),
assignOperator,
new TransitivePrototypeKey(rhsObj));
}
} else {
// property can come from object itself...
system.newConstraint(
getPointerKeyForLocal(instruction.getDef(0)),
assignOperator,
getPointerKeyForLocal(instruction.getUse(0)));
// ...or prototype objects
system.newConstraint(
getPointerKeyForLocal(instruction.getDef(0)),
transitivePrototypeOp,
getPointerKeyForLocal(instruction.getUse(0)));
}
}
}
// ///////////////////////////////////////////////////////////////////////////
//
// function call handling
//
// //////////////////////////////////////////////////////////////////////////
@Override
protected void processCallingConstraints(
CGNode caller,
SSAAbstractInvokeInstruction instruction,
CGNode target,
InstanceKey[][] constParams,
PointerKey uniqueCatchKey) {
processCallingConstraintsInternal(
this, caller, instruction, target, constParams, uniqueCatchKey);
}
@SuppressWarnings("unused")
public static void processCallingConstraintsInternal(
AstSSAPropagationCallGraphBuilder builder,
CGNode caller,
SSAAbstractInvokeInstruction instruction,
CGNode target,
InstanceKey[][] constParams,
PointerKey uniqueCatchKey) {
IRView sourceIR = builder.getCFAContextInterpreter().getIRView(caller);
SymbolTable sourceST = sourceIR.getSymbolTable();
IRView targetIR = builder.getCFAContextInterpreter().getIRView(target);
SymbolTable targetST = targetIR.getSymbolTable();
JSConstraintVisitor targetVisitor = null;
int av = -1;
for (int v = 0; v <= targetST.getMaxValueNumber(); v++) {
String[] vns = targetIR.getLocalNames(1, v);
for (int n = 0; vns != null && n < vns.length; n++) {
if ("arguments".equals(vns[n])) {
av = v;
targetVisitor = (JSConstraintVisitor) builder.makeVisitor(target);
break;
}
}
}
int paramCount = targetST.getParameterValueNumbers().length;
int argCount = instruction.getNumberOfPositionalParameters();
// the first two arguments are the function object and the receiver, neither of which
// should become part of the arguments array
int num_pseudoargs = 2;
// pass actual arguments to formals in the normal way
for (int i = 0; i < Math.min(paramCount, argCount); i++) {
InstanceKey[] fn =
new InstanceKey[] {
builder.getInstanceKeyForConstant(
JavaScriptTypes.String, String.valueOf(i - num_pseudoargs))
};
PointerKey F = builder.getTargetPointerKey(target, i);
if (constParams != null && constParams[i] != null) {
for (int j = 0; j < constParams[i].length; j++) {
builder.getSystem().newConstraint(F, constParams[i][j]);
}
if (av != -1 && i >= num_pseudoargs) {
targetVisitor.newFieldWrite(target, av, fn, constParams[i]);
}
} else {
PointerKey A = builder.getPointerKeyForLocal(caller, instruction.getUse(i));
builder
.getSystem()
.newConstraint(
F, (F instanceof FilteredPointerKey) ? builder.filterOperator : assignOperator, A);
if (av != -1 && i >= num_pseudoargs) {
targetVisitor.newFieldWrite(target, av, fn, F);
}
}
}
// extra actual arguments get assigned into the ``arguments'' object
if (paramCount < argCount) {
if (av != -1) {
for (int i = paramCount; i < argCount; i++) {
InstanceKey[] fn =
new InstanceKey[] {
builder.getInstanceKeyForConstant(
JavaScriptTypes.String, String.valueOf(i - num_pseudoargs))
};
if (constParams != null && constParams[i] != null && i >= num_pseudoargs) {
targetVisitor.newFieldWrite(target, av, fn, constParams[i]);
} else if (i >= num_pseudoargs) {
PointerKey A = builder.getPointerKeyForLocal(caller, instruction.getUse(i));
targetVisitor.newFieldWrite(target, av, fn, A);
}
}
}
}
// extra formal parameters get null (extra args are ignored here)
else if (argCount < paramCount) {
int nullvn = sourceST.getNullConstant();
DefUse sourceDU = builder.getCFAContextInterpreter().getDU(caller);
InstanceKey[] nullkeys =
builder.getInvariantContents(sourceST, sourceDU, caller, nullvn, builder);
for (int i = argCount; i < paramCount; i++) {
PointerKey F = builder.getPointerKeyForLocal(target, targetST.getParameter(i));
for (InstanceKey nullkey : nullkeys) {
builder.getSystem().newConstraint(F, nullkey);
}
}
}
// write `length' in argument objects
if (av != -1) {
InstanceKey[] svn =
new InstanceKey[] {
builder.getInstanceKeyForConstant(JavaScriptTypes.Number, argCount - 1)
};
InstanceKey[] lnv =
new InstanceKey[] {builder.getInstanceKeyForConstant(JavaScriptTypes.String, "length")};
targetVisitor.newFieldWrite(target, av, lnv, svn);
}
// return values
if (instruction.getDef(0) != -1) {
PointerKey RF = builder.getPointerKeyForReturnValue(target);
PointerKey RA = builder.getPointerKeyForLocal(caller, instruction.getDef(0));
builder.getSystem().newConstraint(RA, assignOperator, RF);
}
PointerKey EF = builder.getPointerKeyForExceptionalReturnValue(target);
if (SHORT_CIRCUIT_SINGLE_USES && uniqueCatchKey != null) {
// e has exactly one use. so, represent e implicitly
builder.getSystem().newConstraint(uniqueCatchKey, assignOperator, EF);
} else {
PointerKey EA = builder.getPointerKeyForLocal(caller, instruction.getDef(1));
builder.getSystem().newConstraint(EA, assignOperator, EF);
}
}
@Override
protected boolean sameMethod(CGNode opNode, String definingMethod) {
return definingMethod.equals(
opNode.getMethod().getReference().getDeclaringClass().getName().toString());
}
}
| 43,613
| 36.565891
| 126
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSSyntheticParameterKey.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.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.NodeKey;
public class JSSyntheticParameterKey extends NodeKey {
public static int lengthOffset = -1;
private final int param;
public JSSyntheticParameterKey(CGNode node, int param) {
super(node);
this.param = param;
}
@Override
public boolean equals(Object o) {
return (o instanceof JSSyntheticParameterKey)
&& ((JSSyntheticParameterKey) o).param == param
&& internalEquals(o);
}
@Override
public int hashCode() {
return param * getNode().hashCode();
}
@Override
public String toString() {
return "p" + param + ':' + getNode().getMethod().getName();
}
}
| 1,130
| 25.302326
| 72
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JSZeroOrOneXCFABuilder.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.AnalysisScope;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.impl.ContextInsensitiveSelector;
import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DelegatingSSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.callgraph.propagation.cfa.nCFAContextSelector;
import com.ibm.wala.ipa.cha.IClassHierarchy;
/** 0-x-CFA Call graph builder, optimized to not disambiguate instances of "uninteresting" types */
public class JSZeroOrOneXCFABuilder extends JSCFABuilder {
private static final boolean USE_OBJECT_SENSITIVITY = false;
public JSZeroOrOneXCFABuilder(
IClassHierarchy cha,
JSAnalysisOptions options,
IAnalysisCacheView cache,
ContextSelector appContextSelector,
SSAContextInterpreter appContextInterpreter,
int instancePolicy,
boolean doOneCFA) {
super(cha, options, cache);
SSAContextInterpreter contextInterpreter =
setupSSAContextInterpreter(cha, options, cache, appContextInterpreter);
setupMethodTargetSelector(cha, options);
setupContextSelector(options, appContextSelector, doOneCFA);
setInstanceKeys(
new JavaScriptScopeMappingInstanceKeys(
cha,
this,
new JavaScriptConstructorInstanceKeys(
new ZeroXInstanceKeys(options, cha, contextInterpreter, instancePolicy))));
}
private void setupContextSelector(
JSAnalysisOptions options, ContextSelector appContextSelector, boolean doOneCFA) {
// baseline selector
ContextSelector def = new ContextInsensitiveSelector();
ContextSelector contextSelector =
appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def);
// JavaScriptConstructorContextSelector ensures at least a 0-1-CFA (i.e.,
// Andersen's-style) heap abstraction. This level of heap abstraction is
// _necessary_ for correctness (we rely on it when handling lexical scoping)
contextSelector = new JavaScriptConstructorContextSelector(contextSelector);
// contextSelector = new OneLevelForLexicalAccessFunctions(contextSelector);
if (USE_OBJECT_SENSITIVITY) {
contextSelector = new ObjectSensitivityContextSelector(contextSelector);
}
if (options.handleCallApply()) {
contextSelector = new JavaScriptFunctionApplyContextSelector(contextSelector);
}
if (doOneCFA) {
contextSelector = new nCFAContextSelector(1, contextSelector);
}
setContextSelector(contextSelector);
}
private void setupMethodTargetSelector(IClassHierarchy cha, JSAnalysisOptions options) {
MethodTargetSelector targetSelector =
new JavaScriptConstructTargetSelector(cha, options.getMethodTargetSelector());
if (options.handleCallApply()) {
targetSelector =
new JavaScriptFunctionApplyTargetSelector(
new JavaScriptFunctionDotCallTargetSelector(targetSelector));
}
if (options.useLoadFileTargetSelector()) {
targetSelector = new LoadFileTargetSelector(targetSelector, this);
}
options.setSelector(targetSelector);
}
private SSAContextInterpreter setupSSAContextInterpreter(
IClassHierarchy cha,
JSAnalysisOptions options,
IAnalysisCacheView cache,
SSAContextInterpreter appContextInterpreter) {
SSAContextInterpreter contextInterpreter =
makeDefaultContextInterpreters(appContextInterpreter, options, cha);
if (options.handleCallApply()) {
contextInterpreter =
new DelegatingSSAContextInterpreter(
new JavaScriptFunctionApplyContextInterpreter(options, cache), contextInterpreter);
}
setContextInterpreter(contextInterpreter);
return contextInterpreter;
}
/**
* @param options options that govern call graph construction
* @param cha governing class hierarchy
* @param cl classloader that can find DOMO resources
* @param scope representation of the analysis scope
* @param xmlFiles set of Strings that are names of XML files holding bypass logic specifications.
* @return a 0-1-Opt-CFA Call Graph Builder.
*/
public static JSCFABuilder make(
JSAnalysisOptions options,
IAnalysisCacheView cache,
IClassHierarchy cha,
ClassLoader cl,
AnalysisScope scope,
String[] xmlFiles,
byte instancePolicy,
boolean doOneCFA) {
com.ibm.wala.ipa.callgraph.impl.Util.addDefaultSelectors(options, cha);
for (String xmlFile : xmlFiles) {
com.ibm.wala.ipa.callgraph.impl.Util.addBypassLogic(options, cl, xmlFile, cha);
}
return new JSZeroOrOneXCFABuilder(cha, options, cache, null, null, instancePolicy, doOneCFA);
}
}
| 5,413
| 38.808824
| 100
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptConstructTargetSelector.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.js.ipa.summaries.JavaScriptConstructorFunctions;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
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.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
/** generates instructions to simulate the semantics of JS constructor invocations */
public class JavaScriptConstructTargetSelector implements MethodTargetSelector {
private final MethodTargetSelector base;
private final JavaScriptConstructorFunctions constructors;
public JavaScriptConstructTargetSelector(IClassHierarchy cha, MethodTargetSelector base) {
this.constructors = new JavaScriptConstructorFunctions(cha);
this.base = base;
}
public JavaScriptConstructTargetSelector(
JavaScriptConstructorFunctions constructors, MethodTargetSelector base) {
this.constructors = constructors;
this.base = base;
}
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) {
if (site.getDeclaredTarget().equals(JavaScriptMethods.ctorReference)) {
IR callerIR = caller.getIR();
SSAAbstractInvokeInstruction callStmts[] = callerIR.getCalls(site);
assert callStmts.length == 1;
int nargs = callStmts[0].getNumberOfPositionalParameters();
return constructors.findOrCreateConstructorMethod(
callerIR, callStmts[0], receiver, nargs - 1);
} else {
return base.getCalleeTarget(caller, site, receiver);
}
}
public boolean mightReturnSyntheticMethod() {
return true;
}
}
| 2,210
| 36.474576
| 92
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptConstructorContextSelector.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.ir.translator.AstTranslator.AstLexicalInformation;
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.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.cfa.OneLevelSiteContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.cfa.nCFAContextSelector;
import com.ibm.wala.util.intset.IntSet;
public class JavaScriptConstructorContextSelector implements ContextSelector {
private final ContextSelector base;
/**
* for generating contexts with one-level of call strings, to match standard Andersen's heap
* abstraction
*/
private final nCFAContextSelector oneLevelCallStrings;
private final OneLevelSiteContextSelector oneLevelCallerSite;
public JavaScriptConstructorContextSelector(ContextSelector base) {
this.base = base;
this.oneLevelCallStrings = new nCFAContextSelector(1, base);
this.oneLevelCallerSite = new OneLevelSiteContextSelector(base);
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return base.getRelevantParameters(caller, site);
}
@Override
public Context getCalleeTarget(
final CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (callee instanceof JavaScriptConstructor) {
final Context oneLevelCallStringContext =
oneLevelCallStrings.getCalleeTarget(caller, site, callee, receiver);
if (AstLexicalInformation.hasExposedUses(caller, site)) {
// use a caller-site context, to enable lexical scoping lookups (via caller CGNode)
return oneLevelCallerSite.getCalleeTarget(caller, site, callee, receiver);
} else {
// use at least one-level of call-string sensitivity for constructors
// always
return oneLevelCallStringContext;
}
} else {
return base.getCalleeTarget(caller, site, callee, receiver);
}
}
}
| 2,617
| 38.666667
| 95
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptConstructorInstanceKeys.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.JavaScriptConstructorFunctions.JavaScriptConstructor;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.ProgramCounter;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory;
import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode;
import com.ibm.wala.types.TypeReference;
public class JavaScriptConstructorInstanceKeys implements InstanceKeyFactory {
private final InstanceKeyFactory base;
public JavaScriptConstructorInstanceKeys(InstanceKeyFactory base) {
super();
this.base = base;
}
@Override
public InstanceKey getInstanceKeyForAllocation(CGNode node, NewSiteReference allocation) {
if (node.getMethod() instanceof JavaScriptConstructor) {
InstanceKey bk = base.getInstanceKeyForAllocation(node, allocation);
return new NormalAllocationInNode(node, allocation, bk.getConcreteType());
} else {
return base.getInstanceKeyForAllocation(node, allocation);
}
}
@Override
public InstanceKey getInstanceKeyForMetadataObject(Object obj, TypeReference objType) {
return base.getInstanceKeyForMetadataObject(obj, objType);
}
@Override
public <T> InstanceKey getInstanceKeyForConstant(TypeReference type, T S) {
return base.getInstanceKeyForConstant(type, S);
}
@Override
public InstanceKey getInstanceKeyForMultiNewArray(
CGNode node, NewSiteReference allocation, int dim) {
return base.getInstanceKeyForMultiNewArray(node, allocation, dim);
}
@Override
public InstanceKey getInstanceKeyForPEI(CGNode node, ProgramCounter instr, TypeReference type) {
return base.getInstanceKeyForPEI(node, instr, type);
}
}
| 2,219
| 35.393443
| 98
|
java
|
WALA
|
WALA-master/cast/js/src/main/java/com/ibm/wala/cast/js/ipa/callgraph/JavaScriptEntryPoints.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.ScriptEntryPoints;
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.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
public class JavaScriptEntryPoints extends ScriptEntryPoints {
@Override
protected CallSiteReference makeScriptSite(IMethod m, int pc) {
return new DynamicCallSiteReference(JavaScriptTypes.CodeBody, pc);
}
public JavaScriptEntryPoints(IClassHierarchy cha, IClassLoader loader) {
super(cha, loader.lookupClass(JavaScriptTypes.Script.getName()));
}
}
| 1,140
| 34.65625
| 74
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.