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/src/main/java/com/ibm/wala/cast/tree/pattern/Alt.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.tree.pattern;
import com.ibm.wala.cast.tree.CAstNode;
/**
* Pattern to match one of two alternatives.
*
* @author mschaefer
*/
public class Alt implements NodePattern {
private final NodePattern left, right;
public Alt(NodePattern left, NodePattern right) {
this.left = left;
this.right = right;
}
@Override
public boolean matches(CAstNode node) {
return left.matches(node) || right.matches(node);
}
}
| 828
| 24.121212
| 72
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/pattern/AnyNode.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.tree.pattern;
import com.ibm.wala.cast.tree.CAstNode;
/**
* A node pattern that matches any AST node.
*
* @author mschaefer
*/
public class AnyNode implements NodePattern {
@Override
public boolean matches(CAstNode node) {
return true;
}
}
| 651
| 23.148148
| 72
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/pattern/NodeOfKind.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.tree.pattern;
import com.ibm.wala.cast.tree.CAstNode;
/**
* A node pattern that matches an AST node of a certain kind; additionally, the node's children have
* to match the pattern's child patterns.
*
* @author mschaefer
*/
public class NodeOfKind implements NodePattern {
protected int kind;
protected NodePattern[] children;
public NodeOfKind(int kind, NodePattern... children) {
this.kind = kind;
this.children = children.clone();
}
/* (non-Javadoc)
* @see pattern.NodePattern#matches(com.ibm.wala.cast.tree.CAstNode)
*/
@Override
public boolean matches(CAstNode node) {
if (node == null || node.getKind() != kind || node.getChildCount() != children.length)
return false;
for (int i = 0; i < children.length; ++i)
if (!children[i].matches(node.getChild(i))) return false;
return true;
}
}
| 1,250
| 28.093023
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/pattern/NodePattern.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.tree.pattern;
import com.ibm.wala.cast.tree.CAstNode;
/**
* Interface for lightweight AST patterns.
*
* @author mschaefer
*/
public interface NodePattern {
boolean matches(CAstNode node);
}
| 593
| 23.75
| 72
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/pattern/SomeConstant.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.tree.pattern;
import com.ibm.wala.cast.tree.CAstNode;
/**
* A node pattern matching any constant. A pattern of this class also stores its last match.
*
* @author mschaefer
*/
public class SomeConstant extends NodeOfKind {
private Object last_match;
public SomeConstant() {
super(CAstNode.CONSTANT);
}
@Override
public boolean matches(CAstNode node) {
boolean res = super.matches(node);
if (res) this.last_match = node.getValue();
return res;
}
public Object getLastMatch() {
return last_match;
}
}
| 938
| 23.076923
| 92
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/pattern/SubtreeOfKind.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.tree.pattern;
import com.ibm.wala.cast.tree.CAstNode;
/**
* A node pattern matching a node of a given kind, without regard to its children.
*
* @author mschaefer
*/
public class SubtreeOfKind extends NodeOfKind {
public SubtreeOfKind(int kind) {
super(kind);
}
@Override
public boolean matches(CAstNode node) {
return node != null && node.getKind() == this.kind;
}
}
| 787
| 24.419355
| 82
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/AstConstantFolder.java
|
package com.ibm.wala.cast.tree.rewrite;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstNodeTypeMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.cast.tree.impl.DelegatingEntity;
import com.ibm.wala.cast.tree.rewrite.CAstBasicRewriter.NonCopyingContext;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter.Rewrite;
import com.ibm.wala.cast.util.AstConstantCollector;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class AstConstantFolder {
protected boolean skip(@SuppressWarnings("unused") CAstNode n) {
return false;
}
static class AssignSkipContext extends NonCopyingContext {
private final Set<CAstNode> skip = HashSetFactory.make();
}
public CAstEntity fold(CAstEntity ce) {
Map<String, Object> constants = AstConstantCollector.collectConstants(ce);
if (constants.isEmpty()) {
return ce;
} else {
Rewrite nce =
new CAstCloner(new CAstImpl(), new AssignSkipContext(), true) {
@Override
protected CAstNode copyNodes(
CAstNode root,
CAstControlFlowMap cfg,
NonCopyingContext c,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
if (root.getKind() == CAstNode.ASSIGN) {
((AssignSkipContext) c).skip.add(root.getChild(0));
}
if (root.getKind() == CAstNode.GLOBAL_DECL) {
for (int i = 0; i < root.getChildCount(); i++) {
((AssignSkipContext) c).skip.add(root.getChild(i));
}
}
if (root.getKind() == CAstNode.VAR
&& !skip(root)
&& constants.containsKey(root.getChild(0).getValue())
&& !((AssignSkipContext) c).skip.contains(root)) {
return Ast.makeConstant(constants.get(root.getChild(0).getValue()));
} else {
return super.copyNodes(root, cfg, c, nodeMap);
}
}
}.rewrite(
ce.getAST(),
ce.getControlFlow(),
ce.getSourceMap(),
ce.getNodeTypeMap(),
ce.getAllScopedEntities(),
ce.getArgumentDefaults());
return new DelegatingEntity(ce) {
@Override
public CAstNode getAST() {
return nce.newRoot();
}
@Override
public CAstControlFlowMap getControlFlow() {
return nce.newCfg();
}
@Override
public CAstSourcePositionMap getSourceMap() {
return nce.newPos();
}
@Override
public CAstNodeTypeMap getNodeTypeMap() {
return nce.newTypes();
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
return nce.newChildren();
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
Collection<CAstEntity> children = nce.newChildren().get(construct);
return children == null ? EmptyIterator.instance() : children.iterator();
}
};
}
}
}
| 3,504
| 32.066038
| 84
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/AstLoopUnwinder.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.tree.rewrite;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.util.collections.Pair;
import java.util.Map;
import java.util.Objects;
public class AstLoopUnwinder
extends CAstRewriter<
CAstRewriter.RewriteContext<AstLoopUnwinder.UnwindKey>, AstLoopUnwinder.UnwindKey> {
public static class UnwindKey implements CAstRewriter.CopyKey<UnwindKey> {
private final int iteration;
private final UnwindKey rest;
private UnwindKey(int iteration, UnwindKey rest) {
this.rest = rest;
this.iteration = iteration;
}
@Override
public int hashCode() {
return iteration * (rest == null ? 1 : rest.hashCode());
}
@Override
public UnwindKey parent() {
return rest;
}
@Override
public boolean equals(Object o) {
return (o instanceof UnwindKey)
&& ((UnwindKey) o).iteration == iteration
&& Objects.equals(rest, ((UnwindKey) o).rest);
}
@Override
public String toString() {
return "#" + iteration + ((rest == null) ? "" : rest.toString());
}
}
// private static final boolean DEBUG = false;
private final int unwindFactor;
public AstLoopUnwinder(CAst Ast, boolean recursive) {
this(Ast, recursive, 3);
}
public AstLoopUnwinder(CAst Ast, boolean recursive, int unwindFactor) {
super(Ast, recursive, new RootContext());
this.unwindFactor = unwindFactor;
}
public CAstEntity translate(CAstEntity original) {
return rewrite(original);
}
private static class RootContext implements RewriteContext<UnwindKey> {
@Override
public UnwindKey key() {
return null;
}
}
private static class LoopContext implements RewriteContext<UnwindKey> {
private final CAstRewriter.RewriteContext<UnwindKey> parent;
private final int iteration;
private LoopContext(int iteration, RewriteContext<UnwindKey> parent) {
this.iteration = iteration;
this.parent = parent;
}
@Override
public UnwindKey key() {
return new UnwindKey(iteration, parent.key());
}
}
@Override
protected CAstNode flowOutTo(
Map<Pair<CAstNode, UnwindKey>, CAstNode> nodeMap,
CAstNode oldSource,
Object label,
CAstNode oldTarget,
CAstControlFlowMap orig,
CAstSourcePositionMap src) {
assert oldTarget == CAstControlFlowMap.EXCEPTION_TO_EXIT;
return oldTarget;
}
@Override
protected CAstNode copyNodes(
CAstNode n,
final CAstControlFlowMap cfg,
RewriteContext<UnwindKey> c,
Map<Pair<CAstNode, UnwindKey>, CAstNode> nodeMap) {
if (n instanceof CAstOperator) {
return n;
} else if (n.getValue() != null) {
return Ast.makeConstant(n.getValue());
} else if (n.getKind() == CAstNode.LOOP) {
CAstNode test = n.getChild(0);
CAstNode body = n.getChild(1);
int count = unwindFactor;
RewriteContext<UnwindKey> lc = new LoopContext(count, c);
CAstNode code =
Ast.makeNode(
CAstNode.ASSERT,
Ast.makeNode(
CAstNode.UNARY_EXPR, CAstOperator.OP_NOT, copyNodes(test, cfg, lc, nodeMap)),
Ast.makeConstant(false));
while (count-- > 0) {
lc = new LoopContext(count, c);
code =
Ast.makeNode(
CAstNode.IF_STMT,
copyNodes(test, cfg, lc, nodeMap),
Ast.makeNode(CAstNode.BLOCK_STMT, copyNodes(body, cfg, lc, nodeMap), code));
}
return code;
} else {
return copySubtreesIntoNewNode(n, cfg, c, nodeMap);
}
}
}
| 4,213
| 27.472973
| 95
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/CAstBasicRewriter.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.tree.rewrite;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import java.util.HashMap;
import java.util.Map;
/** abstract base class for {@link CAstRewriter}s that do no cloning of nodes */
public abstract class CAstBasicRewriter<T extends CAstBasicRewriter.NonCopyingContext>
extends CAstRewriter<T, CAstBasicRewriter.NoKey> {
/** context indicating that no cloning is being performed */
public static class NonCopyingContext implements CAstRewriter.RewriteContext<NoKey> {
private final Map<Object, Object> nodeMap = new HashMap<>();
public Map<Object, Object> nodeMap() {
return nodeMap;
}
@Override
public NoKey key() {
return null;
}
}
/** key indicating that no duplication is being performed */
public static class NoKey implements CAstRewriter.CopyKey<NoKey> {
private NoKey() {
Assertions.UNREACHABLE();
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public NoKey parent() {
return null;
}
}
protected CAstBasicRewriter(CAst Ast, T context, boolean recursive) {
super(Ast, recursive, context);
}
@Override
protected abstract CAstNode copyNodes(
CAstNode root,
final CAstControlFlowMap cfg,
T context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap);
}
| 1,988
| 26.625
| 87
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/CAstCloner.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.tree.rewrite;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstNodeTypeMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.util.collections.Pair;
import java.util.Collection;
import java.util.Map;
public class CAstCloner extends CAstBasicRewriter<CAstBasicRewriter.NonCopyingContext> {
public CAstCloner(CAst Ast, boolean recursive) {
this(Ast, new NonCopyingContext(), recursive);
}
public CAstCloner(CAst Ast) {
this(Ast, false);
}
protected CAstCloner(CAst Ast, NonCopyingContext context, boolean recursive) {
super(Ast, context, recursive);
}
@Override
protected CAstNode copyNodes(
CAstNode root,
final CAstControlFlowMap cfg,
NonCopyingContext context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
final Pair<CAstNode, NoKey> pairKey = Pair.make(root, context.key());
return copyNodes(root, cfg, context, nodeMap, pairKey);
}
protected CAstNode copyNodes(
CAstNode root,
CAstControlFlowMap cfg,
NonCopyingContext context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap,
Pair<CAstNode, NoKey> pairKey) {
if (root instanceof CAstOperator) {
nodeMap.put(pairKey, root);
return root;
} else if (root.getValue() != null) {
CAstNode copy = Ast.makeConstant(root.getValue());
assert !nodeMap.containsKey(pairKey);
nodeMap.put(pairKey, copy);
return copy;
} else {
return copySubtreesIntoNewNode(root, cfg, context, nodeMap, pairKey);
}
}
public Rewrite copy(
CAstNode root,
final CAstControlFlowMap cfg,
final CAstSourcePositionMap pos,
final CAstNodeTypeMap types,
final Map<CAstNode, Collection<CAstEntity>> children,
CAstNode[] defaults) {
return rewrite(root, cfg, pos, types, children, defaults);
}
}
| 2,441
| 30.714286
| 88
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/CAstRewriter.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.tree.rewrite;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstNodeTypeMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder;
import com.ibm.wala.cast.tree.impl.CAstNodeTypeMapRecorder;
import com.ibm.wala.cast.tree.impl.CAstSourcePositionRecorder;
import com.ibm.wala.cast.tree.impl.DelegatingEntity;
import com.ibm.wala.cast.util.CAstPrinter;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Abstract superclass for types performing a rewrite operation on a CAst. The CAst is not mutated;
* instead, a new CAst is created which delegates to the original CAst where no transformation was
* performed.
*
* @param <C> type of the RewriteContext used when traversing the original CAst during the rewrite
* operation
* @param <K> a key used to ease cloning of partial ASTs. When rewriting an AST, sub-classes
* maintain a mapping from (original node, key) pairs (where key is of type K) to new nodes; see
* {@link #copyNodes}
*/
public abstract class CAstRewriter<
C extends CAstRewriter.RewriteContext<K>, K extends CAstRewriter.CopyKey<K>> {
protected static final boolean DEBUG = false;
/** interface to be implemented by keys used for cloning sub-trees during the rewrite */
public interface CopyKey<Self extends CopyKey<Self>> {
@Override
int hashCode();
@Override
boolean equals(Object o);
/**
* keys have parent pointers, useful for when nesting cloning must occur (e.g., unrolling of
* nested loops)
*/
Self parent();
}
/** interface to be implemented by contexts used while traversing the AST */
public interface RewriteContext<K extends CopyKey<K>> {
/** get the cloning key for this context */
K key();
}
/** represents a rewritten CAst */
public interface Rewrite {
CAstNode newRoot();
CAstControlFlowMap newCfg();
CAstSourcePositionMap newPos();
CAstNodeTypeMap newTypes();
Map<CAstNode, Collection<CAstEntity>> newChildren();
CAstNode[] newDefaults();
}
protected final CAst Ast;
/**
* for CAstEntity nodes r s.t. r.getAst() == null, should the scoped entities of r be rewritten?
*/
protected final boolean recursive;
protected final C rootContext;
public CAstRewriter(CAst Ast, boolean recursive, C rootContext) {
this.Ast = Ast;
this.recursive = recursive;
this.rootContext = rootContext;
}
/**
* rewrite the CAst rooted at root under some context, returning the node at the root of the
* rewritten tree. mutate nodeMap in the process, indicating how (original node, copy key) pairs
* are mapped to nodes in the rewritten tree.
*/
protected abstract CAstNode copyNodes(
CAstNode root,
final CAstControlFlowMap cfg,
C context,
Map<Pair<CAstNode, K>, CAstNode> nodeMap);
protected CAstNode copySubtreesIntoNewNode(
CAstNode n, CAstControlFlowMap cfg, C c, Map<Pair<CAstNode, K>, CAstNode> nodeMap) {
return copySubtreesIntoNewNode(n, cfg, c, nodeMap, Pair.make(n, c.key()));
}
protected CAstNode copySubtreesIntoNewNode(
CAstNode n,
CAstControlFlowMap cfg,
C c,
Map<Pair<CAstNode, K>, CAstNode> nodeMap,
Pair<CAstNode, K> pairKey) {
final List<CAstNode> newChildren = copyChildrenArray(n, cfg, c, nodeMap);
CAstNode newN = Ast.makeNode(n.getKind(), newChildren);
assert !nodeMap.containsKey(pairKey);
nodeMap.put(pairKey, newN);
return newN;
}
protected List<CAstNode> copyChildrenArray(
CAstNode n, CAstControlFlowMap cfg, C context, Map<Pair<CAstNode, K>, CAstNode> nodeMap) {
List<CAstNode> newChildren = new ArrayList<>(n.getChildCount());
for (CAstNode child : n.getChildren()) {
newChildren.add(copyNodes(child, cfg, context, nodeMap));
}
return newChildren;
}
protected List<CAstNode> copyChildrenArrayAndTargets(
CAstNode n, CAstControlFlowMap cfg, C context, Map<Pair<CAstNode, K>, CAstNode> nodeMap) {
final List<CAstNode> children = copyChildrenArray(n, cfg, context, nodeMap);
if (cfg != null) {
final Collection<Object> targetLabels = cfg.getTargetLabels(n);
if (targetLabels != null)
for (Object label : targetLabels)
if (label instanceof CAstNode) copyNodes((CAstNode) label, cfg, context, nodeMap);
}
return children;
}
/**
* in {@link #copyFlow(Map, CAstControlFlowMap, CAstSourcePositionMap)}, if the source of some
* original CFG edge is replicated, but we find no replica for the target, what node should be the
* target of the CFG edge in the rewritten AST? By default, just uses the original target.
*/
@SuppressWarnings("unused")
protected CAstNode flowOutTo(
Map<Pair<CAstNode, K>, CAstNode> nodeMap,
CAstNode oldSource,
Object label,
CAstNode oldTarget,
CAstControlFlowMap orig,
CAstSourcePositionMap src) {
return oldTarget;
}
/**
* create a control-flow map for the rewritten tree, given the mapping from (original node, copy
* key) pairs ot new nodes and the original control-flow map.
*/
protected CAstControlFlowMap copyFlow(
Map<Pair<CAstNode, K>, CAstNode> nodeMap,
CAstControlFlowMap orig,
CAstSourcePositionMap newSrc) {
// the new control-flow map
final CAstControlFlowRecorder newMap = new CAstControlFlowRecorder(newSrc);
// tracks which CAstNodes not present in nodeMap's key set (under any copy
// key) are added as targets of CFG edges
// via a call to flowOutTo() (see below); used to ensure these nodes are
// only mapped to themselves once in newMap
final Set<CAstNode> mappedOutsideNodes = HashSetFactory.make(1);
// all edge targets in new control-flow map; must all be mapped to
// themselves
Set<CAstNode> allNewTargetNodes = HashSetFactory.make(1);
Collection<CAstNode> oldSources = orig.getMappedNodes();
for (Entry<Pair<CAstNode, K>, CAstNode> entry : nodeMap.entrySet()) {
Pair<CAstNode, K> N = entry.getKey();
CAstNode oldSource = N.fst;
K key = N.snd;
CAstNode newSource = entry.getValue();
assert newSource != null;
newMap.map(newSource, newSource);
if (DEBUG) {
System.err.println(("\n\nlooking at " + key + ':' + CAstPrinter.print(oldSource)));
}
if (oldSources.contains(oldSource)) {
// if (orig.getTarget(oldSource, null) != null) {
// LS = IteratorPlusOne.make(LS, null);
// }
for (Object origLabel : orig.getTargetLabels(oldSource)) {
CAstNode oldTarget = orig.getTarget(oldSource, origLabel);
assert oldTarget != null;
if (DEBUG) {
System.err.println(("old: " + origLabel + " --> " + CAstPrinter.print(oldTarget)));
}
// try to find a k in key's parent chain such that (oldTarget, k) is
// in nodeMap's key set
Pair<CAstNode, CopyKey<K>> targetKey;
CopyKey<K> k = key;
do {
targetKey = Pair.make(oldTarget, k);
if (k != null) {
k = k.parent();
} else {
break;
}
} while (!nodeMap.containsKey(targetKey));
Object newLabel;
if (nodeMap.containsKey(Pair.make(origLabel, targetKey.snd))) { // label
// is
// mapped
// too
newLabel = nodeMap.get(Pair.make(origLabel, targetKey.snd));
} else {
newLabel = origLabel;
}
CAstNode newTarget;
if (nodeMap.containsKey(targetKey)) {
newTarget = nodeMap.get(targetKey);
newMap.add(newSource, newTarget, newLabel);
allNewTargetNodes.add(newTarget);
} else {
// could not discover target of CFG edge in nodeMap under any key related to the current
// source key.
// the edge might have been deleted, or it may end at a node above the root where we
// were
// rewriting
// ask flowOutTo() to just choose a target
newTarget = flowOutTo(nodeMap, oldSource, origLabel, oldTarget, orig, newSrc);
allNewTargetNodes.add(newTarget);
newMap.add(newSource, newTarget, newLabel);
if (newTarget != CAstControlFlowMap.EXCEPTION_TO_EXIT
&& !mappedOutsideNodes.contains(newTarget)) {
mappedOutsideNodes.add(newTarget);
newMap.map(newTarget, newTarget);
}
}
if (DEBUG) {
System.err.println(
("mapping:old: "
+ CAstPrinter.print(oldSource)
+ "-- "
+ origLabel
+ " --> "
+ CAstPrinter.print(oldTarget)));
System.err.println(
("mapping:new: "
+ CAstPrinter.print(newSource)
+ "-- "
+ newLabel
+ " --> "
+ CAstPrinter.print(newTarget)));
}
}
}
}
allNewTargetNodes.removeAll(newMap.getMappedNodes());
for (CAstNode newTarget : allNewTargetNodes) {
if (newTarget != CAstControlFlowMap.EXCEPTION_TO_EXIT) {
newMap.map(newTarget, newTarget);
}
}
assert !oldNodesInNewMap(nodeMap, newMap);
return newMap;
}
// check whether newMap contains any CFG edges involving nodes in the domain of nodeMap
private boolean oldNodesInNewMap(
Map<Pair<CAstNode, K>, CAstNode> nodeMap, final CAstControlFlowRecorder newMap) {
HashSet<CAstNode> oldNodes = HashSetFactory.make();
for (Entry<Pair<CAstNode, K>, CAstNode> e : nodeMap.entrySet()) oldNodes.add(e.getKey().fst);
for (CAstNode mappedNode : newMap.getMappedNodes()) {
if (oldNodes.contains(mappedNode)) return true;
for (Object lbl : newMap.getTargetLabels(mappedNode))
if (oldNodes.contains(newMap.getTarget(mappedNode, lbl))) return true;
}
return false;
}
protected CAstSourcePositionMap copySource(
Map<Pair<CAstNode, K>, CAstNode> nodeMap, CAstSourcePositionMap orig) {
CAstSourcePositionRecorder newMap = new CAstSourcePositionRecorder();
for (Entry<Pair<CAstNode, K>, CAstNode> entry : nodeMap.entrySet()) {
Pair<CAstNode, K> N = entry.getKey();
CAstNode oldNode = N.fst;
CAstNode newNode = entry.getValue();
if (orig.getPosition(oldNode) != null) {
newMap.setPosition(newNode, orig.getPosition(oldNode));
}
}
return newMap;
}
protected CAstNodeTypeMap copyTypes(
Map<Pair<CAstNode, K>, CAstNode> nodeMap, CAstNodeTypeMap orig) {
if (orig != null) {
CAstNodeTypeMapRecorder newMap = new CAstNodeTypeMapRecorder();
for (Entry<Pair<CAstNode, K>, CAstNode> entry : nodeMap.entrySet()) {
Pair<CAstNode, K> N = entry.getKey();
CAstNode oldNode = N.fst;
CAstNode newNode = entry.getValue();
if (orig.getNodeType(oldNode) != null) {
newMap.add(newNode, orig.getNodeType(oldNode));
}
}
return newMap;
} else {
return null;
}
}
protected Map<CAstNode, Collection<CAstEntity>> copyChildren(
@SuppressWarnings("unused") CAstNode root,
Map<Pair<CAstNode, K>, CAstNode> nodeMap,
Map<CAstNode, Collection<CAstEntity>> children) {
final Map<CAstNode, Collection<CAstEntity>> newChildren = new LinkedHashMap<>();
for (Entry<Pair<CAstNode, K>, CAstNode> entry : nodeMap.entrySet()) {
Pair<CAstNode, K> N = entry.getKey();
CAstNode oldNode = N.fst;
CAstNode newNode = entry.getValue();
if (children.containsKey(oldNode)) {
Set<CAstEntity> newEntities = new LinkedHashSet<>();
newChildren.put(newNode, newEntities);
for (CAstEntity cAstEntity : children.get(oldNode)) {
newEntities.add(rewrite(cAstEntity));
}
}
}
for (Entry<CAstNode, Collection<CAstEntity>> entry : children.entrySet()) {
CAstNode key = entry.getKey();
if (key == null) {
Set<CAstEntity> newEntities = new LinkedHashSet<>();
newChildren.put(key, newEntities);
for (CAstEntity oldEntity : entry.getValue()) {
newEntities.add(rewrite(oldEntity));
}
}
}
return newChildren;
}
/** rewrite the CAst sub-tree rooted at root */
public Rewrite rewrite(
final CAstNode root,
final CAstControlFlowMap cfg,
final CAstSourcePositionMap pos,
final CAstNodeTypeMap types,
final Map<CAstNode, Collection<CAstEntity>> children,
final CAstNode[] defaults) {
final Map<Pair<CAstNode, K>, CAstNode> nodes = HashMapFactory.make();
final CAstNode newRoot = copyNodes(root, cfg, rootContext, nodes);
final CAstNode newDefaults[] = new CAstNode[defaults == null ? 0 : defaults.length];
for (int i = 0; i < newDefaults.length; i++) {
newDefaults[i] = copyNodes(defaults[i], cfg, rootContext, nodes);
}
return new Rewrite() {
private CAstControlFlowMap theCfg = null;
private CAstSourcePositionMap theSource = null;
private CAstNodeTypeMap theTypes = null;
private Map<CAstNode, Collection<CAstEntity>> theChildren = null;
@Override
public CAstNode[] newDefaults() {
return newDefaults;
}
@Override
public CAstNode newRoot() {
return newRoot;
}
@Override
public CAstControlFlowMap newCfg() {
if (theCfg == null && cfg != null) theCfg = copyFlow(nodes, cfg, newPos());
return theCfg;
}
@Override
public CAstSourcePositionMap newPos() {
if (theSource == null && pos != null) theSource = copySource(nodes, pos);
return theSource;
}
@Override
public CAstNodeTypeMap newTypes() {
if (theTypes == null && types != null) theTypes = copyTypes(nodes, types);
return theTypes;
}
@Override
public Map<CAstNode, Collection<CAstEntity>> newChildren() {
if (theChildren == null) theChildren = copyChildren(root, nodes, children);
return theChildren;
}
};
}
/**
* perform the rewrite on a {@link CAstEntity}, returning the new {@link CAstEntity} as the result
*/
public CAstEntity rewrite(final CAstEntity root) {
if (root.getAST() != null) {
final Rewrite rewrite =
rewrite(
root.getAST(),
root.getControlFlow(),
root.getSourceMap(),
root.getNodeTypeMap(),
root.getAllScopedEntities(),
root.getArgumentDefaults());
return new DelegatingEntity(root) {
@Override
public String toString() {
return root + " (clone)";
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
Map<CAstNode, Collection<CAstEntity>> newChildren = getAllScopedEntities();
if (newChildren.containsKey(construct)) {
return newChildren.get(construct).iterator();
} else {
return EmptyIterator.instance();
}
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
return rewrite.newChildren();
}
@Override
public CAstNode getAST() {
return rewrite.newRoot();
}
@Override
public CAstNodeTypeMap getNodeTypeMap() {
return rewrite.newTypes();
}
@Override
public CAstSourcePositionMap getSourceMap() {
return rewrite.newPos();
}
@Override
public CAstControlFlowMap getControlFlow() {
return rewrite.newCfg();
}
@Override
public CAstNode[] getArgumentDefaults() {
return rewrite.newDefaults();
}
};
} else if (recursive) {
Map<CAstNode, Collection<CAstEntity>> children = root.getAllScopedEntities();
final Map<CAstNode, Collection<CAstEntity>> newChildren = new LinkedHashMap<>();
for (Entry<CAstNode, Collection<CAstEntity>> entry : children.entrySet()) {
CAstNode key = entry.getKey();
Set<CAstEntity> newValues = new LinkedHashSet<>();
newChildren.put(key, newValues);
for (CAstEntity entity : entry.getValue()) {
newValues.add(rewrite(entity));
}
}
return new DelegatingEntity(root) {
@Override
public String toString() {
return root + " (clone)";
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
if (newChildren.containsKey(construct)) {
return newChildren.get(construct).iterator();
} else {
return EmptyIterator.instance();
}
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
return newChildren;
}
};
} else {
return root;
}
}
}
| 18,126
| 32.078467
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/CAstRewriterFactory.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.tree.rewrite;
import com.ibm.wala.cast.tree.CAst;
public interface CAstRewriterFactory<
C extends CAstRewriter.RewriteContext<K>, K extends CAstRewriter.CopyKey<K>> {
CAstRewriter<C, K> createCAstRewriter(CAst ast);
}
| 621
| 30.1
| 82
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/rewrite/PatternBasedRewriter.java
|
package com.ibm.wala.cast.tree.rewrite;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.util.CAstPattern;
import com.ibm.wala.cast.util.CAstPattern.Segments;
import com.ibm.wala.util.collections.Pair;
import java.util.Map;
import java.util.function.Function;
public class PatternBasedRewriter extends CAstCloner {
private final CAstPattern pattern;
private final Function<Segments, CAstNode> rewrite;
public PatternBasedRewriter(CAst ast, CAstPattern pattern, Function<Segments, CAstNode> rewrite) {
super(ast, true);
this.pattern = pattern;
this.rewrite = rewrite;
}
@Override
protected CAstNode copyNodes(
CAstNode root,
CAstControlFlowMap cfg,
NonCopyingContext context,
Map<Pair<CAstNode, NoKey>, CAstNode> nodeMap) {
final Pair<CAstNode, NoKey> pairKey = Pair.make(root, context.key());
Segments s = CAstPattern.match(pattern, root);
if (s != null) {
CAstNode replacement = rewrite.apply(s);
nodeMap.put(pairKey, replacement);
return replacement;
} else return copyNodes(root, cfg, context, nodeMap, pairKey);
}
}
| 1,211
| 30.894737
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/visit/CAstVisitor.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.tree.visit;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.util.CAstPrinter;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/** @author Igor Peshansky Ripped out of Julian's AstTranslator TODO: document me. */
public abstract class CAstVisitor<C extends CAstVisitor.Context> {
public static boolean DEBUG = true;
protected Position currentPosition;
public Position getCurrentPosition() {
return currentPosition;
}
protected CAstVisitor() {}
/**
* This interface represents a visitor-specific context. All it knows is how to get its top-level
* entity. It is expected that visitors will have classes implementing this interface to collect
* visitor-specific information.
*
* @author Igor Peshansky
*/
public interface Context {
CAstEntity top();
CAstSourcePositionMap getSourceMap();
}
/**
* Construct a context for a File entity.
*
* @param context a visitor-specific context in which this file was visited
* @param n the file entity
*/
protected C makeFileContext(C context, CAstEntity n) {
return context;
}
/**
* Construct a context for a Type entity.
*
* @param context a visitor-specific context in which this type was visited
* @param n the type entity
*/
protected C makeTypeContext(C context, CAstEntity n) {
return context;
}
/**
* Construct a context for a Code entity.
*
* @param context a visitor-specific context in which the code was visited
* @param n the code entity
*/
protected C makeCodeContext(C context, CAstEntity n) {
return context;
}
/**
* Construct a context for a LocalScope node.
*
* @param context a visitor-specific context in which the local scope was visited
* @param n the local scope node
*/
protected C makeLocalContext(C context, CAstNode n) {
return context;
}
/**
* Construct a context for an Unwind node.
*
* @param context a visitor-specific context in which the unwind was visited
* @param n the unwind node
*/
protected C makeUnwindContext(
C context, CAstNode n, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return context;
}
private final Map<CAstEntity, CAstEntity> entityParents = HashMapFactory.make();
/**
* Get the parent entity for a given entity.
*
* @param entity the child entity
* @return the parent entity for the given entity
*/
protected CAstEntity getParent(CAstEntity entity) {
return entityParents.get(entity);
}
/**
* Set the parent entity for a given entity.
*
* @param entity the child entity
* @param parent the parent entity
*/
protected void setParent(CAstEntity entity, CAstEntity parent) {
entityParents.put(entity, parent);
}
/**
* Entity processing hook; sub-classes are expected to override if they introduce new entity
* types. Should invoke super.doVisitEntity() for unprocessed entities.
*
* @return true if entity was handled
*/
@SuppressWarnings("unused")
protected boolean doVisitEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return false;
}
/**
* Visit scoped entities of an entity using a given iterator. Prerequisite (unchecked): i iterates
* over entities scoped in n.
*
* @param n the parent entity of the entities to process
* @param context a visitor-specific context
*/
public final void visitScopedEntities(
CAstEntity n,
Map<CAstNode, Collection<CAstEntity>> allScopedEntities,
C context,
CAstVisitor<C> visitor) {
for (Collection<CAstEntity> collection : allScopedEntities.values()) {
visitScopedEntities(n, collection.iterator(), context, visitor);
}
}
public final void visitScopedEntities(
CAstEntity n, Iterator<CAstEntity> i, C context, CAstVisitor<C> visitor) {
while (i.hasNext()) {
CAstEntity child = i.next();
setParent(child, n);
visitor.visitEntities(child, context, visitor);
}
}
protected C getCodeContext(C context) {
return context;
}
/**
* Recursively visit an entity.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
public final void visitEntities(final CAstEntity n, C context, CAstVisitor<C> visitor) {
Position restore = currentPosition;
if (n.getPosition() != null) {
currentPosition = n.getPosition();
} else {
currentPosition = null;
}
if (visitor.enterEntity(n, context, visitor)) return;
switch (n.getKind()) {
case CAstEntity.FILE_ENTITY:
{
C fileContext = visitor.makeFileContext(context, n);
if (visitor.visitFileEntity(n, context, fileContext, visitor)) break;
visitor.visitScopedEntities(n, n.getAllScopedEntities(), fileContext, visitor);
visitor.leaveFileEntity(n, context, fileContext, visitor);
break;
}
case CAstEntity.FIELD_ENTITY:
{
if (visitor.visitFieldEntity(n, context, visitor)) break;
visitor.leaveFieldEntity(n, context, visitor);
break;
}
case CAstEntity.GLOBAL_ENTITY:
{
if (visitor.visitGlobalEntity(n, context, visitor)) break;
visitor.leaveGlobalEntity(n, context, visitor);
break;
}
case CAstEntity.TYPE_ENTITY:
{
C typeContext = visitor.makeTypeContext(context, n);
if (visitor.visitTypeEntity(n, context, typeContext, visitor)) break;
visitor.visitScopedEntities(n, n.getAllScopedEntities(), typeContext, visitor);
visitor.leaveTypeEntity(n, context, typeContext, visitor);
break;
}
case CAstEntity.FUNCTION_ENTITY:
{
for (CAstNode dflt : n.getArgumentDefaults()) {
visitor.visit(dflt, getCodeContext(context), visitor);
visitor.visitScopedEntities(
context.top(), context.top().getScopedEntities(dflt), context, visitor);
}
C codeContext = visitor.makeCodeContext(context, n);
if (visitor.visitFunctionEntity(n, context, codeContext, visitor)) break;
// visit the AST if any
if (n.getAST() != null) visitor.visit(n.getAST(), codeContext, visitor);
// XXX: there may be code that needs to go in here
// process any remaining scoped children
visitor.visitScopedEntities(n, n.getScopedEntities(null), codeContext, visitor);
visitor.leaveFunctionEntity(n, context, codeContext, visitor);
break;
}
case CAstEntity.MACRO_ENTITY:
{
C codeContext = visitor.makeCodeContext(context, n);
if (visitor.visitMacroEntity(n, context, codeContext, visitor)) break;
// visit the AST if any
if (n.getAST() != null) visitor.visit(n.getAST(), codeContext, visitor);
// XXX: there may be code that needs to go in here
// process any remaining scoped children
visitor.visitScopedEntities(n, n.getScopedEntities(null), codeContext, visitor);
visitor.leaveMacroEntity(n, context, codeContext, visitor);
break;
}
case CAstEntity.SCRIPT_ENTITY:
{
C codeContext = visitor.makeCodeContext(context, n);
if (visitor.visitScriptEntity(n, context, codeContext, visitor)) break;
// visit the AST if any
if (n.getAST() != null) visitor.visit(n.getAST(), codeContext, visitor);
// XXX: there may be code that needs to go in here
// process any remaining scoped children
visitor.visitScopedEntities(n, n.getScopedEntities(null), codeContext, visitor);
visitor.leaveScriptEntity(n, context, codeContext, visitor);
break;
}
default:
{
if (!visitor.doVisitEntity(n, context, visitor)) {
System.err.println(("No handler for entity " + n.getName()));
Assertions.UNREACHABLE("cannot handle entity of kind" + n.getKind());
}
}
}
visitor.postProcessEntity(n, context, visitor);
currentPosition = restore;
}
/**
* Enter the entity visitor.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean enterEntity(
CAstEntity n, C context, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return false;
}
/**
* Post-process an entity after visiting it.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
protected void postProcessEntity(
CAstEntity n, C context, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return;
}
/**
* Visit any entity. Override only this to change behavior for all entities.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
public boolean visitEntity(
CAstEntity n, C context, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return false;
}
/**
* Leave any entity. Override only this to change behavior for all entities.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
public void leaveEntity(
CAstEntity n, C context, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return;
}
/**
* Visit a File entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param fileC a visitor-specific context for this file
* @return true if no further processing is needed
*/
protected boolean visitFileEntity(CAstEntity n, C context, C fileC, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a File entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param fileContext a visitor-specific context for this file
*/
protected void leaveFileEntity(CAstEntity n, C context, C fileContext, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Visit a Field entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitFieldEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a Field entity.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
protected void leaveFieldEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Visit a Field entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitGlobalEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a Field entity.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
protected void leaveGlobalEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Visit a Type entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param typeContext a visitor-specific context for this type
* @return true if no further processing is needed
*/
protected boolean visitTypeEntity(
CAstEntity n, C context, C typeContext, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a Type entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param typeContext a visitor-specific context for this type
*/
protected void leaveTypeEntity(CAstEntity n, C context, C typeContext, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Visit a Function entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this function
* @return true if no further processing is needed
*/
protected boolean visitFunctionEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a Function entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this function
*/
protected void leaveFunctionEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Visit a Macro entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this macro
* @return true if no further processing is needed
*/
protected boolean visitMacroEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a Macro entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this macro
*/
protected void leaveMacroEntity(CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Visit a Script entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this script
* @return true if no further processing is needed
*/
protected boolean visitScriptEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
return visitor.visitEntity(n, context, visitor);
}
/**
* Leave a Script entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this script
*/
protected void leaveScriptEntity(CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
visitor.leaveEntity(n, context, visitor);
}
/**
* Node processing hook; sub-classes are expected to override if they introduce new node types.
*
* <p>(Should invoke super.doVisit() for unprocessed nodes.)
*
* @return true if node was handled
*/
@SuppressWarnings("unused")
protected boolean doVisit(CAstNode n, C context, CAstVisitor<C> visitor) {
return false;
}
/**
* Node processing hook; sub-classes are expected to override if they introduce new node types
* that appear on the left hand side of assignment operations.
*
* <p>(Should invoke super.doVisit() for unprocessed nodes.)
*
* @return true if node was handled
*/
@SuppressWarnings("unused")
protected boolean doVisitAssignNodes(
CAstNode n, C context, CAstNode v, CAstNode a, CAstVisitor<C> visitor) {
return false;
}
/**
* Visit children of a node starting at a given index.
*
* @param n the parent node of the nodes to process
* @param start the starting index of the nodes to process
* @param context a visitor-specific context
*/
public final void visitChildren(CAstNode n, int start, C context, CAstVisitor<C> visitor) {
int end = n.getChildCount();
for (int i = start; i < end; i++) visitor.visit(n.getChild(i), context, visitor);
}
/**
* Visit all children of a node.
*
* @param n the parent node of the nodes to process
* @param context a visitor-specific context
*/
public final void visitAllChildren(CAstNode n, C context, CAstVisitor<C> visitor) {
visitor.visitChildren(n, 0, context, visitor);
}
/**
* Recursively visit a given node. TODO: do assertions about structure belong here?
*
* @param n the node to process
* @param context a visitor-specific context
*/
public final void visit(final CAstNode n, C context, CAstVisitor<C> visitor) {
Position restore = currentPosition;
if (context != null && context.getSourceMap() != null) {
Position p = context.getSourceMap().getPosition(n);
if (p != null) {
currentPosition = p;
}
}
if (visitor.enterNode(n, context, visitor)) return;
int NT = n.getKind();
switch (NT) {
case CAstNode.FUNCTION_EXPR:
{
if (visitor.visitFunctionExpr(n, context, visitor)) break;
visitor.leaveFunctionExpr(n, context, visitor);
break;
}
case CAstNode.FUNCTION_STMT:
{
if (visitor.visitFunctionStmt(n, context, visitor)) break;
visitor.leaveFunctionStmt(n, context, visitor);
break;
}
case CAstNode.CLASS_STMT:
{
if (visitor.visitClassStmt(n, context, visitor)) break;
visitor.leaveClassStmt(n, context, visitor);
break;
}
case CAstNode.LOCAL_SCOPE:
{
if (visitor.visitLocalScope(n, context, visitor)) break;
C localContext = visitor.makeLocalContext(context, n);
visitor.visit(n.getChild(0), localContext, visitor);
visitor.leaveLocalScope(n, context, visitor);
break;
}
case CAstNode.SPECIAL_PARENT_SCOPE:
{
if (visitor.visitSpecialParentScope(n, context, visitor)) break;
C localContext = visitor.makeSpecialParentContext(context, n);
visitor.visit(n.getChild(1), localContext, visitor);
visitor.leaveSpecialParentScope(n, context, visitor);
break;
}
case CAstNode.BLOCK_EXPR:
{
if (visitor.visitBlockExpr(n, context, visitor)) break;
visitor.visitAllChildren(n, context, visitor);
visitor.leaveBlockExpr(n, context, visitor);
break;
}
case CAstNode.BLOCK_STMT:
{
if (visitor.visitBlockStmt(n, context, visitor)) break;
visitor.visitAllChildren(n, context, visitor);
visitor.leaveBlockStmt(n, context, visitor);
break;
}
case CAstNode.LOOP:
{
if (visitor.visitLoop(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveLoopHeader(n, context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveLoop(n, context, visitor);
break;
}
case CAstNode.FORIN_LOOP:
{
if (visitor.visitForIn(n, context, visitor)) {
break;
}
visitor.leaveForIn(n, context, visitor);
break;
}
case CAstNode.GET_CAUGHT_EXCEPTION:
{
if (visitor.visitGetCaughtException(n, context, visitor)) break;
visitor.leaveGetCaughtException(n, context, visitor);
break;
}
case CAstNode.THIS:
{
if (visitor.visitThis(n, context, visitor)) break;
visitor.leaveThis(n, context, visitor);
break;
}
case CAstNode.SUPER:
{
if (visitor.visitSuper(n, context, visitor)) break;
visitor.leaveSuper(n, context, visitor);
break;
}
case CAstNode.CALL:
{
if (visitor.visitCall(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.visitChildren(n, 2, context, visitor);
visitor.leaveCall(n, context, visitor);
break;
}
case CAstNode.VAR:
{
if (visitor.visitVar(n, context, visitor)) break;
visitor.leaveVar(n, context, visitor);
break;
}
case CAstNode.CONSTANT:
{
if (visitor.visitConstant(n, context, visitor)) break;
visitor.leaveConstant(n, context, visitor);
break;
}
case CAstNode.BINARY_EXPR:
{
if (visitor.visitBinaryExpr(n, context, visitor)) break;
visitor.visit(n.getChild(1), context, visitor);
visitor.visit(n.getChild(2), context, visitor);
visitor.leaveBinaryExpr(n, context, visitor);
break;
}
case CAstNode.UNARY_EXPR:
{
if (visitor.visitUnaryExpr(n, context, visitor)) break;
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveUnaryExpr(n, context, visitor);
break;
}
case CAstNode.ARRAY_LENGTH:
{
if (visitor.visitArrayLength(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveArrayLength(n, context, visitor);
break;
}
case CAstNode.ARRAY_REF:
{
if (visitor.visitArrayRef(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.visitChildren(n, 2, context, visitor);
visitor.leaveArrayRef(n, context, visitor);
break;
}
case CAstNode.DECL_STMT:
{
if (visitor.visitDeclStmt(n, context, visitor)) break;
if (n.getChildCount() == 2) visitor.visit(n.getChild(1), context, visitor);
visitor.leaveDeclStmt(n, context, visitor);
break;
}
case CAstNode.RETURN:
{
if (visitor.visitReturn(n, context, visitor)) break;
if (n.getChildCount() > 0) visitor.visit(n.getChild(0), context, visitor);
visitor.leaveReturn(n, context, visitor);
break;
}
case CAstNode.IFGOTO:
{
if (visitor.visitIfgoto(n, context, visitor)) break;
if (n.getChildCount() == 1) {
visitor.visit(n.getChild(0), context, visitor);
} else if (n.getChildCount() == 3) {
visitor.visit(n.getChild(1), context, visitor);
visitor.visit(n.getChild(2), context, visitor);
} else {
Assertions.UNREACHABLE();
}
visitor.leaveIfgoto(n, context, visitor);
break;
}
case CAstNode.GOTO:
{
if (visitor.visitGoto(n, context, visitor)) break;
visitor.leaveGoto(n, context, visitor);
break;
}
case CAstNode.LABEL_STMT:
{
if (visitor.visitLabelStmt(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
if (n.getChildCount() == 2) visitor.visit(n.getChild(1), context, visitor);
else assert n.getChildCount() < 2;
visitor.leaveLabelStmt(n, context, visitor);
break;
}
case CAstNode.IF_STMT:
{
if (visitor.visitIfStmt(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveIfStmtCondition(n, context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveIfStmtTrueClause(n, context, visitor);
if (n.getChildCount() == 3) visitor.visit(n.getChild(2), context, visitor);
visitor.leaveIfStmt(n, context, visitor);
break;
}
case CAstNode.IF_EXPR:
{
if (visitor.visitIfExpr(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveIfExprCondition(n, context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveIfExprTrueClause(n, context, visitor);
if (n.getChildCount() == 3) visitor.visit(n.getChild(2), context, visitor);
visitor.leaveIfExpr(n, context, visitor);
break;
}
case CAstNode.NEW_ENCLOSING:
case CAstNode.NEW:
{
if (visitor.visitNew(n, context, visitor)) break;
visitChildren(n, 1, context, visitor);
visitor.leaveNew(n, context, visitor);
break;
}
case CAstNode.OBJECT_LITERAL:
{
if (visitor.visitObjectLiteral(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
for (int i = 1; i < n.getChildCount(); i += 2) {
visitor.visit(n.getChild(i), context, visitor);
visitor.visit(n.getChild(i + 1), context, visitor);
visitor.leaveObjectLiteralFieldInit(n, i, context, visitor);
}
visitor.leaveObjectLiteral(n, context, visitor);
break;
}
case CAstNode.ARRAY_LITERAL:
{
if (visitor.visitArrayLiteral(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveArrayLiteralObject(n, context, visitor);
for (int i = 1; i < n.getChildCount(); i++) {
visitor.visit(n.getChild(i), context, visitor);
visitor.leaveArrayLiteralInitElement(n, i, context, visitor);
}
visitor.leaveArrayLiteral(n, context, visitor);
break;
}
case CAstNode.OBJECT_REF:
{
if (visitor.visitObjectRef(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveObjectRef(n, context, visitor);
break;
}
case CAstNode.ASSIGN:
case CAstNode.ASSIGN_PRE_OP:
case CAstNode.ASSIGN_POST_OP:
{
if (visitor.visitAssign(n, context, visitor)) break;
visitor.visit(n.getChild(1), context, visitor);
// TODO: is this correct?
if (visitor.visitAssignNodes(n.getChild(0), context, n.getChild(1), n, visitor)) break;
visitor.leaveAssign(n, context, visitor);
break;
}
case CAstNode.SWITCH:
{
if (visitor.visitSwitch(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveSwitchValue(n, context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveSwitch(n, context, visitor);
break;
}
case CAstNode.THROW:
{
if (visitor.visitThrow(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveThrow(n, context, visitor);
break;
}
case CAstNode.CATCH:
{
if (visitor.visitCatch(n, context, visitor)) break;
visitor.visitChildren(n, 1, context, visitor);
visitor.leaveCatch(n, context, visitor);
break;
}
case CAstNode.UNWIND:
{
if (visitor.visitUnwind(n, context, visitor)) break;
C unwindContext = visitor.makeUnwindContext(context, n.getChild(1), visitor);
visitor.visit(n.getChild(0), unwindContext, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveUnwind(n, context, visitor);
break;
}
case CAstNode.TRY:
{
if (visitor.visitTry(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveTryBlock(n, context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveTry(n, context, visitor);
break;
}
case CAstNode.EMPTY:
{
if (visitor.visitEmpty(n, context, visitor)) break;
visitor.leaveEmpty(n, context, visitor);
break;
}
case CAstNode.PRIMITIVE:
{
if (visitor.visitPrimitive(n, context, visitor)) break;
visitor.visitAllChildren(n, context, visitor);
visitor.leavePrimitive(n, context, visitor);
break;
}
case CAstNode.VOID:
{
if (visitor.visitVoid(n, context, visitor)) break;
visitor.leaveVoid(n, context, visitor);
break;
}
case CAstNode.CAST:
{
if (visitor.visitCast(n, context, visitor)) break;
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveCast(n, context, visitor);
break;
}
case CAstNode.INSTANCEOF:
{
if (visitor.visitInstanceOf(n, context, visitor)) break;
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveInstanceOf(n, context, visitor);
break;
}
case CAstNode.ASSERT:
{
if (visitor.visitAssert(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveAssert(n, context, visitor);
break;
}
case CAstNode.EACH_ELEMENT_GET:
{
if (visitor.visitEachElementGet(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveEachElementGet(n, context, visitor);
break;
}
case CAstNode.EACH_ELEMENT_HAS_NEXT:
{
if (visitor.visitEachElementHasNext(n, context, visitor)) break;
visitor.visit(n.getChild(0), context, visitor);
visitor.visit(n.getChild(1), context, visitor);
visitor.leaveEachElementHasNext(n, context, visitor);
break;
}
case CAstNode.TYPE_LITERAL_EXPR:
{
if (visitor.visitTypeLiteralExpr(n, context, visitor)) {
break;
}
visitor.visit(n.getChild(0), context, visitor);
visitor.leaveTypeLiteralExpr(n, context, visitor);
break;
}
case CAstNode.IS_DEFINED_EXPR:
{
if (visitor.visitIsDefinedExpr(n, context, visitor)) {
break;
}
visitor.visit(n.getChild(0), context, visitor);
if (n.getChildCount() == 2) {
visitor.visit(n.getChild(1), context, visitor);
}
visitor.leaveIsDefinedExpr(n, context, visitor);
break;
}
case CAstNode.INCLUDE:
{
if (visitor.visitInclude(n, context, visitor)) {
break;
}
visitor.leaveInclude(n, context, visitor);
break;
}
case CAstNode.MACRO_VAR:
{
if (visitor.visitMacroVar(n, context, visitor)) {
break;
}
visitor.leaveMacroVar(n, context, visitor);
break;
}
case CAstNode.ECHO:
{
if (visitor.visitEcho(n, context, visitor)) {
break;
}
visitAllChildren(n, context, visitor);
visitor.leaveEcho(n, context, visitor);
break;
}
case CAstNode.RETURN_WITHOUT_BRANCH:
{
if (visitor.visitYield(n, context, visitor)) {
break;
}
visitAllChildren(n, context, visitor);
visitor.leaveYield(n, context, visitor);
break;
}
default:
{
if (!visitor.doVisit(n, context, visitor)) {
System.err.println(
("looking at unhandled " + n + '(' + NT + ')' + " of " + n.getClass()));
Assertions.UNREACHABLE("cannot handle node of kind " + NT);
}
}
}
if (context != null) {
visitor.visitScopedEntities(
context.top(), context.top().getScopedEntities(n), context, visitor);
}
visitor.postProcessNode(n, context, visitor);
currentPosition = restore;
}
protected void leaveSpecialParentScope(CAstNode n, C context, CAstVisitor<C> visitor) {
visitor.leaveNode(n, context, visitor);
}
protected C makeSpecialParentContext(C context, @SuppressWarnings("unused") CAstNode n) {
return context;
}
protected boolean visitSpecialParentScope(CAstNode n, C context, CAstVisitor<C> visitor) {
return visitor.visitNode(n, context, visitor);
}
/**
* Process the given array reference node. Factored out so that derived languages can reuse this
* code for specially-marked types of array references (as in X10, for which different instruction
* types get generated, but whose structure is essentially the same as an ordinary array
* reference).
*/
protected boolean doVisitArrayRefNode(
CAstNode n,
CAstNode v,
CAstNode a,
boolean assign,
boolean preOp,
C context,
CAstVisitor<C> visitor) {
if (assign
? visitor.visitArrayRefAssign(n, v, a, context, visitor)
: visitor.visitArrayRefAssignOp(n, v, a, preOp, context, visitor)) return true;
visitor.visit(n.getChild(0), context, visitor);
// XXX: we don't really need to visit array dims twice!
visitor.visitChildren(n, 2, context, visitor);
if (assign) visitor.leaveArrayRefAssign(n, v, a, context, visitor);
else visitor.leaveArrayRefAssignOp(n, v, a, preOp, context, visitor);
return false;
}
protected boolean visitAssignNodes(
CAstNode n, C context, CAstNode v, CAstNode a, CAstVisitor<C> visitor) {
int NT = a.getKind();
boolean assign = NT == CAstNode.ASSIGN;
boolean preOp = NT == CAstNode.ASSIGN_PRE_OP;
switch (n.getKind()) {
case CAstNode.ARRAY_REF:
{
if (doVisitArrayRefNode(n, v, a, assign, preOp, context, visitor)) {
return true;
}
break;
}
case CAstNode.OBJECT_REF:
{
if (assign
? visitor.visitObjectRefAssign(n, v, a, context, visitor)
: visitor.visitObjectRefAssignOp(n, v, a, preOp, context, visitor)) return true;
visitor.visit(n.getChild(0), context, visitor);
if (assign) visitor.leaveObjectRefAssign(n, v, a, context, visitor);
else visitor.leaveObjectRefAssignOp(n, v, a, preOp, context, visitor);
break;
}
case CAstNode.BLOCK_EXPR:
{
if (assign
? visitor.visitBlockExprAssign(n, v, a, context, visitor)
: visitor.visitBlockExprAssignOp(n, v, a, preOp, context, visitor)) return true;
// FIXME: is it correct to ignore all the other children?
if (visitor.visitAssignNodes(n.getChild(n.getChildCount() - 1), context, v, a, visitor))
return true;
if (assign) visitor.leaveBlockExprAssign(n, v, a, context, visitor);
else visitor.leaveBlockExprAssignOp(n, v, a, preOp, context, visitor);
break;
}
case CAstNode.VAR:
{
if (assign
? visitor.visitVarAssign(n, v, a, context, visitor)
: visitor.visitVarAssignOp(n, v, a, preOp, context, visitor)) return true;
if (assign) visitor.leaveVarAssign(n, v, a, context, visitor);
else visitor.leaveVarAssignOp(n, v, a, preOp, context, visitor);
break;
}
case CAstNode.ARRAY_LITERAL:
{
assert assign;
if (visitor.visitArrayLiteralAssign(n, v, a, context, visitor)) return true;
visitor.leaveArrayLiteralAssign(n, v, a, context, visitor);
break;
}
case CAstNode.OBJECT_LITERAL:
{
assert assign;
for (int i = 1; i < n.getChildCount(); i += 2) {
visitor.visit(n.getChild(i), context, visitor);
}
if (visitor.visitObjectLiteralAssign(n, v, a, context, visitor)) return true;
visitor.leaveObjectLiteralAssign(n, v, a, context, visitor);
break;
}
default:
{
if (!visitor.doVisitAssignNodes(n, context, a, v, visitor)) {
if (DEBUG) {
System.err.println(("cannot handle assign to kind " + n.getKind()));
}
throw new UnsupportedOperationException(
"cannot handle assignment: " + CAstPrinter.print(a, context.getSourceMap()));
}
}
}
return false;
}
/**
* Enter the node visitor.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean enterNode(CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return false;
}
/**
* Post-process a node after visiting it.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void postProcessNode(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return;
}
/**
* Visit any node. Override only this to change behavior for all nodes.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
public boolean visitNode(CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return false;
}
/**
* Leave any node. Override only this to change behavior for all nodes.
*
* @param n the node to process
* @param c a visitor-specific context
*/
public void leaveNode(CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
return;
}
/**
* Visit a FunctionExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitFunctionExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a FunctionExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveFunctionExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitFunctionStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveFunctionStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitClassStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveClassStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a LocalScope node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitLocalScope(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a LocalScope node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveLocalScope(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a BlockExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitBlockExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a BlockExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveBlockExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a BlockStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitBlockStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a BlockStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveBlockStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Loop node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitLoop(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit a For..In node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitForIn(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit a Loop node after processing the loop header.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveLoopHeader(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave a Loop node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveLoop(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Leave a For..In node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveForIn(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a GetCaughtException node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitGetCaughtException(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a GetCaughtException node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveGetCaughtException(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a This node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitThis(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a This node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveThis(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Super node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitSuper(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Super node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveSuper(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Call node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitCall(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Call node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveCall(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Var node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitVar(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Var node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveVar(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Constant node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitConstant(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Constant node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveConstant(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a BinaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitBinaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a BinaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveBinaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a UnaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitUnaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a UnaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveUnaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an ArrayLength node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitArrayLength(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an ArrayLength node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveArrayLength(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an ArrayRef node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitArrayRef(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an ArrayRef node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveArrayRef(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a DeclStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitDeclStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a DeclStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveDeclStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Return node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitReturn(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Return node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveReturn(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Return node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitYield(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Return node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveYield(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an Ifgoto node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitIfgoto(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an Ifgoto node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfgoto(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Goto node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitGoto(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Goto node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveGoto(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a LabelStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitLabelStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a LabelStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveLabelStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an IfStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitIfStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit an IfStmt node after processing the condition.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfStmtCondition(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an IfStmt node after processing the true clause.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfStmtTrueClause(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave an IfStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an IfExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitIfExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit an IfExpr node after processing the condition.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfExprCondition(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an IfExpr node after processing the true clause.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfExprTrueClause(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave an IfExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIfExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a New node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitNew(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a New node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveNew(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an ObjectLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitObjectLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit an ObjectLiteral node after processing the {i}th field initializer.
*
* @param n the node to process
* @param i the field position that was initialized
* @param c a visitor-specific context
*/
protected void leaveObjectLiteralFieldInit(
CAstNode n, int i, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave an ObjectLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveObjectLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an ArrayLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitArrayLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit an ArrayLiteral node after processing the array object.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveArrayLiteralObject(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an ArrayLiteral node after processing the {i}th element initializer.
*
* @param n the node to process
* @param i the index that was initialized
* @param c a visitor-specific context
*/
protected void leaveArrayLiteralInitElement(
CAstNode n, int i, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave a ArrayLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveArrayLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an ObjectRef node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitObjectRef(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an ObjectRef node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveObjectRef(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an Assign node. Override only this to change behavior for all assignment nodes.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
public boolean visitAssign(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an Assign node. Override only this to change behavior for all assignment nodes.
*
* @param n the node to process
* @param c a visitor-specific context
*/
public void leaveAssign(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an ArrayRef Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitArrayRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit an ArrayRef Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
protected void leaveArrayRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an ArrayRef Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitArrayRefAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit an ArrayRef Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
protected void leaveArrayRefAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an ObjectRef Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitObjectRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit an ObjectRef Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
protected void leaveObjectRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an ObjectRef Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitObjectRefAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit an ObjectRef Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
protected void leaveObjectRefAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit a BlockExpr Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitBlockExprAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit a BlockExpr Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
protected void leaveBlockExprAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit a BlockExpr Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitBlockExprAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit a BlockExpr Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
protected void leaveBlockExprAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit a Var Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitVarAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit a Var Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
protected void leaveVarAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an array literal Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitArrayLiteralAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit an array literal Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
protected void leaveArrayLiteralAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit an array literal Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitObjectLiteralAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit an array literal Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
protected void leaveObjectLiteralAssign(
CAstNode n, CAstNode v, CAstNode a, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit a Var Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitVarAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
return false;
}
/**
* Visit a Var Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
protected void leaveVarAssignOp(
CAstNode n,
CAstNode v,
CAstNode a,
boolean pre,
C c,
@SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Visit a Switch node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitSwitch(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit a Switch node after processing the switch value.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveSwitchValue(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave a Switch node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveSwitch(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Throw node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitThrow(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Throw node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveThrow(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Catch node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitCatch(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Catch node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveCatch(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an Unwind node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitUnwind(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an Unwind node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveUnwind(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Try node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitTry(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Visit a Try node after processing the try block.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveTryBlock(
CAstNode n, C c, @SuppressWarnings("unused") CAstVisitor<C> visitor) {
/* empty */
}
/**
* Leave a Try node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveTry(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an Empty node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitEmpty(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an Empty node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveEmpty(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Primitive node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitPrimitive(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Primitive node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leavePrimitive(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Void node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitVoid(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Void node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveVoid(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit a Cast node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitCast(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave a Cast node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveCast(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitInstanceOf(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveInstanceOf(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveAssert(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
protected boolean visitAssert(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected boolean visitEachElementHasNext(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
protected void leaveEachElementHasNext(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitEachElementGet(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an FOR_EACH_ELEMENT_GET node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveEachElementGet(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
/**
* Visit an TYPE_LITERAL_EXPR node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
protected boolean visitTypeLiteralExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an TYPE_LITERAL_EXPR node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveTypeLiteralExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
protected boolean visitIsDefinedExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an IS_DEFINED_EXPR node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveIsDefinedExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
protected boolean visitEcho(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an ECHO node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveEcho(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
protected boolean visitInclude(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an INCLUDE node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveInclude(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
protected boolean visitMacroVar(CAstNode n, C c, CAstVisitor<C> visitor) {
return visitor.visitNode(n, c, visitor);
}
/**
* Leave an MACRO_VAR node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
protected void leaveMacroVar(CAstNode n, C c, CAstVisitor<C> visitor) {
visitor.leaveNode(n, c, visitor);
}
}
| 75,856
| 29.848719
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/tree/visit/DelegatingCAstVisitor.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.tree.visit;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
/**
* Extend {@link CAstVisitor}{@code <C>} to delegate unimplemented functionality to another visitor.
* Needed to work around Java's retarded multiple inheritance rules. TODO: document me.
*
* @author Igor Peshansky
*/
public abstract class DelegatingCAstVisitor<C extends CAstVisitor.Context> extends CAstVisitor<C> {
/**
* Construct a context for a File entity or delegate by default.
*
* @param context a visitor-specific context in which this file was visited
* @param n the file entity
*/
@Override
protected C makeFileContext(C context, CAstEntity n) {
return delegate.makeFileContext(context, n);
}
/**
* Construct a context for a Type entity or delegate by default.
*
* @param context a visitor-specific context in which this type was visited
* @param n the type entity
*/
@Override
protected C makeTypeContext(C context, CAstEntity n) {
return delegate.makeTypeContext(context, n);
}
/**
* Construct a context for a Code entity or delegate by default.
*
* @param context a visitor-specific context in which the code was visited
* @param n the code entity
*/
@Override
protected C makeCodeContext(C context, CAstEntity n) {
return delegate.makeCodeContext(context, n);
}
/**
* Construct a context for a LocalScope node or delegate by default.
*
* @param context a visitor-specific context in which the local scope was visited
* @param n the local scope node
*/
@Override
protected C makeLocalContext(C context, CAstNode n) {
return delegate.makeLocalContext(context, n);
}
/**
* Construct a context for an Unwind node or delegate by default.
*
* @param context a visitor-specific context in which the unwind was visited
* @param n the unwind node
*/
@Override
protected C makeUnwindContext(C context, CAstNode n, CAstVisitor<C> visitor) {
return delegate.makeUnwindContext(context, n, visitor);
}
/**
* Get the parent entity for a given entity.
*
* @param entity the child entity
* @return the parent entity for the given entity
*/
@Override
protected CAstEntity getParent(CAstEntity entity) {
return delegate.getParent(entity);
}
/**
* Set the parent entity for a given entity.
*
* @param entity the child entity
* @param parent the parent entity
*/
@Override
protected void setParent(CAstEntity entity, CAstEntity parent) {
delegate.setParent(entity, parent);
}
private final CAstVisitor<C> delegate;
protected final CAstVisitor<C> delegate() {
return delegate;
}
/**
* Delegating {@link CAstVisitor}{@code <C>} constructor. Needs to have a valid (non-null)
* delegate visitor.
*
* @param delegate the visitor to delegate to for default implementation
*/
protected DelegatingCAstVisitor(CAstVisitor<C> delegate) {
assert delegate != null;
this.delegate = delegate;
}
/**
* Entity processing hook; sub-classes are expected to override if they introduce new entity
* types. Should invoke super.doVisitEntity() for unprocessed entities.
*
* @return true if entity was handled
*/
@Override
protected boolean doVisitEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return delegate.doVisitEntity(n, context, visitor);
}
/**
* Enter the entity visitor.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean enterEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return delegate.enterEntity(n, context, visitor);
}
/**
* Post-process an entity after visiting it.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
@Override
protected void postProcessEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
delegate.postProcessEntity(n, context, visitor);
}
/**
* Visit any entity. Override only this to change behavior for all entities.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
@Override
public boolean visitEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return delegate.visitEntity(n, context, visitor);
}
/**
* Leave any entity. Override only this to change behavior for all entities.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
@Override
public void leaveEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
delegate.leaveEntity(n, context, visitor);
}
/**
* Visit a File entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param fileContext a visitor-specific context for this file
* @return true if no further processing is needed
*/
@Override
protected boolean visitFileEntity(
CAstEntity n, C context, C fileContext, CAstVisitor<C> visitor) {
return delegate.visitFileEntity(n, context, fileContext, visitor);
}
/**
* Leave a File entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param fileContext a visitor-specific context for this file
*/
@Override
protected void leaveFileEntity(CAstEntity n, C context, C fileContext, CAstVisitor<C> visitor) {
delegate.leaveFileEntity(n, context, fileContext, visitor);
}
/**
* Visit a Field entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitFieldEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
return delegate.visitFieldEntity(n, context, visitor);
}
/**
* Leave a Field entity.
*
* @param n the entity to process
* @param context a visitor-specific context
*/
@Override
protected void leaveFieldEntity(CAstEntity n, C context, CAstVisitor<C> visitor) {
delegate.leaveFieldEntity(n, context, visitor);
}
/**
* Visit a Type entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param typeContext a visitor-specific context for this type
* @return true if no further processing is needed
*/
@Override
protected boolean visitTypeEntity(
CAstEntity n, C context, C typeContext, CAstVisitor<C> visitor) {
return delegate.visitTypeEntity(n, context, typeContext, visitor);
}
/**
* Leave a Type entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param typeContext a visitor-specific context for this type
*/
@Override
protected void leaveTypeEntity(CAstEntity n, C context, C typeContext, CAstVisitor<C> visitor) {
delegate.leaveTypeEntity(n, context, typeContext, visitor);
}
/**
* Visit a Function entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this function
* @return true if no further processing is needed
*/
@Override
protected boolean visitFunctionEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
return delegate.visitFunctionEntity(n, context, codeContext, visitor);
}
/**
* Leave a Function entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this function
*/
@Override
protected void leaveFunctionEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
delegate.leaveFunctionEntity(n, context, codeContext, visitor);
}
/**
* Visit a Script entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this script
* @return true if no further processing is needed
*/
@Override
protected boolean visitScriptEntity(
CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
return delegate.visitScriptEntity(n, context, codeContext, visitor);
}
/**
* Leave a Script entity.
*
* @param n the entity to process
* @param context a visitor-specific context
* @param codeContext a visitor-specific context for this script
*/
@Override
protected void leaveScriptEntity(CAstEntity n, C context, C codeContext, CAstVisitor<C> visitor) {
delegate.leaveScriptEntity(n, context, codeContext, visitor);
}
/**
* Node processing hook; sub-classes are expected to override if they introduce new node types.
* Should invoke super.doVisit() for unprocessed nodes.
*
* @return true if node was handled
*/
@Override
protected boolean doVisit(CAstNode n, C context, CAstVisitor<C> visitor) {
return delegate.doVisit(n, context, visitor);
}
/**
* Enter the node visitor.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean enterNode(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.enterNode(n, c, visitor);
}
/**
* Post-process a node after visiting it.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void postProcessNode(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.postProcessNode(n, c, visitor);
}
/**
* Visit any node. Override only this to change behavior for all nodes.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
public boolean visitNode(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitNode(n, c, visitor);
}
/**
* Leave any node. Override only this to change behavior for all nodes.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
public void leaveNode(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveNode(n, c, visitor);
}
/**
* Visit a FunctionExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitFunctionExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitFunctionExpr(n, c, visitor);
}
/**
* Leave a FunctionExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveFunctionExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveFunctionExpr(n, c, visitor);
}
/**
* Visit a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitFunctionStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitFunctionStmt(n, c, visitor);
}
/**
* Leave a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveFunctionStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveFunctionStmt(n, c, visitor);
}
/**
* Visit a ClassStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitClassStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitClassStmt(n, c, visitor);
}
/**
* Leave a FunctionStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveClassStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveClassStmt(n, c, visitor);
}
/**
* Visit a LocalScope node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitLocalScope(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitLocalScope(n, c, visitor);
}
/**
* Leave a LocalScope node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveLocalScope(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveLocalScope(n, c, visitor);
}
/**
* Visit a BlockExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitBlockExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitBlockExpr(n, c, visitor);
}
/**
* Leave a BlockExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveBlockExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveBlockExpr(n, c, visitor);
}
/**
* Visit a BlockStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitBlockStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitBlockStmt(n, c, visitor);
}
/**
* Leave a BlockStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveBlockStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveBlockStmt(n, c, visitor);
}
/**
* Visit a Loop node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitLoop(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitLoop(n, c, visitor);
}
/**
* Visit a Loop node after processing the loop header.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveLoopHeader(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveLoopHeader(n, c, visitor);
}
/**
* Leave a Loop node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveLoop(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveLoop(n, c, visitor);
}
/**
* Visit a GetCaughtException node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitGetCaughtException(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitGetCaughtException(n, c, visitor);
}
/**
* Leave a GetCaughtException node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveGetCaughtException(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveGetCaughtException(n, c, visitor);
}
/**
* Visit a This node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitThis(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitThis(n, c, visitor);
}
/**
* Leave a This node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveThis(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveThis(n, c, visitor);
}
/**
* Visit a Super node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitSuper(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitSuper(n, c, visitor);
}
/**
* Leave a Super node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveSuper(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveSuper(n, c, visitor);
}
/**
* Visit a Call node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitCall(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitCall(n, c, visitor);
}
/**
* Leave a Call node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveCall(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveCall(n, c, visitor);
}
/**
* Visit a Var node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitVar(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitVar(n, c, visitor);
}
/**
* Leave a Var node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveVar(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveVar(n, c, visitor);
}
/**
* Visit a Constant node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitConstant(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitConstant(n, c, visitor);
}
/**
* Leave a Constant node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveConstant(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveConstant(n, c, visitor);
}
/**
* Visit a BinaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitBinaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitBinaryExpr(n, c, visitor);
}
/**
* Leave a BinaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveBinaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveBinaryExpr(n, c, visitor);
}
/**
* Visit a UnaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitUnaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitUnaryExpr(n, c, visitor);
}
/**
* Leave a UnaryExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveUnaryExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveUnaryExpr(n, c, visitor);
}
/**
* Visit an ArrayLength node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitArrayLength(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitArrayLength(n, c, visitor);
}
/**
* Leave an ArrayLength node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayLength(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayLength(n, c, visitor);
}
/**
* Visit an ArrayRef node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitArrayRef(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitArrayRef(n, c, visitor);
}
/**
* Leave an ArrayRef node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayRef(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayRef(n, c, visitor);
}
/**
* Visit a DeclStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitDeclStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitDeclStmt(n, c, visitor);
}
/**
* Leave a DeclStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveDeclStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveDeclStmt(n, c, visitor);
}
/**
* Visit a Return node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitReturn(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitReturn(n, c, visitor);
}
/**
* Leave a Return node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveReturn(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveReturn(n, c, visitor);
}
/**
* Visit an Ifgoto node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitIfgoto(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitIfgoto(n, c, visitor);
}
/**
* Leave an Ifgoto node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfgoto(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfgoto(n, c, visitor);
}
/**
* Visit a Goto node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitGoto(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitGoto(n, c, visitor);
}
/**
* Leave a Goto node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveGoto(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveGoto(n, c, visitor);
}
/**
* Visit a LabelStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitLabelStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitLabelStmt(n, c, visitor);
}
/**
* Leave a LabelStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveLabelStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveLabelStmt(n, c, visitor);
}
/**
* Visit an IfStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitIfStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitIfStmt(n, c, visitor);
}
/**
* Visit an IfStmt node after processing the condition.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfStmtCondition(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfStmtCondition(n, c, visitor);
}
/**
* Visit an IfStmt node after processing the true clause.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfStmtTrueClause(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfStmtTrueClause(n, c, visitor);
}
/**
* Leave an IfStmt node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfStmt(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfStmt(n, c, visitor);
}
/**
* Visit an IfExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitIfExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitIfExpr(n, c, visitor);
}
/**
* Visit an IfExpr node after processing the condition.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfExprCondition(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfExprCondition(n, c, visitor);
}
/**
* Visit an IfExpr node after processing the true clause.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfExprTrueClause(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfExprTrueClause(n, c, visitor);
}
/**
* Leave an IfExpr node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveIfExpr(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveIfExpr(n, c, visitor);
}
/**
* Visit a New node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitNew(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitNew(n, c, visitor);
}
/**
* Leave a New node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveNew(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveNew(n, c, visitor);
}
/**
* Visit an ObjectLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitObjectLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitObjectLiteral(n, c, visitor);
}
/**
* Visit an ObjectLiteral node after processing the {i}th field initializer.
*
* @param n the node to process
* @param i the field position that was initialized
* @param c a visitor-specific context
*/
@Override
protected void leaveObjectLiteralFieldInit(CAstNode n, int i, C c, CAstVisitor<C> visitor) {
delegate.leaveObjectLiteralFieldInit(n, i, c, visitor);
}
/**
* Leave an ObjectLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveObjectLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveObjectLiteral(n, c, visitor);
}
/**
* Visit an ArrayLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitArrayLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitArrayLiteral(n, c, visitor);
}
/**
* Visit an ArrayLiteral node after processing the array object.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayLiteralObject(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayLiteralObject(n, c, visitor);
}
/**
* Visit an ArrayLiteral node after processing the {i}th element initializer.
*
* @param n the node to process
* @param i the index that was initialized
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayLiteralInitElement(CAstNode n, int i, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayLiteralInitElement(n, i, c, visitor);
}
/**
* Leave a ArrayLiteral node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayLiteral(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayLiteral(n, c, visitor);
}
/**
* Visit an ObjectRef node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitObjectRef(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitObjectRef(n, c, visitor);
}
/**
* Leave an ObjectRef node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveObjectRef(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveObjectRef(n, c, visitor);
}
/**
* Visit an Assign node. Override only this to change behavior for all assignment nodes.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
public boolean visitAssign(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitAssign(n, c, visitor);
}
/**
* Leave an Assign node. Override only this to change behavior for all assignment nodes.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
public void leaveAssign(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveAssign(n, c, visitor);
}
/**
* Visit an ArrayRef Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitArrayRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
return delegate.visitArrayRefAssign(n, v, a, c, visitor);
}
/**
* Visit an ArrayRef Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayRefAssign(n, v, a, c, visitor);
}
/**
* Visit an ArrayRef Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitArrayRefAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
return delegate.visitArrayRefAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit an ArrayRef Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
@Override
protected void leaveArrayRefAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
delegate.leaveArrayRefAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit an ObjectRef Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitObjectRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
return delegate.visitObjectRefAssign(n, v, a, c, visitor);
}
/**
* Visit an ObjectRef Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveObjectRefAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
delegate.leaveObjectRefAssign(n, v, a, c, visitor);
}
/**
* Visit an ObjectRef Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitObjectRefAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
return delegate.visitObjectRefAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit an ObjectRef Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
@Override
protected void leaveObjectRefAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
delegate.leaveObjectRefAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit a BlockExpr Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitBlockExprAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
return delegate.visitBlockExprAssign(n, v, a, c, visitor);
}
/**
* Visit a BlockExpr Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveBlockExprAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
delegate.leaveBlockExprAssign(n, v, a, c, visitor);
}
/**
* Visit a BlockExpr Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitBlockExprAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
return delegate.visitBlockExprAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit a BlockExpr Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
@Override
protected void leaveBlockExprAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
delegate.leaveBlockExprAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit a Var Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitVarAssign(
CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
return delegate.visitVarAssign(n, v, a, c, visitor);
}
/**
* Visit a Var Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveVarAssign(CAstNode n, CAstNode v, CAstNode a, C c, CAstVisitor<C> visitor) {
delegate.leaveVarAssign(n, v, a, c, visitor);
}
/**
* Visit a Var Op/Assignment node after visiting the RHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitVarAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
return delegate.visitVarAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit a Var Op/Assignment node after visiting the LHS.
*
* @param n the LHS node to process
* @param v the RHS node to process
* @param a the assignment node to process
* @param pre whether the value before the operation should be used
* @param c a visitor-specific context
*/
@Override
protected void leaveVarAssignOp(
CAstNode n, CAstNode v, CAstNode a, boolean pre, C c, CAstVisitor<C> visitor) {
delegate.leaveVarAssignOp(n, v, a, pre, c, visitor);
}
/**
* Visit a Switch node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitSwitch(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitSwitch(n, c, visitor);
}
/**
* Visit a Switch node after processing the switch value.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveSwitchValue(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveSwitchValue(n, c, visitor);
}
/**
* Leave a Switch node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveSwitch(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveSwitch(n, c, visitor);
}
/**
* Visit a Throw node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitThrow(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitThrow(n, c, visitor);
}
/**
* Leave a Throw node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveThrow(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveThrow(n, c, visitor);
}
/**
* Visit a Catch node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitCatch(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitCatch(n, c, visitor);
}
/**
* Leave a Catch node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveCatch(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveCatch(n, c, visitor);
}
/**
* Visit an Unwind node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitUnwind(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitUnwind(n, c, visitor);
}
/**
* Leave an Unwind node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveUnwind(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveUnwind(n, c, visitor);
}
/**
* Visit a Try node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitTry(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitTry(n, c, visitor);
}
/**
* Visit a Try node after processing the try block.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveTryBlock(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveTryBlock(n, c, visitor);
}
/**
* Leave a Try node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveTry(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveTry(n, c, visitor);
}
/**
* Visit an Empty node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitEmpty(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitEmpty(n, c, visitor);
}
/**
* Leave an Empty node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveEmpty(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveEmpty(n, c, visitor);
}
/**
* Visit a Primitive node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitPrimitive(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitPrimitive(n, c, visitor);
}
/**
* Leave a Primitive node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leavePrimitive(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leavePrimitive(n, c, visitor);
}
/**
* Visit a Void node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitVoid(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitVoid(n, c, visitor);
}
/**
* Leave a Void node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveVoid(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveVoid(n, c, visitor);
}
/**
* Visit a Cast node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitCast(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitCast(n, c, visitor);
}
/**
* Leave a Cast node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveCast(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveCast(n, c, visitor);
}
/**
* Visit an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitInstanceOf(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitInstanceOf(n, c, visitor);
}
/**
* Leave an InstanceOf node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveInstanceOf(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveInstanceOf(n, c, visitor);
}
/**
* Visit a LocalScope node.
*
* @param n the node to process
* @param c a visitor-specific context
* @return true if no further processing is needed
*/
@Override
protected boolean visitSpecialParentScope(CAstNode n, C c, CAstVisitor<C> visitor) {
return delegate.visitSpecialParentScope(n, c, visitor);
}
/**
* Leave a LocalScope node.
*
* @param n the node to process
* @param c a visitor-specific context
*/
@Override
protected void leaveSpecialParentScope(CAstNode n, C c, CAstVisitor<C> visitor) {
delegate.leaveSpecialParentScope(n, c, visitor);
}
}
| 44,610
| 28.524156
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/types/AstMethodReference.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.types;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
public class AstMethodReference {
public static final String fnAtomStr = "do";
public static final Atom fnAtom = Atom.findOrCreateUnicodeAtom(fnAtomStr);
public static final Descriptor fnDesc =
Descriptor.findOrCreate(new TypeName[0], AstTypeReference.rootTypeName);
public static final Selector fnSelector = new Selector(fnAtom, fnDesc);
public static MethodReference fnReference(TypeReference cls) {
return MethodReference.findOrCreate(cls, fnAtom, fnDesc);
}
}
| 1,136
| 34.53125
| 78
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/types/AstTypeReference.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.types;
import com.ibm.wala.types.TypeName;
public class AstTypeReference {
public static final String rootTypeSourceStr = "Root";
public static final String rootTypeDescStr = 'L' + rootTypeSourceStr;
public static final TypeName rootTypeName = TypeName.string2TypeName(rootTypeDescStr);
public static final String functionTypeSourceStr = "CodeBody";
public static final String functionTypeDescStr = 'L' + functionTypeSourceStr;
public static final TypeName functionTypeName = TypeName.string2TypeName(functionTypeDescStr);
}
| 942
| 36.72
| 96
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/AstConstantCollector.java
|
package com.ibm.wala.cast.util;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.util.CAstPattern.Segments;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public class AstConstantCollector {
public static final CAstPattern simplePreUpdatePattern =
CAstPattern.parse("ASSIGN_PRE_OP(VAR(<name>CONSTANT()),**)");
public static final CAstPattern simplePostUpdatePattern =
CAstPattern.parse("ASSIGN_POST_OP(VAR(<name>CONSTANT()),**)");
public static final CAstPattern simpleGlobalPattern =
CAstPattern.parse("GLOBAL_DECL(@(VAR(<name>CONSTANT()))@)");
public static final CAstPattern simpleValuePattern =
CAstPattern.parse("ASSIGN(VAR(<name>CONSTANT()),<value>*)");
public static Map<String, Object> collectConstants(
CAstEntity function, Map<String, Object> values, Set<String> bad) {
if (function.getAST() != null) {
for (Segments s : CAstPattern.findAll(simplePreUpdatePattern, function)) {
bad.add((String) s.getSingle("name").getValue());
}
for (Segments s : CAstPattern.findAll(simpleGlobalPattern, function)) {
s.getMultiple("name")
.iterator()
.forEachRemaining((name) -> bad.add((String) name.getValue()));
}
for (Segments s : CAstPattern.findAll(simplePostUpdatePattern, function)) {
bad.add((String) s.getSingle("name").getValue());
}
for (Segments s : CAstPattern.findAll(simpleValuePattern, function)) {
String var = (String) s.getSingle("name").getValue();
if (s.getSingle("value").getKind() != CAstNode.CONSTANT) {
bad.add(var);
} else {
Object val = s.getSingle("value").getValue();
if (!bad.contains(var)) {
if (values.containsKey(var)) {
if (val == null ? values.get(var) != null : !val.equals(values.get(var))) {
values.remove(var);
bad.add(var);
}
} else {
values.put(var, val);
}
}
}
}
}
for (Collection<CAstEntity> ces : function.getAllScopedEntities().values()) {
for (CAstEntity ce : ces) {
collectConstants(ce, values, bad);
}
}
bad.forEach(values::remove);
for (Collection<CAstEntity> ces : function.getAllScopedEntities().values()) {
for (CAstEntity ce : ces) {
for (String s : ce.getArgumentNames()) {
values.remove(s);
}
}
}
return values;
}
public static Map<String, Object> collectConstants(CAstEntity function) {
Map<String, Object> values = HashMapFactory.make();
Set<String> bad = HashSetFactory.make();
collectConstants(function, values, bad);
return values;
}
}
| 2,924
| 33.011628
| 89
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/CAstFunctions.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.util;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.graph.traverse.DFSDiscoverTimeIterator;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Predicate;
public class CAstFunctions {
public static CAstNode findIf(CAstNode tree, Predicate<CAstNode> f) {
if (f.test(tree)) {
return tree;
} else {
for (final CAstNode child : tree.getChildren()) {
CAstNode result = findIf(child, f);
if (result != null) {
return result;
}
}
}
return null;
}
public static Iterator<CAstNode> iterateNodes(final CAstNode tree) {
return new DFSDiscoverTimeIterator<>() {
private static final long serialVersionUID = -627203481092871529L;
private final Map<Object, Iterator<? extends CAstNode>> pendingChildren =
HashMapFactory.make();
@Override
protected Iterator<? extends CAstNode> getPendingChildren(CAstNode n) {
return pendingChildren.get(n);
}
@Override
protected void setPendingChildren(CAstNode v, Iterator<? extends CAstNode> iterator) {
pendingChildren.put(v, iterator);
}
@Override
protected Iterator<CAstNode> getConnected(final CAstNode n) {
return new Iterator<>() {
private int i = 0;
@Override
public boolean hasNext() {
return i < n.getChildCount();
}
@Override
public CAstNode next() {
return n.getChild(i++);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
{
init(tree);
}
};
}
public static Iterator<CAstNode> findAll(CAstNode tree, Predicate<? super CAstNode> f) {
return new FilterIterator<>(iterateNodes(tree), f);
}
}
| 2,377
| 26.333333
| 92
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/CAstPattern.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.util;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.visit.CAstVisitor;
import com.ibm.wala.cast.tree.visit.CAstVisitor.Context;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
public class CAstPattern {
private static final boolean DEBUG_PARSER = false;
private static final boolean DEBUG_MATCH = false;
private static final int CHILD_KIND = -1;
private static final int CHILDREN_KIND = -2;
private static final int REPEATED_PATTERN_KIND = -3;
private static final int ALTERNATIVE_PATTERN_KIND = -4;
private static final int OPTIONAL_PATTERN_KIND = -5;
private static final int REFERENCE_PATTERN_KIND = -6;
private static final int IGNORE_KIND = -99;
private final String name;
private final int kind;
private final Object value;
private final CAstPattern[] children;
private final Map<String, CAstPattern> references;
public static class Segments extends TreeMap<String, Object> {
private static final long serialVersionUID = 4119719848336209576L;
public CAstNode getSingle(String name) {
assert containsKey(name) : name;
return (CAstNode) get(name);
}
@SuppressWarnings("unchecked")
public List<CAstNode> getMultiple(String name) {
if (!containsKey(name)) {
return Collections.emptyList();
} else {
Object o = get(name);
if (o instanceof CAstNode) {
return Collections.singletonList((CAstNode) o);
} else {
assert o instanceof List;
return (List<CAstNode>) o;
}
}
}
private void addAll(Segments other) {
for (Map.Entry<String, Object> e : other.entrySet()) {
String name = e.getKey();
if (e.getValue() instanceof CAstNode) {
add(name, (CAstNode) e.getValue());
} else {
@SuppressWarnings("unchecked")
final List<CAstNode> nodes = (List<CAstNode>) e.getValue();
for (CAstNode v : nodes) {
add(name, v);
}
}
}
}
@SuppressWarnings("unchecked")
private void add(String name, CAstNode result) {
if (containsKey(name)) {
Object o = get(name);
if (o instanceof List) {
((List<CAstNode>) o).add(result);
} else {
assert o instanceof CAstNode;
List<Object> x = new ArrayList<>();
x.add(o);
x.add(result);
put(name, x);
}
} else {
put(name, result);
}
}
}
public CAstPattern(String name, int kind, CAstPattern[] children) {
this.name = name;
this.kind = kind;
this.value = null;
this.children = children;
this.references = null;
}
public CAstPattern(String name, Object value) {
this.name = name;
this.kind = IGNORE_KIND;
this.value = value;
this.children = null;
this.references = null;
}
public CAstPattern(String patternName, Map<String, CAstPattern> references) {
this.name = null;
this.kind = REFERENCE_PATTERN_KIND;
this.value = patternName;
this.references = references;
this.children = null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (name != null) {
sb.append('<').append(name).append('>');
}
if (value != null) {
if (kind == REFERENCE_PATTERN_KIND) {
sb.append("ref:").append(value);
} else if (value instanceof Pattern) {
sb.append('/').append(value).append('/');
} else {
sb.append("literal:").append(value);
}
} else if (kind == CHILD_KIND) {
sb.append('*');
} else if (kind == CHILDREN_KIND) {
sb.append("**");
} else if (kind == REPEATED_PATTERN_KIND) {
sb.append('@');
} else if (kind == ALTERNATIVE_PATTERN_KIND) {
sb.append('|');
} else if (kind == OPTIONAL_PATTERN_KIND) {
sb.append('?');
} else {
sb.append(CAstPrinter.kindAsString(kind));
}
if (children != null) {
sb.append('(');
for (int i = 0; i < children.length; i++) {
sb.append(children[i].toString());
if (i == children.length - 1) {
sb.append(')');
} else {
sb.append(',');
}
}
}
return sb.toString();
}
private static boolean matchChildren(CAstNode tree, int i, CAstPattern[] cs, int j, Segments s) {
if (i >= tree.getChildCount() && j >= cs.length) {
return true;
} else if (i < tree.getChildCount() && j >= cs.length) {
return false;
} else if (i >= tree.getChildCount() && j < cs.length) {
switch (cs[j].kind) {
case CHILDREN_KIND:
case OPTIONAL_PATTERN_KIND:
case REPEATED_PATTERN_KIND:
return matchChildren(tree, i, cs, j + 1, s);
default:
return false;
}
} else {
switch (cs[j].kind) {
case CHILD_KIND:
if (DEBUG_MATCH) {
System.err.println(("* matches " + CAstPrinter.print(tree.getChild(i))));
}
if (s != null && cs[j].name != null) {
s.add(cs[j].name, tree.getChild(i));
}
return matchChildren(tree, i + 1, cs, j + 1, s);
case CHILDREN_KIND:
if (tryMatchChildren(tree, i, cs, j + 1, s)) {
if (DEBUG_MATCH) {
System.err.println("** matches nothing");
}
return true;
} else {
if (DEBUG_MATCH) {
System.err.println(("** matches " + CAstPrinter.print(tree.getChild(i))));
}
if (s != null && cs[j].name != null) {
s.add(cs[j].name, tree.getChild(i));
}
return matchChildren(tree, i + 1, cs, j, s);
}
case REPEATED_PATTERN_KIND:
CAstPattern repeatedPattern = cs[j].children[0];
if (repeatedPattern.tryMatch(tree.getChild(i), s)) {
if (s != null && cs[j].name != null) {
s.add(cs[j].name, tree.getChild(i));
}
if (DEBUG_MATCH) {
System.err.println((cs[j] + " matches " + CAstPrinter.print(tree.getChild(i))));
}
return matchChildren(tree, i + 1, cs, j, s);
} else {
if (DEBUG_MATCH) {
System.err.println((cs[j] + " matches nothing"));
}
return matchChildren(tree, i, cs, j + 1, s);
}
case OPTIONAL_PATTERN_KIND:
if (tryMatchChildren(tree, i, cs, j + 1, s)) {
if (DEBUG_MATCH) {
System.err.println((cs[j] + " matches nothing"));
}
return true;
} else {
CAstPattern optionalPattern = cs[j].children[0];
if (optionalPattern.tryMatch(tree.getChild(i), s)) {
if (DEBUG_MATCH) {
System.err.println((cs[j] + " matches " + CAstPrinter.print(tree.getChild(i))));
}
return matchChildren(tree, i + 1, cs, j + 1, s);
} else {
return false;
}
}
default:
return cs[j].match(tree.getChild(i), s) && matchChildren(tree, i + 1, cs, j + 1, s);
}
}
}
public boolean match(CAstNode tree, Segments s) {
if (DEBUG_MATCH) {
System.err.println(("matching " + this + " against " + CAstPrinter.print(tree)));
}
switch (kind) {
case REFERENCE_PATTERN_KIND:
return references.get(value).match(tree, s);
case ALTERNATIVE_PATTERN_KIND:
for (CAstPattern element : children) {
if (element.tryMatch(tree, s)) {
if (s != null && name != null) s.add(name, tree);
return true;
}
}
if (DEBUG_MATCH) {
System.err.println("match failed (a)");
}
return false;
default:
if ((value == null)
? tree.getKind() != kind
: (tree.getKind() != CAstNode.CONSTANT
|| (value instanceof Pattern
? !((Pattern) value).matcher(tree.getValue().toString()).matches()
: !value.equals(tree.getValue().toString())))) {
if (DEBUG_MATCH) {
System.err.println("match failed (b)");
}
return false;
}
if (s != null && name != null) s.add(name, tree);
if (children == null || children.length == 0) {
if (DEBUG_MATCH) {
if (tree.getChildCount() != 0) {
System.err.println("match failed (c)");
}
}
return tree.getChildCount() == 0;
} else {
return matchChildren(tree, 0, children, 0, s);
}
}
}
private static boolean tryMatchChildren(
CAstNode tree, int i, CAstPattern[] cs, int j, Segments s) {
if (s == null) {
return matchChildren(tree, i, cs, j, s);
} else {
Segments ss = new Segments();
boolean result = matchChildren(tree, i, cs, j, ss);
if (result) s.addAll(ss);
return result;
}
}
private boolean tryMatch(CAstNode tree, Segments s) {
if (s == null) {
return match(tree, s);
} else {
Segments ss = new Segments();
boolean result = match(tree, ss);
if (result) s.addAll(ss);
return result;
}
}
public static Segments match(CAstPattern p, CAstNode n) {
Segments s = new Segments();
if (p.match(n, s)) {
return s;
} else {
return null;
}
}
public static CAstPattern parse(String patternString) {
try {
return new Parser(patternString).parse();
} catch (NoSuchFieldException e) {
Assertions.UNREACHABLE("no such kind in pattern: " + e.getMessage());
return null;
} catch (IllegalAccessException e) {
Assertions.UNREACHABLE("internal error in CAstPattern" + e);
return null;
}
}
public static Collection<Segments> findAll(final CAstPattern p, final CAstEntity e) {
return p.new Matcher()
.findAll(
new Context() {
@Override
public CAstEntity top() {
return e;
}
@Override
public CAstSourcePositionMap getSourceMap() {
return e.getSourceMap();
}
},
e.getAST());
}
public class Matcher extends CAstVisitor<Context> {
private final Collection<Segments> result = HashSetFactory.make();
@Override
public void leaveNode(CAstNode n, Context c, CAstVisitor<Context> visitor) {
Segments s = match(CAstPattern.this, n);
if (s != null) {
result.add(s);
}
}
public Collection<Segments> findAll(final Context c, final CAstNode top) {
visit(top, c, this);
return result;
}
@Override
protected boolean doVisit(CAstNode n, Context context, CAstVisitor<Context> visitor) {
Segments s = match(CAstPattern.this, n);
if (s != null) {
result.add(s);
}
return true;
}
@Override
protected boolean doVisitAssignNodes(
CAstNode n, Context context, CAstNode v, CAstNode a, CAstVisitor<Context> visitor) {
return true;
}
}
private static class Parser {
private final Map<String, CAstPattern> namedPatterns = HashMapFactory.make();
private final String patternString;
private int start;
private int end;
private Parser(String patternString) {
this.patternString = patternString;
}
// private Parser(String patternString, int start) {
// this(patternString);
// this.start = start;
// }
private String parseName(boolean internal) {
if (patternString.charAt(start) == (internal ? '{' : '<')) {
int nameStart = start + 1;
int nameEnd = patternString.indexOf(internal ? '}' : '>', nameStart);
start = nameEnd + 1;
return patternString.substring(nameStart, nameEnd);
} else {
return null;
}
}
public CAstPattern parse() throws NoSuchFieldException, IllegalAccessException {
if (DEBUG_PARSER) {
System.err.println(("parsing " + patternString.substring(start)));
}
String internalName = parseName(true);
String name = parseName(false);
CAstPattern result;
if (patternString.charAt(start) == '`') {
int strEnd = patternString.indexOf('`', start + 1);
end = strEnd + 1;
String patternName = patternString.substring(start + 1, strEnd);
assert internalName == null;
result = new CAstPattern(patternName, namedPatterns);
} else if (patternString.charAt(start) == '"') {
int strEnd = patternString.indexOf('"', start + 1);
end = strEnd + 1;
result = new CAstPattern(name, patternString.substring(start + 1, strEnd));
} else if (patternString.charAt(start) == '/') {
int strEnd = patternString.indexOf('/', start + 1);
end = strEnd + 1;
result = new CAstPattern(name, Pattern.compile(patternString.substring(start + 1, strEnd)));
} else if (patternString.startsWith("**", start)) {
end = start + 2;
result = new CAstPattern(name, CHILDREN_KIND, null);
} else if (patternString.startsWith("*", start)) {
end = start + 1;
result = new CAstPattern(name, CHILD_KIND, null);
} else if (patternString.startsWith("|(", start)) {
List<CAstPattern> alternatives = new ArrayList<>();
start += 2;
do {
alternatives.add(parse());
start = end + 2;
} while (patternString.startsWith("||", end));
assert patternString.startsWith(")|", end) : patternString;
end += 2;
result =
new CAstPattern(
name, ALTERNATIVE_PATTERN_KIND, alternatives.toArray(new CAstPattern[0]));
} else if (patternString.startsWith("@(", start)) {
start += 2;
CAstPattern children[] = new CAstPattern[] {parse()};
assert patternString.startsWith(")@", end);
end += 2;
if (DEBUG_PARSER) {
System.err.println(("repeated pattern: " + children[0]));
}
result = new CAstPattern(name, REPEATED_PATTERN_KIND, children);
} else if (patternString.startsWith("?(", start)) {
start += 2;
CAstPattern children[] = new CAstPattern[] {parse()};
assert patternString.startsWith(")?", end);
end += 2;
if (DEBUG_PARSER) {
System.err.println(("optional pattern: " + children[0]));
}
result = new CAstPattern(name, OPTIONAL_PATTERN_KIND, children);
} else {
int kindEnd = patternString.indexOf('(', start);
String kindStr = patternString.substring(start, kindEnd);
Field kindField = CAstNode.class.getField(kindStr);
int kind = kindField.getInt(null);
if (patternString.charAt(kindEnd + 1) == ')') {
end = kindEnd + 2;
result = new CAstPattern(name, kind, null);
} else {
List<CAstPattern> children = new ArrayList<>();
start = patternString.indexOf('(', start) + 1;
do {
children.add(parse());
start = end + 1;
if (DEBUG_PARSER) {
System.err.println(("parsing children: " + patternString.substring(end)));
}
} while (patternString.charAt(end) == ',');
assert patternString.charAt(end) == ')';
end++;
result = new CAstPattern(name, kind, children.toArray(new CAstPattern[0]));
}
}
if (internalName != null) {
namedPatterns.put(internalName, result);
}
return result;
}
}
}
| 16,530
| 28.052724
| 100
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/CAstPrinter.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.util;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
public class CAstPrinter {
private static final class StringWriter extends Writer {
private final StringBuilder sb;
private StringWriter(StringBuilder sb) {
this.sb = sb;
}
@Override
public void write(char[] cbuf, int off, int len) {
sb.append(new String(cbuf, off, len));
}
@Override
public void flush() {
// do nothing
}
@Override
public void close() {
// do nothing
}
}
private static CAstPrinter instance = new CAstPrinter();
public static void setPrinter(CAstPrinter printer) {
instance = printer;
}
public static String kindAsString(int kind) {
return instance.getKindAsString(kind);
}
public String getKindAsString(int kind) {
switch (kind) {
// statements
case CAstNode.SWITCH:
return "SWITCH";
case CAstNode.LOOP:
return "LOOP";
case CAstNode.BLOCK_STMT:
return "BLOCK";
case CAstNode.TRY:
return "TRY";
case CAstNode.EXPR_STMT:
return "EXPR_STMT";
case CAstNode.DECL_STMT:
return "DECL_STMT";
case CAstNode.RETURN:
return "RETURN";
case CAstNode.GOTO:
return "GOTO";
case CAstNode.BREAK:
return "BREAK";
case CAstNode.CONTINUE:
return "CONTINUE";
case CAstNode.IF_STMT:
return "IF_STMT";
case CAstNode.THROW:
return "THROW";
case CAstNode.FUNCTION_STMT:
return "FUNCTION_STMT";
case CAstNode.ASSIGN:
return "ASSIGN";
case CAstNode.ASSIGN_PRE_OP:
return "ASSIGN_PRE_OP";
case CAstNode.ASSIGN_POST_OP:
return "ASSIGN_POST_OP";
case CAstNode.LABEL_STMT:
return "LABEL_STMT";
case CAstNode.IFGOTO:
return "IFGOTO";
case CAstNode.EMPTY:
return "EMPTY";
case CAstNode.YIELD_STMT:
return "YIELD";
case CAstNode.CATCH:
return "CATCH";
case CAstNode.UNWIND:
return "UNWIND";
case CAstNode.MONITOR_ENTER:
return "MONITOR_ENTER";
case CAstNode.MONITOR_EXIT:
return "MONITOR_EXIT";
case CAstNode.ECHO:
return "ECHO";
case CAstNode.FORIN_LOOP:
return "FOR..IN";
// expression kinds
case CAstNode.FUNCTION_EXPR:
return "FUNCTION_EXPR";
case CAstNode.EXPR_LIST:
return "EXPR_LIST";
case CAstNode.CALL:
return "CALL";
case CAstNode.GET_CAUGHT_EXCEPTION:
return "EXCEPTION";
case CAstNode.BLOCK_EXPR:
return "BLOCK_EXPR";
case CAstNode.BINARY_EXPR:
return "BINARY_EXPR";
case CAstNode.UNARY_EXPR:
return "UNARY_EXPR";
case CAstNode.IF_EXPR:
return "IF_EXPR";
case CAstNode.ANDOR_EXPR:
return "ANDOR_EXPR";
case CAstNode.NEW:
return "NEW";
case CAstNode.NEW_ENCLOSING:
return "NEW_ENCLOSING";
case CAstNode.OBJECT_LITERAL:
return "OBJECT_LITERAL";
case CAstNode.VAR:
return "VAR";
case CAstNode.OBJECT_REF:
return "OBJECT_REF";
case CAstNode.CHOICE_EXPR:
return "CHOICE_EXPR";
case CAstNode.CHOICE_CASE:
return "CHOICE_CASE";
case CAstNode.SUPER:
return "SUPER";
case CAstNode.THIS:
return "THIS";
case CAstNode.ARRAY_LITERAL:
return "ARRAY_LITERAL";
case CAstNode.CAST:
return "CAST";
case CAstNode.INSTANCEOF:
return "INSTANCEOF";
case CAstNode.ARRAY_REF:
return "ARRAY_REF";
case CAstNode.ARRAY_LENGTH:
return "ARRAY_LENGTH";
case CAstNode.TYPE_OF:
return "TYPE_OF";
case CAstNode.EACH_ELEMENT_HAS_NEXT:
return "EACH_ELEMENT_HAS_NEXT";
case CAstNode.EACH_ELEMENT_GET:
return "EACH_ELEMENT_GET";
case CAstNode.LIST_EXPR:
return "LIST_EXPR";
case CAstNode.EMPTY_LIST_EXPR:
return "EMPTY_LIST_EXPR";
case CAstNode.IS_DEFINED_EXPR:
return "IS_DEFINED_EXPR";
case CAstNode.NARY_EXPR:
return "NARY_EXPR";
// explicit lexical scopes
case CAstNode.LOCAL_SCOPE:
return "SCOPE";
case CAstNode.SPECIAL_PARENT_SCOPE:
return "SPECIAL PARENT SCOPE";
// literal expression kinds
case CAstNode.CONSTANT:
return "CONSTANT";
case CAstNode.OPERATOR:
return "OPERATOR";
// special stuff
case CAstNode.PRIMITIVE:
return "PRIMITIVE";
case CAstNode.VOID:
return "VOID";
case CAstNode.ERROR:
return "ERROR";
case CAstNode.ASSERT:
return "ASSERT";
default:
return "UNKNOWN(" + kind + ')';
}
}
public static String print(CAstNode top) {
return instance.doPrint(top);
}
public String doPrint(CAstNode top) {
return print(top, null);
}
public static String print(CAstNode top, CAstSourcePositionMap pos) {
return instance.doPrint(top, pos);
}
public String doPrint(CAstNode top, CAstSourcePositionMap pos) {
final StringBuilder sb = new StringBuilder();
try (final StringWriter writer = new StringWriter(sb)) {
printTo(top, pos, writer);
}
return sb.toString();
}
public String doPrint(CAstEntity ce) {
final StringBuilder sb = new StringBuilder();
try (final StringWriter writer = new StringWriter(sb)) {
printTo(ce, writer);
}
return sb.toString();
}
public static String print(CAstEntity ce) {
return instance.doPrint(ce);
}
public static void printTo(CAstNode top, Writer w) {
instance.doPrintTo(top, w);
}
public void doPrintTo(CAstNode top, Writer w) {
printTo(top, null, w, 0, false);
}
public static void printTo(CAstNode top, CAstSourcePositionMap pos, Writer w) {
instance.doPrintTo(top, pos, w);
}
public void doPrintTo(CAstNode top, CAstSourcePositionMap pos, Writer w) {
printTo(top, pos, w, 0, false);
}
public static void xmlTo(CAstNode top, Writer w) {
instance.doXmlTo(top, w);
}
public void doXmlTo(CAstNode top, Writer w) {
printTo(top, null, w, 0, true);
}
public static void xmlTo(CAstNode top, CAstSourcePositionMap pos, Writer w) {
doXmlTo(top, pos, w);
}
private static void doXmlTo(CAstNode top, CAstSourcePositionMap pos, Writer w) {
printTo(top, pos, w, 0, true);
}
private static String escapeForXML(String x, char from, String to) {
return (x.indexOf(from) != -1) ? x.replaceAll(Character.toString(from), to) : x;
}
public static String escapeForXML(String x) {
return escapeForXML(
escapeForXML(escapeForXML(escapeForXML(x, '&', "&"), '"', """), '<', "<"),
'>',
">");
}
public static void printTo(
CAstNode top, CAstSourcePositionMap pos, Writer w, int depth, boolean uglyBrackets) {
instance.doPrintTo(top, pos, w, depth, uglyBrackets);
}
public void doPrintTo(
CAstNode top, CAstSourcePositionMap pos, Writer w, int depth, boolean uglyBrackets) {
try {
CAstSourcePositionMap.Position p = (pos != null) ? pos.getPosition(top) : null;
for (int i = 0; i < depth; i++) w.write(" ");
if (top == null) {
w.write("(null)\n");
} else if (top.getValue() != null) {
if (uglyBrackets) {
w.write("<constant value=\"");
w.write(escapeForXML(top.getValue().toString()));
w.write("\" type=\"");
w.write(top.getValue().getClass().toString());
w.write("\"");
} else {
w.write("\"");
w.write(top.getValue().toString());
w.write("\"");
}
if (p != null) {
if (uglyBrackets) w.write(" lineNumber=\"" + p + '"');
else w.write(" at " + p);
}
if (uglyBrackets) w.write("/>");
w.write("\n");
} else {
if (uglyBrackets) w.write("<");
w.write(kindAsString(top.getKind()));
if (p != null)
if (uglyBrackets) w.write(" position=\"" + p + '"');
else w.write(" at " + p);
if (uglyBrackets) w.write(">");
w.write("\n");
for (CAstNode child : top.getChildren()) {
doPrintTo(child, pos, w, depth + 1, uglyBrackets);
}
if (uglyBrackets) {
for (int i = 0; i < depth; i++) w.write(" ");
w.write("</" + kindAsString(top.getKind()) + ">\n");
}
}
} catch (java.io.IOException e) {
}
}
public static String entityKindAsString(int kind) {
return instance.getEntityKindAsString(kind);
}
public String getEntityKindAsString(int kind) {
switch (kind) {
case CAstEntity.FUNCTION_ENTITY:
return "function";
case CAstEntity.FIELD_ENTITY:
return "field";
case CAstEntity.FILE_ENTITY:
return "unit";
case CAstEntity.TYPE_ENTITY:
return "type";
case CAstEntity.SCRIPT_ENTITY:
return "script";
case CAstEntity.RULE_ENTITY:
return "rule";
default:
return "<unknown entity kind>";
}
}
public static void printTo(CAstEntity e, Writer w) {
// anca: check if the writer is null
if (w != null) instance.doPrintTo(e, w);
}
protected void doPrintTo(CAstEntity e, Writer w) {
try {
w.write(getEntityKindAsString(e.getKind()));
w.write(": ");
w.write(e.getName());
w.write('\n');
if (e.getArgumentNames().length > 0) {
w.write("(");
String[] names = e.getArgumentNames();
for (String name : names) {
w.write(" " + name);
}
w.write(" )\n");
}
if (e.getAST() != null) {
doPrintTo(e.getAST(), e.getSourceMap(), w);
w.write('\n');
}
for (Collection<CAstEntity> collection : e.getAllScopedEntities().values()) {
for (CAstEntity entity : collection) {
doPrintTo(entity, w);
}
}
w.flush();
} catch (IOException e1) {
System.err.println("unexpected I/O exception " + e1);
}
}
}
| 10,697
| 27.005236
| 94
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/CAstToDOM.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.util;
import com.ibm.wala.cast.tree.CAstNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class CAstToDOM extends CAstPrinter {
private static final String VALUE_TAG = "value";
private static final String TYPE_TAG = "type";
public static Document toDOM(CAstNode astRoot) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
Document document = domImplementation.createDocument("CAst", "CAst", null);
Element rootNode = document.getDocumentElement();
nodeToDOM(document, rootNode, astRoot);
return document;
} catch (ParserConfigurationException e) {
e.printStackTrace();
throw new RuntimeException("DOM builder error.");
}
}
private static void nodeToDOM(Document doc, Element root, CAstNode astNode) {
Element nodeElt = doc.createElement(kindAsString(astNode.getKind()));
if (astNode.getValue() == null) {
for (CAstNode child : astNode.getChildren()) {
nodeToDOM(doc, nodeElt, child);
}
} else {
Element typeTag = doc.createElement(TYPE_TAG);
Text type = doc.createTextNode(astNode.getValue().getClass().toString());
typeTag.appendChild(type);
nodeElt.appendChild(typeTag);
Element valueTag = doc.createElement(VALUE_TAG);
Text value = doc.createTextNode(astNode.getValue().toString());
valueTag.appendChild(value);
nodeElt.appendChild(valueTag);
}
root.appendChild(nodeElt);
}
}
| 2,286
| 33.134328
| 91
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/SourceBuffer.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.util;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.tree.impl.AbstractSourcePosition;
import com.ibm.wala.classLoader.IMethod.SourcePosition;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class SourceBuffer {
private static final class DetailedPosition implements Position {
private final int endOffset;
private final int endLine;
private final int endColumn;
private final int startColumn;
private final Position p;
private final int startLine;
private final int startOffset;
private DetailedPosition(
int endOffset,
int endLine,
int endColumn,
int startColumn,
Position p,
int startLine,
int startOffset) {
this.endOffset = endOffset;
this.endLine = endLine;
this.endColumn = endColumn;
this.startColumn = startColumn;
this.p = p;
this.startLine = startLine;
this.startOffset = startOffset;
}
@Override
public int getFirstLine() {
return startLine;
}
@Override
public int getLastLine() {
return endLine;
}
@Override
public int getFirstCol() {
return startColumn;
}
@Override
public int getLastCol() {
return endColumn;
}
@Override
public int getFirstOffset() {
return startOffset;
}
@Override
public int getLastOffset() {
return endOffset;
}
@Override
public int compareTo(SourcePosition o) {
return p.compareTo(o);
}
@Override
public URL getURL() {
return p.getURL();
}
@Override
public Reader getReader() throws IOException {
return p.getReader();
}
}
private String[] lines;
private final Position p;
public final Position detail;
public SourceBuffer(Position p) throws IOException {
this.p = p;
try (Reader pr = p.getReader()) {
try (BufferedReader reader = new BufferedReader(pr)) {
String currentLine = null;
List<String> lines = new ArrayList<>();
int offset = 0, line = 0;
do {
currentLine = reader.readLine();
if (currentLine == null) {
this.lines = new String[0];
detail = null;
return;
}
offset += (currentLine.length() + 1);
line++;
} while (p.getLastOffset() >= 0 ? p.getFirstOffset() > offset : p.getFirstLine() > line);
// partial first line
int endOffset = -1;
int endLine = -1;
int endColumn = -1;
int startOffset = -1;
int startLine = line;
int startColumn = -1;
if (p.getLastOffset() >= 0) {
if (p.getFirstOffset() == offset) {
startOffset = p.getFirstOffset();
startColumn = 0;
lines.add("\n");
} else {
startOffset = p.getFirstOffset() - (offset - currentLine.length() - 1);
startColumn = startOffset;
if (offset > p.getLastOffset()) {
endOffset = p.getLastOffset() - (offset - currentLine.length() - 1);
endLine = line;
endColumn = endOffset;
lines.add(currentLine.substring(startOffset, endOffset));
} else {
lines.add(currentLine.substring(startOffset));
}
}
} else {
lines.add(currentLine.substring(Math.max(p.getFirstCol(), 0)));
startColumn = p.getFirstCol();
}
while (p.getLastOffset() >= 0 ? p.getLastOffset() >= offset : p.getLastLine() >= line) {
currentLine = reader.readLine();
if (currentLine == null) {
offset = p.getLastOffset();
break;
} else {
offset += currentLine.length() + 1;
}
line++;
if (p.getLastOffset() >= 0) {
if (offset > p.getLastOffset()) {
endColumn = currentLine.length() - (offset - p.getLastOffset()) + 1;
lines.add(currentLine.substring(0, endColumn));
endLine = line;
endOffset = p.getLastOffset();
break;
} else {
lines.add(currentLine);
}
} else {
if (p.getLastLine() == line) {
lines.add(currentLine.substring(0, p.getLastCol()));
endColumn = p.getLastCol();
endLine = line;
endOffset = offset - (currentLine.length() - p.getLastCol());
break;
} else {
lines.add(currentLine);
}
}
}
this.lines = lines.toArray(new String[0]);
this.detail =
new DetailedPosition(
endOffset, endLine, endColumn, startColumn, p, startLine, startOffset);
reader.close();
pr.close();
}
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
if (i == lines.length - 1) {
result.append(lines[i]);
} else {
result.append(lines[i]).append('\n');
}
}
return result.toString();
}
public void substitute(Position range, String newText) {
int startLine = range.getFirstLine() - p.getFirstLine();
int endLine = range.getLastLine() - p.getFirstLine();
if (startLine != endLine) {
String newLines[] = new String[lines.length - (endLine - startLine)];
int i = 0;
while (i < startLine) {
newLines[i] = lines[i];
i++;
}
newLines[i++] =
lines[startLine].substring(0, range.getFirstCol())
+ lines[endLine].substring(range.getLastCol());
while (i < newLines.length) {
newLines[i] = lines[i + (endLine - startLine)];
i++;
}
lines = newLines;
endLine = startLine;
final Position hack = range;
range =
new AbstractSourcePosition() {
@Override
public int getFirstLine() {
return hack.getFirstLine();
}
@Override
public int getLastLine() {
return hack.getFirstLine();
}
@Override
public int getFirstCol() {
return hack.getFirstCol();
}
@Override
public int getLastCol() {
return hack.getFirstCol();
}
@Override
public int getFirstOffset() {
return hack.getFirstOffset();
}
@Override
public int getLastOffset() {
return hack.getFirstOffset();
}
@Override
public URL getURL() {
return hack.getURL();
}
@Override
public Reader getReader() throws IOException {
return hack.getReader();
}
};
}
String[] newTextLines = newText.split("\n");
if (newTextLines.length == 1) {
lines[startLine] =
lines[startLine].substring(0, range.getFirstCol())
+ newTextLines[0]
+ lines[startLine].substring(range.getLastCol() + 1);
} else {
String[] newLines = new String[lines.length + newTextLines.length - 1];
int i = 0;
while (i < startLine) {
newLines[i] = lines[i];
i++;
}
newLines[i++] = lines[startLine].substring(0, range.getFirstCol()) + newTextLines[0];
for (int j = 1; j < newTextLines.length - 1; j++) {
lines[i++] = newTextLines[j];
}
newLines[i++] =
newTextLines[newTextLines.length - 1] + lines[endLine].substring(range.getLastCol() + 1);
while (i < newLines.length) {
newLines[i] = lines[i - newTextLines.length + 1];
i++;
}
lines = newLines;
}
}
}
| 8,412
| 26.314935
| 99
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/TargetLanguageSelector.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.util;
import com.ibm.wala.core.util.strings.Atom;
public interface TargetLanguageSelector<T, C> {
T get(Atom language, C construct);
}
| 534
| 27.157895
| 72
|
java
|
WALA
|
WALA-master/cast/src/main/java/com/ibm/wala/cast/util/Util.java
|
package com.ibm.wala.cast.util;
import com.ibm.wala.cast.loader.CAstAbstractLoader;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.util.WalaException;
import java.util.Iterator;
public class Util {
public static void checkForFrontEndErrors(IClassHierarchy cha) throws WalaException {
StringBuilder message = null;
for (IClassLoader loader : cha.getLoaders()) {
if (loader instanceof CAstAbstractLoader) {
Iterator<ModuleEntry> errors = ((CAstAbstractLoader) loader).getModulesWithParseErrors();
if (errors.hasNext()) {
if (message == null) {
message = new StringBuilder("front end errors:\n");
}
while (errors.hasNext()) {
ModuleEntry errorModule = errors.next();
for (Warning w : ((CAstAbstractLoader) loader).getMessages(errorModule)) {
message.append("error in ").append(errorModule.getName()).append(":\n");
message.append(w.toString()).append('\n');
}
}
}
// clear out the errors to free some memory
((CAstAbstractLoader) loader).clearMessages();
}
}
if (message != null) {
message.append("end of front end errors\n");
throw new WalaException(String.valueOf(message));
}
}
}
| 1,444
| 35.125
| 97
|
java
|
WALA
|
WALA-master/cast/src/test/java/com/ibm/wala/cast/test/TestCAstPattern.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.test;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.impl.CAstImpl;
import com.ibm.wala.cast.util.CAstPattern;
import com.ibm.wala.cast.util.CAstPattern.Segments;
import com.ibm.wala.cast.util.CAstPrinter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
public class TestCAstPattern {
private static final int NAME_ASSERTION_SINGLE = 501;
private static final int NAME_ASSERTION_MULTI = 502;
private static class TestingCAstImpl extends CAstImpl {
private final Map<String, Object> testNameMap = new HashMap<>();
@Override
public CAstNode makeNode(int kind, List<CAstNode> children) {
if (kind == NAME_ASSERTION_SINGLE || kind == NAME_ASSERTION_MULTI) {
assert children.size() == 2;
final Object child0Value = children.get(0).getValue();
assert child0Value instanceof String;
final String name = (String) child0Value;
@SuppressWarnings("unused")
CAstNode result = children.get(1);
if (kind == NAME_ASSERTION_SINGLE) {
testNameMap.put(name, children.get(1));
} else {
@SuppressWarnings("unchecked")
ArrayList<CAstNode> nodeList = (ArrayList<CAstNode>) testNameMap.get(name);
if (nodeList == null) {
nodeList = new ArrayList<>();
testNameMap.put(name, nodeList);
}
nodeList.add(children.get(1));
}
return children.get(1);
} else {
return super.makeNode(kind, children);
}
}
}
private static void test(CAstPattern p, CAstNode n, Map<String, Object> names) {
System.err.println(("testing pattern " + p));
System.err.println(("testing with input " + CAstPrinter.print(n)));
if (names == null) {
Assert.assertFalse(p.match(n, null));
} else {
Segments s = CAstPattern.match(p, n);
Assert.assertNotNull(s);
for (Map.Entry<String, Object> entry : names.entrySet()) {
Object o = entry.getValue();
final String nm = entry.getKey();
if (o instanceof CAstNode) {
System.err.println(("found " + CAstPrinter.print(s.getSingle(nm)) + " for " + nm));
Assert.assertEquals(
"for name " + nm + ": expected " + entry.getValue() + " but got " + s.getSingle(nm),
entry.getValue(),
s.getSingle(nm));
} else {
for (CAstNode node : s.getMultiple(nm)) {
System.err.println(("found " + CAstPrinter.print(node) + " for " + nm));
}
Assert.assertEquals(
"for name " + nm + ": expected " + entry.getValue() + " but got " + s.getMultiple(nm),
entry.getValue(),
s.getMultiple(nm));
}
}
}
}
private final CAstPattern simpleNamePattern =
CAstPattern.parse("<top>BINARY_EXPR(\"+\",<left>\"prefix\",\"suffix\")");
private final CAstNode simpleNameAst;
private final Map<String, Object> simpleNameMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleNameAst =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_SINGLE, Ast.makeConstant("left"), Ast.makeConstant("prefix")),
Ast.makeConstant("suffix")));
simpleNameMap = Ast.testNameMap;
}
@Test
public void testSimpleName() {
test(simpleNamePattern, simpleNameAst, simpleNameMap);
}
private final CAstPattern simpleStarNamePattern =
CAstPattern.parse("<top>BINARY_EXPR(\"+\",*,<right>\"suffix\")");
private final CAstNode simpleStarNameAst;
private final Map<String, Object> simpleStarNameMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleStarNameAst =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeConstant("prefix"),
Ast.makeNode(
NAME_ASSERTION_SINGLE, Ast.makeConstant("right"), Ast.makeConstant("suffix"))));
simpleStarNameMap = Ast.testNameMap;
}
@Test
public void testSimpleStarName() {
test(simpleStarNamePattern, simpleStarNameAst, simpleStarNameMap);
}
private final CAstPattern simpleRepeatedPattern =
CAstPattern.parse("<top>BINARY_EXPR(\"+\",<children>@(VAR(*))@)");
private final CAstNode simpleRepeatedAstOne;
private final Map<String, Object> simpleRepeatedMapOne;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleRepeatedAstOne =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix")))));
simpleRepeatedMapOne = Ast.testNameMap;
}
@Test
public void testSimpleRepeatedOne() {
test(simpleRepeatedPattern, simpleRepeatedAstOne, simpleRepeatedMapOne);
}
private final CAstNode simpleRepeatedAstTwo;
private final Map<String, Object> simpleRepeatedMapTwo;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleRepeatedAstTwo =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("prefix"))),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix")))));
simpleRepeatedMapTwo = Ast.testNameMap;
}
@Test
public void testSimpleRepeatedTwo() {
test(simpleRepeatedPattern, simpleRepeatedAstTwo, simpleRepeatedMapTwo);
}
private final CAstNode simpleRepeatedAstThree;
private final Map<String, Object> simpleRepeatedMapThree;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleRepeatedAstThree =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("prefix"))),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("middle"))),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix")))));
simpleRepeatedMapThree = Ast.testNameMap;
}
@Test
public void testSimpleRepeatedThree() {
test(simpleRepeatedPattern, simpleRepeatedAstThree, simpleRepeatedMapThree);
}
private final CAstPattern simpleDoubleStarPattern =
CAstPattern.parse("<top>BINARY_EXPR(\"+\",<children>**)");
private final CAstNode simpleDoubleStarAst;
private final Map<String, Object> simpleDoubleStarMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleDoubleStarAst =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("prefix"))),
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("children"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix")))));
simpleDoubleStarMap = Ast.testNameMap;
}
@Test
public void testSimpleDoubleStar() {
test(simpleDoubleStarPattern, simpleDoubleStarAst, simpleDoubleStarMap);
}
private final CAstPattern simpleAlternativePattern =
CAstPattern.parse(
"<top>BINARY_EXPR(\"+\",<firstchild>|(VAR(\"suffix\")||VAR(\"prefix\"))|,*)");
private final CAstNode simpleAlternativeAst;
private final Map<String, Object> simpleAlternativeMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleAlternativeAst =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("firstchild"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("prefix"))),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix"))));
simpleAlternativeMap = Ast.testNameMap;
}
@Test
public void testSimpleAlternative() {
test(simpleAlternativePattern, simpleAlternativeAst, simpleAlternativeMap);
}
private final CAstPattern simpleOptionalPattern =
CAstPattern.parse("<top>BINARY_EXPR(\"+\",?(VAR(\"prefix\"))?,<child>VAR(\"suffix\"))");
private final CAstNode simpleOptionalAstWith;
private final Map<String, Object> simpleOptionalMapWith;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleOptionalAstWith =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("prefix")),
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("child"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix")))));
simpleOptionalMapWith = Ast.testNameMap;
}
@Test
public void testSimpleOptionalWith() {
test(simpleOptionalPattern, simpleOptionalAstWith, simpleOptionalMapWith);
}
private final CAstNode simpleOptionalAstNot;
private final Map<String, Object> simpleOptionalMapNot;
{
TestingCAstImpl Ast = new TestingCAstImpl();
simpleOptionalAstNot =
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("top"),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
NAME_ASSERTION_SINGLE,
Ast.makeConstant("child"),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("suffix")))));
simpleOptionalMapNot = Ast.testNameMap;
}
@Test
public void testSimpleOptionalNot() {
test(simpleOptionalPattern, simpleOptionalAstNot, simpleOptionalMapNot);
}
private final String recursiveTreeStr =
"|({leaf}|(<const>CONSTANT()||VAR(<vars>*))|||{node}BINARY_EXPR(\"+\",`leaf`,|(`leaf`||`node`)|))|";
private final CAstPattern recursiveTreePattern = CAstPattern.parse(recursiveTreeStr);
private final CAstNode recursiveTreeOneAst;
private final Map<String, Object> recursiveTreeOneMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
recursiveTreeOneAst =
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("x"))),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("y"))));
recursiveTreeOneMap = Ast.testNameMap;
}
@Test
public void testRecursiveTreeOne() {
test(recursiveTreePattern, recursiveTreeOneAst, recursiveTreeOneMap);
}
private final CAstNode recursiveTreeTwoAst;
private final Map<String, Object> recursiveTreeTwoMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
recursiveTreeTwoAst =
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("x"))),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("y"))),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("z")))));
recursiveTreeTwoMap = Ast.testNameMap;
}
@Test
public void testRecursiveTreeTwo() {
test(recursiveTreePattern, recursiveTreeTwoAst, recursiveTreeTwoMap);
}
private final CAstNode recursiveTreeFiveAst;
private final Map<String, Object> recursiveTreeFiveMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
recursiveTreeFiveAst =
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("u"))),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("v"))),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("w"))),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("vars"),
Ast.makeConstant("x"))),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("vars"),
Ast.makeConstant("y"))),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI,
Ast.makeConstant("vars"),
Ast.makeConstant("z"))))))));
recursiveTreeFiveMap = Ast.testNameMap;
}
@Test
public void testRecursiveTreeFive() {
test(recursiveTreePattern, recursiveTreeFiveAst, recursiveTreeFiveMap);
}
private final CAstPattern buggyRecursiveTreePattern =
CAstPattern.parse(
"|({leaf}|(<const>CONSTANT()||VAR(<vars>*))|||{node}BINARY_EXPR(\"+\",`leaf`,`node`))|");
@Test
public void testBuggyRecursiveTreeOne() {
test(buggyRecursiveTreePattern, recursiveTreeOneAst, null);
}
@Test
public void testBuggyRecursiveTreeTwo() {
test(buggyRecursiveTreePattern, recursiveTreeTwoAst, null);
}
@Test
public void testBuggyRecursiveTreeFive() {
test(buggyRecursiveTreePattern, recursiveTreeFiveAst, null);
}
private static final String extraTestsStr =
"BINARY_EXPR(|(\"==\"||\"\\==\")|,|(CONSTANT()||VAR(CONSTANT()))|,|(CONSTANT()||VAR(CONSTANT()))|)";
private final CAstPattern testedTreePattern =
CAstPattern.parse(
"{top}|(" + recursiveTreeStr + "||BINARY_EXPR(\",\"," + extraTestsStr + ",`top`))|");
@Test
public void testTestedTreeOne() {
test(testedTreePattern, recursiveTreeOneAst, recursiveTreeOneMap);
}
@Test
public void testTestedTreeTwo() {
test(testedTreePattern, recursiveTreeTwoAst, recursiveTreeTwoMap);
}
@Test
public void testTestedTreeFive() {
test(testedTreePattern, recursiveTreeFiveAst, recursiveTreeFiveMap);
}
private final CAstNode testedTreeOneAst;
private final Map<String, Object> testedTreeOneMap;
{
TestingCAstImpl Ast = new TestingCAstImpl();
testedTreeOneAst =
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant(","),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("=="),
Ast.makeNode(CAstNode.VAR, Ast.makeConstant("x")),
Ast.makeConstant(7)),
Ast.makeNode(
CAstNode.BINARY_EXPR,
Ast.makeConstant("+"),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("x"))),
Ast.makeNode(
CAstNode.VAR,
Ast.makeNode(
NAME_ASSERTION_MULTI, Ast.makeConstant("vars"), Ast.makeConstant("y")))));
testedTreeOneMap = Ast.testNameMap;
}
@Test
public void testTestedTreeOneWithTest() {
test(testedTreePattern, testedTreeOneAst, testedTreeOneMap);
}
}
| 18,788
| 31.563258
| 106
|
java
|
WALA
|
WALA-master/cast/src/test/java/com/ibm/wala/cast/test/TestCAstTranslator.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.test;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.ir.ssa.AstIRFactory;
import com.ibm.wala.cast.loader.SingleClassLoaderFactory;
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.classLoader.SourceFileModule;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
public abstract class TestCAstTranslator {
protected static class TranslatorAssertions {
private final Set<String> classes = new HashSet<>();
private final Map<String, String> supers = new HashMap<>();
private final Set<Pair<String, String>> instanceFields = new HashSet<>();
private final Set<Pair<String, String>> staticFields = new HashSet<>();
private final Map<Pair<String, Object>, Object> instanceMethods = HashMapFactory.make();
private final Map<Pair<String, Object>, Object> staticMethods = HashMapFactory.make();
private Set<String> getClasses() {
return classes;
}
private Map<String, String> getSuperClasses() {
return supers;
}
private Set<Pair<String, String>> getInstanceFields() {
return instanceFields;
}
private Set<Pair<String, String>> getStaticFields() {
return staticFields;
}
private Map<Pair<String, Object>, Object> getInstanceMethods() {
return instanceMethods;
}
private Map<Pair<String, Object>, Object> getStaticMethods() {
return staticMethods;
}
public TranslatorAssertions(Object[][] data) {
for (Object[] entry : data) {
String clsName = (String) entry[0];
this.classes.add(clsName);
String superName = (String) entry[1];
this.supers.put(clsName, superName);
String[] instanceFields = (String[]) entry[2];
if (instanceFields != null) {
for (String instanceField : instanceFields) {
this.instanceFields.add(Pair.make(clsName, instanceField));
}
}
String[] staticFields = (String[]) entry[3];
if (staticFields != null) {
for (String staticField : staticFields) {
this.staticFields.add(Pair.make(clsName, staticField));
}
}
Pair<?, ?>[] instanceMethods = (Pair<?, ?>[]) entry[4];
if (instanceMethods != null) {
for (Pair<?, ?> instanceMethod : instanceMethods) {
this.instanceMethods.put(
Pair.make(clsName, (Object) instanceMethod.fst), instanceMethod.snd);
}
}
Pair<?, ?>[] staticMethods = (Pair<?, ?>[]) entry[5];
if (staticMethods != null) {
for (Pair<?, ?> staticMethod : staticMethods) {
this.staticMethods.put(Pair.make(clsName, (Object) staticMethod.fst), staticMethod.snd);
}
}
}
}
}
protected abstract Language getLanguage();
protected abstract String getTestPath();
protected abstract SingleClassLoaderFactory getClassLoaderFactory();
protected final IRFactory<IMethod> factory = AstIRFactory.makeDefaultFactory();
protected final SSAOptions options = new SSAOptions();
public ClassHierarchy runTranslator(SourceFileModule[] fileNames) throws Exception {
SingleClassLoaderFactory loaders = getClassLoaderFactory();
AnalysisScope scope = CAstCallGraphUtil.makeScope(fileNames, loaders, getLanguage());
ClassHierarchy cha = ClassHierarchyFactory.make(scope, loaders, getLanguage());
return cha;
}
protected void dump(ClassHierarchy cha) {
for (Object name : cha) {
IClass cls = (IClass) name;
System.err.println(("class " + cls));
for (Object name2 : cls.getDeclaredInstanceFields()) {
IField fld = (IField) name2;
System.err.println(("instance field " + fld));
}
for (Object name2 : cls.getDeclaredStaticFields()) {
IField fld = (IField) name2;
System.err.println(("static field " + fld));
}
for (Object name2 : cls.getDeclaredMethods()) {
IMethod mth = (IMethod) name2;
if (mth.isStatic()) System.err.print("static ");
System.err.println(
("method " + mth + " with " + mth.getNumberOfParameters() + " parameters"));
for (int i = 0; i < mth.getNumberOfParameters(); i++) {
System.err.println(("param " + i + ": " + mth.getParameterType(i)));
}
System.err.println(factory.makeIR(mth, Everywhere.EVERYWHERE, options));
}
}
}
public void checkAssertions(ClassHierarchy cha, TranslatorAssertions assertions) {
Set<String> classes = assertions.getClasses();
Map<String, String> supers = assertions.getSuperClasses();
Set<Pair<String, String>> instanceFields = assertions.getInstanceFields();
Set<Pair<String, String>> staticFields = assertions.getStaticFields();
Map<Pair<String, Object>, Object> instanceMethods = assertions.getInstanceMethods();
Map<Pair<String, Object>, Object> staticMethods = assertions.getStaticMethods();
int clsCount = 0;
for (Object name : cha) {
IClass cls = (IClass) name;
clsCount++;
Assert.assertTrue(
"found class " + cls.getName().toString(), classes.contains(cls.getName().toString()));
if (cls.getSuperclass() == null) {
Assert.assertNull(
cls.getName() + " has no superclass", supers.get(cls.getName().toString()));
} else {
Assert.assertEquals(
"super of " + cls.getName() + " is " + cls.getSuperclass().getName(),
supers.get(cls.getName().toString()),
cls.getSuperclass().getName().toString());
}
for (Object name2 : cls.getDeclaredInstanceFields()) {
IField fld = (IField) name2;
Assert.assertTrue(
cls.getName() + " has field " + fld.getName(),
instanceFields.contains(Pair.make(cls.getName().toString(), fld.getName().toString())));
}
for (Object name2 : cls.getDeclaredStaticFields()) {
IField fld = (IField) name2;
Assert.assertTrue(
cls.getName() + " has static field " + fld.getName(),
staticFields.contains(Pair.make(cls.getName().toString(), fld.getName().toString())));
}
for (Object name2 : cls.getDeclaredMethods()) {
IMethod mth = (IMethod) name2;
Integer np = mth.getNumberOfParameters();
Pair<String, String> key = Pair.make(cls.getName().toString(), mth.getName().toString());
if (mth.isStatic()) {
Assert.assertTrue(
cls.getName() + " has static method " + mth.getName(),
staticMethods.containsKey(key));
Assert.assertEquals(
cls.getName() + "::" + mth.getName() + " has " + np + " parameters",
staticMethods.get(key),
np);
} else {
Assert.assertTrue(
cls.getName() + " has method " + mth.getName(), instanceMethods.containsKey(key));
Assert.assertEquals(
cls.getName() + "::" + mth.getName() + " has " + np + " parameters",
instanceMethods.get(key),
np);
}
}
}
Assert.assertEquals("want " + classes.size() + " classes", clsCount, classes.size());
}
protected void testInternal(String[] args, TranslatorAssertions assertions) throws Exception {
String testPath = getTestPath();
SourceFileModule[] fileNames = new SourceFileModule[args.length];
for (int i = 0; i < args.length; i++) {
if (new File(args[i]).exists()) {
fileNames[i] =
CAstCallGraphUtil.makeSourceModule(new File(args[i]).toURI().toURL(), args[i]);
} else if (new File(testPath + args[i]).exists()) {
fileNames[i] =
CAstCallGraphUtil.makeSourceModule(
new File(testPath + args[i]).toURI().toURL(), args[i]);
} else {
URL url = getClass().getClassLoader().getResource(args[i]);
fileNames[i] = CAstCallGraphUtil.makeSourceModule(url, args[i]);
}
Assert.assertNotNull(args[i], fileNames[i]);
}
ClassHierarchy cha = runTranslator(fileNames);
dump(cha);
if (assertions != null) {
checkAssertions(cha, assertions);
} else {
System.err.println(("WARNING: no assertions for " + getClass()));
}
}
protected void testInternal(String arg, TranslatorAssertions assertions) {
try {
testInternal(new String[] {arg}, assertions);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.toString());
}
}
}
| 9,456
| 34.958175
| 100
|
java
|
WALA
|
WALA-master/cast/src/test/java/com/ibm/wala/cast/test/TestConstantCollector.java
|
package com.ibm.wala.cast.test;
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.CAstImpl;
import com.ibm.wala.cast.tree.impl.CAstOperator;
import com.ibm.wala.cast.tree.rewrite.AstConstantFolder;
import com.ibm.wala.cast.util.AstConstantCollector;
import com.ibm.wala.cast.util.CAstPattern;
import com.ibm.wala.cast.util.CAstPattern.Segments;
import com.ibm.wala.util.collections.EmptyIterator;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.junit.Test;
public class TestConstantCollector {
private final CAst ast = new CAstImpl();
private static CAstEntity fakeEntity(CAstNode root) {
return new CAstEntity() {
@Override
public int getKind() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getSignature() {
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getArgumentNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNode[] getArgumentDefaults() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getArgumentCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
return Collections.emptyMap();
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
return EmptyIterator.instance();
}
@Override
public CAstNode getAST() {
return root;
}
@Override
public CAstControlFlowMap getControlFlow() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstSourcePositionMap getSourceMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public Position getPosition() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNodeTypeMap getNodeTypeMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<CAstQualifier> getQualifiers() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstType getType() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<CAstAnnotation> getAnnotations() {
// TODO Auto-generated method stub
return null;
}
@Override
public Position getPosition(int arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Position getNamePosition() {
// TODO Auto-generated method stub
return null;
}
};
}
private final CAstNode root1 =
ast.makeNode(
CAstNode.BLOCK_STMT,
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1")),
ast.makeConstant(15)));
@Test
public void testSegmentsRoot1() {
Collection<Segments> x =
CAstPattern.findAll(AstConstantCollector.simpleValuePattern, fakeEntity(root1));
assert x.size() == 1;
}
@Test
public void testRoot1() {
Map<String, Object> x = AstConstantCollector.collectConstants(fakeEntity(root1));
assert x.size() == 1;
}
private final CAstNode root2 =
ast.makeNode(
CAstNode.BLOCK_STMT,
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1")),
ast.makeConstant(15)),
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1")),
ast.makeConstant(14)));
@Test
public void testSegmentsRoot2() {
Collection<Segments> x =
CAstPattern.findAll(AstConstantCollector.simpleValuePattern, fakeEntity(root2));
assert x.size() == 2;
}
private final CAstNode root3 =
ast.makeNode(
CAstNode.BLOCK_EXPR,
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1")),
ast.makeConstant(15)),
ast.makeNode(
CAstNode.BINARY_EXPR,
CAstOperator.OP_ADD,
ast.makeConstant(10),
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1"))));
public static final CAstPattern toCodePattern3 =
CAstPattern.parse("BINARY_EXPR(*,\"10\",\"15\")");
@Test
public void testRoot3() {
CAstEntity ce = fakeEntity(root3);
CAstEntity nce = new AstConstantFolder().fold(ce);
Collection<Segments> matches = CAstPattern.findAll(toCodePattern3, nce);
assert matches.size() == 1;
}
private final CAstNode root4 =
ast.makeNode(
CAstNode.BLOCK_STMT,
ast.makeNode(
CAstNode.GLOBAL_DECL,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1")),
ast.makeNode(CAstNode.VAR, ast.makeConstant("var2"))),
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var1")),
ast.makeConstant(14)),
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var2")),
ast.makeConstant(15)),
ast.makeNode(
CAstNode.ASSIGN,
ast.makeNode(CAstNode.VAR, ast.makeConstant("var3")),
ast.makeConstant(16)));
@Test
public void testRoot4() {
Map<String, Object> x = AstConstantCollector.collectConstants(fakeEntity(root4));
assert x.size() == 1 : x;
}
}
| 6,408
| 26.865217
| 88
|
java
|
WALA
|
WALA-master/cast/src/test/java/com/ibm/wala/cast/test/TestNativeTranslator.java
|
package com.ibm.wala.cast.test;
import com.ibm.wala.cast.ir.translator.NativeTranslatorToCAst;
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.CAstImpl;
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.ssa.IR;
import com.ibm.wala.util.io.TemporaryFile;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import org.junit.Test;
public class TestNativeTranslator {
static {
System.loadLibrary("xlator_test");
}
private static native CAstNode inventAst(SmokeXlator ast);
private static class SmokeXlator extends NativeTranslatorToCAst {
private SmokeXlator(CAst Ast, URL sourceURL) throws IOException {
super(Ast, sourceURL, TemporaryFile.urlToFile("temp", sourceURL).getAbsolutePath());
}
@Override
public <C extends RewriteContext<K>, K extends CopyKey<K>> void addRewriter(
CAstRewriterFactory<C, K> factory, boolean prepend) {
assert false;
}
@Override
public CAstEntity translateToCAst() {
return new CAstEntity() {
@Override
public int getKind() {
return CAstEntity.FUNCTION_ENTITY;
}
@Override
public String getName() {
return sourceURL.getFile();
}
@Override
public String getSignature() {
return "()";
}
@Override
public String[] getArgumentNames() {
return new String[0];
}
@Override
public CAstNode[] getArgumentDefaults() {
return new CAstNode[0];
}
@Override
public int getArgumentCount() {
return 0;
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() {
return Collections.emptyMap();
}
@Override
public Iterator<CAstEntity> getScopedEntities(CAstNode construct) {
return Collections.emptyIterator();
}
private CAstNode ast;
@Override
public CAstNode getAST() {
if (ast == null) {
ast = inventAst(SmokeXlator.this);
}
return ast;
}
@Override
public CAstControlFlowMap getControlFlow() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstSourcePositionMap getSourceMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public Position getPosition() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstNodeTypeMap getNodeTypeMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<CAstQualifier> getQualifiers() {
// TODO Auto-generated method stub
return null;
}
@Override
public CAstType getType() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<CAstAnnotation> getAnnotations() {
// TODO Auto-generated method stub
return null;
}
@Override
public Position getPosition(int arg) {
// TODO Auto-generated method stub
return null;
}
@Override
public Position getNamePosition() {
// TODO Auto-generated method stub
return null;
}
};
}
}
@Test
public void testNativeCAst() throws IOException {
CAst Ast = new CAstImpl();
URL junk = IR.class.getClassLoader().getResource("primordial.txt");
SmokeXlator xlator = new SmokeXlator(Ast, junk);
CAstNode ast = xlator.translateToCAst().getAST();
System.err.println(ast);
assert ast.getChildCount() == 3;
}
}
| 4,496
| 24.844828
| 90
|
java
|
WALA
|
WALA-master/cast/src/testFixtures/java/com/ibm/wala/cast/util/test/TestCallGraphShape.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.util.test;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import java.util.Collection;
import java.util.Iterator;
public abstract class TestCallGraphShape {
public void verifyCFGAssertions(CallGraph CG, Object[][] assertionData) {
for (Object[] dat : assertionData) {
String function = (String) dat[0];
for (CGNode N : getNodes(CG, function)) {
int[][] edges = (int[][]) dat[1];
SSACFG cfg = N.getIR().getControlFlowGraph();
for (int i = 0; i < edges.length; i++) {
SSACFG.BasicBlock bb = cfg.getNode(i);
assert edges[i].length == cfg.getSuccNodeCount(bb) : "basic block " + i;
for (int j = 0; j < edges[i].length; j++) {
assert cfg.hasEdge(bb, cfg.getNode(edges[i][j]));
}
}
}
}
}
public void verifySourceAssertions(CallGraph CG, Object[][] assertionData) {
for (Object[] dat : assertionData) {
String function = (String) dat[0];
for (CGNode N : getNodes(CG, function)) {
if (N.getMethod() instanceof AstMethod) {
AstMethod M = (AstMethod) N.getMethod();
SSAInstruction[] insts = N.getIR().getInstructions();
insts:
for (int i = 0; i < insts.length; i++) {
SSAInstruction inst = insts[i];
if (inst != null) {
Position pos = M.getSourcePosition(i);
if (pos != null) {
String fileName = pos.getURL().toString();
if (fileName.lastIndexOf('/') >= 0) {
fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
}
for (Object[] assertionDatum : assertionData) {
String file = (String) assertionDatum[1];
if (file.indexOf('/') >= 0) {
file = file.substring(file.lastIndexOf('/') + 1);
}
if (file.equalsIgnoreCase(fileName)) {
if (pos.getFirstLine() >= (Integer) assertionDatum[2]
&& (pos.getLastLine() != -1 ? pos.getLastLine() : pos.getFirstLine())
<= (Integer) assertionDatum[3]) {
System.err.println(
"found " + inst + " of " + M + " at expected position " + pos);
continue insts;
}
}
}
assert false
: "unexpected location " + pos + " for " + inst + " of " + M + "\n" + N.getIR();
}
}
}
}
}
}
}
public static class Name {
String name;
int instructionIndex;
int vn;
public Name(int vn, int instructionIndex, String name) {
this.vn = vn;
this.name = name;
this.instructionIndex = instructionIndex;
}
}
public void verifyNameAssertions(CallGraph CG, Object[][] assertionData) {
for (Object[] element : assertionData) {
for (CGNode N : getNodes(CG, (String) element[0])) {
IR ir = N.getIR();
Name[] names = (Name[]) element[1];
for (Name name : names) {
System.err.println("looking for " + name.name + ", " + name.vn + " in " + N);
String[] localNames = ir.getLocalNames(name.instructionIndex, name.vn);
boolean found = false;
for (String localName : localNames) {
if (localName.equals(name.name)) {
found = true;
break;
}
}
assert found : "no name " + name.name + " for " + N + "\n" + ir;
}
}
}
}
protected void verifyGraphAssertions(CallGraph CG, Object[][] assertionData) {
// System.err.println(CG);
if (assertionData == null) {
return;
}
for (Object[] assertionDatum : assertionData) {
check_target:
for (int j = 0; j < ((String[]) assertionDatum[1]).length; j++) {
Iterator<CGNode> srcs =
(assertionDatum[0] instanceof String)
? getNodes(CG, (String) assertionDatum[0]).iterator()
: new NonNullSingletonIterator<>(CG.getFakeRootNode());
assert srcs.hasNext() : "cannot find " + assertionDatum[0];
boolean checkAbsence = false;
String targetName = ((String[]) assertionDatum[1])[j];
if (targetName.startsWith("!")) {
checkAbsence = true;
targetName = targetName.substring(1);
}
while (srcs.hasNext()) {
CGNode src = srcs.next();
for (CallSiteReference sr : Iterator2Iterable.make(src.iterateCallSites())) {
Iterator<CGNode> dsts = getNodes(CG, targetName).iterator();
if (!checkAbsence) {
assert dsts.hasNext() : "cannot find " + targetName;
}
while (dsts.hasNext()) {
CGNode dst = dsts.next();
for (CGNode cgNode : CG.getPossibleTargets(src, sr)) {
if (cgNode.equals(dst)) {
if (checkAbsence) {
System.err.println(("found unexpected " + src + " --> " + dst + " at " + sr));
assert false : "found edge " + assertionDatum[0] + " ---> " + targetName;
} else {
System.err.println(("found expected " + src + " --> " + dst + " at " + sr));
continue check_target;
}
}
}
}
}
}
System.err.println("cannot find edge " + assertionDatum[0] + " ---> " + targetName);
assert checkAbsence : "cannot find edge " + assertionDatum[0] + " ---> " + targetName;
}
}
}
/**
* Verifies that none of the nodes that match the source description has an edge to any of the
* nodes that match the destination description. (Used for checking for false connections in the
* callgraph)
*/
public void verifyNoEdges(CallGraph CG, String sourceDescription, String destDescription) {
Collection<CGNode> sources = getNodes(CG, sourceDescription);
Collection<CGNode> dests = getNodes(CG, destDescription);
for (Object source : sources) {
for (Object dest : dests) {
for (CGNode n : Iterator2Iterable.make(CG.getSuccNodes((CGNode) source))) {
if (n.equals(dest)) {
assert false : "Found a link from " + source + " to " + dest;
}
}
}
}
}
public static final Object ROOT =
new Object() {
@Override
public String toString() {
return "CallGraphRoot";
}
};
public abstract Collection<CGNode> getNodes(CallGraph CG, String functionIdentifier);
}
| 7,500
| 34.215962
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/ArrayBoundsGraph.java
|
package com.ibm.wala.analysis.arraybounds;
import com.ibm.wala.analysis.arraybounds.hypergraph.DirectedHyperEdge;
import com.ibm.wala.analysis.arraybounds.hypergraph.DirectedHyperGraph;
import com.ibm.wala.analysis.arraybounds.hypergraph.HyperNode;
import com.ibm.wala.analysis.arraybounds.hypergraph.SoftFinalHyperNode;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight.Type;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.edgeweights.AdditiveEdgeWeight;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.edgeweights.EdgeWeight;
import com.ibm.wala.util.collections.Pair;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Some thoughts about implementation details, not mentioned in [1]:
*
* <p>As it is written The paper describes, that the distance is equal to the shortest hyper path.
* But what if we don't know anything about a variable (i.e. it is returned by a method)? There will
* be no path at all, the distance should be unlimited.
*
* <p>Initializing all nodes with -infinity instead of infinity, seems to work at first glance, as
* we also have hyper edges with more than one source, which cause the maximum to be propagated
* instead of minimum. However, this will not work, as loops will not get updated properly.
*
* <p>We need to make sure, that only nodes, which are not connected to the source of shortest path
* computation are set to infinity. To do so, it is enough to set nodes, which don't have a
* predecessor to infinity. (Nodes in cycles will always have an ancestor, which is not part of the
* cycle. So all nodes are either connected to the source, or a node with no predecessor.)
*
* <p>In this implementation this is done, by adding an infinity node and connect all lose ends to
* it (see {@link ArrayBoundsGraphBuilder#bundleDeadEnds(ArrayBoundsGraph)}). Note, that array
* length and the zero node are dead ends, if they are not the source of a shortest path
* computation. To prevent changing the inequality graph, depending on which source is used, a kind
* of trap door construct is used (See {@link ArrayBoundsGraph#createSourceVar(Integer)}).
*
* <p>There are some variations, but these are minor changes to improve results:
*
* <ul>
* <li>handling of constants (see {@link ArrayBoundsGraph#addConstant(Integer, Integer)})
* <li>pi nodes (see {@link ArrayBoundsGraph#addPhi(Integer)})
* <li>array length nodes (see {@link ArrayBoundsGraph#arrayLength})
* </ul>
*
* [1] Bodík, Rastislav, Rajiv Gupta, and Vivek Sarkar. "ABCD: eliminating array bounds checks on
* demand." ACM SIGPLAN Notices. Vol. 35. No. 5. ACM, 2000.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
@SuppressWarnings({"JavadocReference", "javadoc"})
public class ArrayBoundsGraph extends DirectedHyperGraph<Integer> {
/**
* We need a ssa variable representing zero. So we just use an integer, which is never produced by
* ssa generation
*/
public static final Integer ZERO = -1;
public static final Integer ZERO_HELPER = -3;
/**
* We need a ssa variable representing unlimited (values we don't know anything about). So we just
* use an integer, which is never produced by ssa generation
*/
public static final Integer UNLIMITED = -2;
/**
* Maps each array variable to a set of variables, which are used as Index for accessing that
* array
*/
private final HashMap<Integer, Set<Integer>> arrayAccess;
/**
* Maps each array variable to a node which is parent to all variables, that contain the array
* length
*/
private final HashMap<Integer, Integer> arrayLength;
private final HashSet<Integer> phis;
private final HashMap<Integer, Pair<Integer, Integer>> constants;
/**
* For simplicity we introduce extra variables, for arrayLength, to have a unique node
* representing the array length, even if the length is accessed more than once in the code.
*
* <p>Start with -3 so it is unequal to other constants
*/
private Integer arrayCounter = -4;
public ArrayBoundsGraph() {
this.arrayAccess = new HashMap<>();
this.arrayLength = new HashMap<>();
this.constants = new HashMap<>();
this.phis = new HashSet<>();
this.addNode(UNLIMITED);
this.phis.add(UNLIMITED);
this.createSourceVar(ZERO);
this.addNode(ZERO_HELPER);
this.addEdge(ZERO, ZERO_HELPER);
// this.phis.add(ZERO_HELPER);
}
public void postProcessConstants() {
for (Map.Entry<Integer, Pair<Integer, Integer>> entry : constants.entrySet()) {
HyperNode<Integer> constantNode = this.getNodes().get(entry.getKey());
final Pair<Integer, Integer> value = entry.getValue();
HyperNode<Integer> helper1 = this.getNodes().get(value.fst);
HyperNode<Integer> helper2 = this.getNodes().get(value.snd);
for (DirectedHyperEdge<Integer> edge : constantNode.getOutEdges()) {
if (!edge.getDestination().contains(helper2)) {
edge.getSource().remove(constantNode);
edge.getSource().add(helper1);
}
}
}
}
public void addAdditionEdge(Integer src, Integer dst, Integer value) {
this.addNode(src);
final HyperNode<Integer> srcNode = this.getNodes().get(src);
this.addNode(dst);
final HyperNode<Integer> dstNode = this.getNodes().get(dst);
Weight weight;
if (value == 0) {
weight = Weight.ZERO;
} else {
weight = new Weight(Type.NUMBER, value);
}
final EdgeWeight edgeWeight = new AdditiveEdgeWeight(weight);
final DirectedHyperEdge<Integer> edge = new DirectedHyperEdge<>();
edge.getDestination().add(dstNode);
edge.getSource().add(srcNode);
edge.setWeight(edgeWeight);
this.getEdges().add(edge);
}
public void addArray(Integer array) {
this.getArrayNode(array);
}
/**
* Add variable as constant with value value.
*
* <p>This will create the following construct: [zero] -(value)-> [h1] -0- > [variable]
* -(-value)-> [h2] -0-> [zero].
*
* <p>The bidirectional linking, allows things like
*
* <pre>
* int[] a = new int[2]();
* a[0] = 1;
* </pre>
*
* to work properly. h1, h2 are helper nodes: [zero] and [variable] may have other predecessors,
* this will cause their in edges to be merged to a single hyper edge with weight zero. The helper
* nodes are inserted to keep the proper distance from [zero].
*/
public void addConstant(Integer variable, Integer value) {
final Integer helper1 = this.generateNewVar();
final Integer helper2 = this.generateNewVar();
this.addAdditionEdge(ZERO_HELPER, helper1, value);
// this.addEdge(helper1, variable);
this.addAdditionEdge(variable, helper2, -value);
this.addEdge(helper2, ZERO_HELPER);
this.constants.put(variable, Pair.make(helper1, helper2));
}
public void addEdge(Integer src, Integer dst) {
this.addAdditionEdge(src, dst, 0);
}
public HyperNode<Integer> addNode(Integer value) {
HyperNode<Integer> result;
if (!this.getNodes().containsKey(value)) {
result = new HyperNode<>(value);
this.getNodes().put(value, result);
} else {
result = this.getNodes().get(value);
}
return result;
}
public void addPhi(Integer dst) {
this.phis.add(dst);
}
public void addPi(Integer dst, Integer src1, Integer src2) {
this.addEdge(src1, dst);
this.addEdge(src2, dst);
}
/**
* Adds var as source var. A source var is a variable, which can be used as source for shortest
* path computation.
*
* <p>This will create the following construct: [unlimited] -> [var] -> [var]
* -(unlimited)-> [unlimited]
*
* <p>This is a trap door construct: if [var] is not set to 0 it will get the value unlimited, if
* [var] is set to 0 it will stay 0.
*/
public void createSourceVar(Integer var) {
if (this.getNodes().containsKey(var)) {
throw new AssertionError("Source variables should only be created once.");
}
SoftFinalHyperNode<Integer> node = new SoftFinalHyperNode<>(var);
this.getNodes().put(var, node);
// final HyperNode<Integer> varNode = this.getNodes().get(var);
// final HyperNode<Integer> unlimitedNode = this.getNodes().get(UNLIMITED);
// final DirectedHyperEdge<Integer> edge = new DirectedHyperEdge<>();
// edge.setWeight(new AdditiveEdgeWeight(Weight.UNLIMITED));
// edge.getSource().add(varNode);
// edge.getDestination().add(unlimitedNode);
// this.getEdges().add(edge);
this.addEdge(UNLIMITED, var);
// this.addEdge(var, var);
}
public Integer generateNewVar() {
final int result = this.arrayCounter;
this.arrayCounter -= 1;
return result;
}
public HashMap<Integer, Set<Integer>> getArrayAccess() {
return this.arrayAccess;
}
public HashMap<Integer, Integer> getArrayLength() {
return this.arrayLength;
}
public Integer getArrayNode(Integer array) {
Integer arrayVar;
if (!this.arrayLength.containsKey(array)) {
arrayVar = this.generateNewVar();
this.arrayLength.put(array, arrayVar);
this.createSourceVar(arrayVar);
} else {
arrayVar = this.arrayLength.get(array);
}
return arrayVar;
}
public HashSet<Integer> getPhis() {
return this.phis;
}
public void markAsArrayAccess(Integer array, Integer index) {
Set<Integer> indices;
if (!this.arrayAccess.containsKey(array)) {
indices = new HashSet<>();
this.arrayAccess.put(array, indices);
} else {
indices = this.arrayAccess.get(array);
}
indices.add(index);
this.addArray(array);
}
/** Mark variable as length for array. */
public void markAsArrayLength(Integer array, Integer variable) {
this.addEdge(this.getArrayNode(array), variable);
}
public void markAsDeadEnd(Integer variable) {
this.addEdge(UNLIMITED, variable);
}
public Weight getVariableWeight(Integer variable) {
if (constants.containsKey(variable)) {
variable = constants.get(variable).fst;
}
return this.getNodes().get(variable).getWeight();
}
@Override
public void reset() {
super.reset();
this.getNodes().get(UNLIMITED).setWeight(Weight.UNLIMITED);
this.getNodes().get(UNLIMITED).setNewWeight(Weight.UNLIMITED);
}
}
| 10,397
| 33.66
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/ArrayBoundsGraphBuilder.java
|
package com.ibm.wala.analysis.arraybounds;
import com.ibm.wala.analysis.arraybounds.hypergraph.DirectedHyperEdge;
import com.ibm.wala.analysis.arraybounds.hypergraph.HyperNode;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction.Operator;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayReferenceInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACFG.BasicBlock;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.Visitor;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @see ArrayBoundsGraph
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ArrayBoundsGraphBuilder {
private final IR ir;
/** Variables, which were already explored. */
private final HashSet<Integer> foundVariables;
private final DefUse defUse;
private final ArrayBoundsGraph lowerBoundGraph;
private final ArrayBoundsGraph upperBoundGraph;
private final Set<SSAArrayReferenceInstruction> arrayReferenceInstructions;
private final IBinaryOpInstruction.Operator SUB = IBinaryOpInstruction.Operator.SUB;
private final IBinaryOpInstruction.Operator ADD = IBinaryOpInstruction.Operator.ADD;
public ArrayBoundsGraphBuilder(IR ir) {
this.ir = ir;
this.foundVariables = new HashSet<>();
this.defUse = new DefUse(ir);
this.arrayReferenceInstructions = new HashSet<>();
this.lowerBoundGraph = new ArrayBoundsGraph();
this.upperBoundGraph = new ArrayBoundsGraph();
this.findArrayAccess();
this.exploreIr();
this.addConstructionLength();
this.lowerBoundGraph.updateNodeEdges();
this.upperBoundGraph.updateNodeEdges();
this.lowerBoundGraph.postProcessConstants();
this.upperBoundGraph.postProcessConstants();
this.lowerBoundGraph.updateNodeEdges();
this.upperBoundGraph.updateNodeEdges();
bundleDeadEnds(this.lowerBoundGraph);
bundleDeadEnds(this.upperBoundGraph);
collapseNonPhiEdges(this.lowerBoundGraph);
collapseNonPhiEdges(this.upperBoundGraph);
this.lowerBoundGraph.updateNodeEdges();
this.upperBoundGraph.updateNodeEdges();
}
private void addConstructionLength() {
for (final Integer array : this.lowerBoundGraph.getArrayLength().keySet()) {
final Integer tmp = array;
final SSAInstruction instruction = this.defUse.getDef(array);
if (instruction != null) {
instruction.visit(
new Visitor() {
@Override
public void visitNew(SSANewInstruction instruction) {
// We only support arrays with dimension 1
if (instruction.getNumberOfUses() == 1) {
final int constructionLength = instruction.getUse(0);
Integer arraysNode =
ArrayBoundsGraphBuilder.this.lowerBoundGraph.getArrayLength().get(tmp);
ArrayBoundsGraphBuilder.this.lowerBoundGraph.addEdge(
arraysNode, constructionLength);
arraysNode =
ArrayBoundsGraphBuilder.this.upperBoundGraph.getArrayLength().get(tmp);
ArrayBoundsGraphBuilder.this.upperBoundGraph.addEdge(
arraysNode, constructionLength);
ArrayBoundsGraphBuilder.this.addPossibleConstant(constructionLength);
}
}
});
}
}
}
/**
* Case 1: piRestrictor restricts the pi variable for upper/ lower bounds graph Given this code
* below, we want to create a hyper edge {piParent, piRestrictor} --> {piVar}.
*
* <p>If is op in {<, >} we now, that the distance from piRestrictor to piVar is +-1 as ( a
* < b ) <==> ( a <= b - 1), same with "<". To be more precise we introduce a
* helper node and add {piRestrictor} -- (-)1 --> {helper} {piParent, helper} --> {piVar}
*
* <p>Case 2: no restriction is given by the branch (i.e. the operator is not equal) {piParent}
* --> {piVar}
*
* <pre>if (piParent op piRestrictor) {piVar = piParent}</pre>
*/
private void addPiStructure(Integer piVar, Integer piParent, Integer piRestrictor, Operator op) {
Integer helper;
switch (op) {
case EQ:
this.upperBoundGraph.addPi(piVar, piParent, piRestrictor);
this.lowerBoundGraph.addPi(piVar, piParent, piRestrictor);
break;
case NE:
this.upperBoundGraph.addEdge(piParent, piVar);
this.lowerBoundGraph.addEdge(piParent, piVar);
break;
case LE: // piVar <= piRestrictor
this.upperBoundGraph.addPi(piVar, piParent, piRestrictor);
this.lowerBoundGraph.addEdge(piParent, piVar);
break;
case GE: // piVar >= piRestrictor
this.lowerBoundGraph.addPi(piVar, piParent, piRestrictor);
this.upperBoundGraph.addEdge(piParent, piVar);
break;
case LT: // piVar < piRestrictor
helper = this.upperBoundGraph.generateNewVar();
this.upperBoundGraph.addAdditionEdge(piRestrictor, helper, -1);
this.upperBoundGraph.addPi(piVar, piParent, helper);
this.lowerBoundGraph.addEdge(piParent, piVar);
break;
case GT: // piVar > piRestrictor
helper = this.lowerBoundGraph.generateNewVar();
this.lowerBoundGraph.addAdditionEdge(piRestrictor, helper, 1);
this.lowerBoundGraph.addPi(piVar, piParent, helper);
this.upperBoundGraph.addEdge(piParent, piVar);
break;
default:
throw new UnsupportedOperationException(String.format("unexpected operator %s", op));
}
}
private void addPossibleConstant(int handle) {
if (this.ir.getSymbolTable().isIntegerConstant(handle)) {
final int value = this.ir.getSymbolTable().getIntValue(handle);
this.lowerBoundGraph.addConstant(handle, value);
this.upperBoundGraph.addConstant(handle, value);
}
}
/**
* Connect all lose ends to the infinity node. See the description of {@link ArrayBoundsGraph} for
* why this is necessary.
*/
private static void bundleDeadEnds(ArrayBoundsGraph graph) {
final Set<HyperNode<Integer>> nodes = new HashSet<>(graph.getNodes().values());
for (final DirectedHyperEdge<Integer> edge : graph.getEdges()) {
for (final HyperNode<Integer> node : edge.getDestination()) {
nodes.remove(node);
}
}
for (final HyperNode<Integer> node : nodes) {
graph.markAsDeadEnd(node.getValue());
}
}
/**
* To make construction of the hyper-graph more easy, we always add single edges and fuse them
* into one hyper-edge. Where necessary (Everywhere but incoming edges of phi nodes.)
*/
private static void collapseNonPhiEdges(ArrayBoundsGraph graph) {
final Map<HyperNode<Integer>, DirectedHyperEdge<Integer>> inEdges = new HashMap<>();
final Set<DirectedHyperEdge<Integer>> edges = new HashSet<>(graph.getEdges());
for (final DirectedHyperEdge<Integer> edge : edges) {
assert edge.getDestination().size() == 1;
final HyperNode<Integer> node = edge.getDestination().iterator().next();
if (!graph.getPhis().contains(node.getValue())) {
if (inEdges.containsKey(node)) {
final DirectedHyperEdge<Integer> inEdge = inEdges.get(node);
assert inEdge.getWeight().equals(edge.getWeight());
for (final HyperNode<Integer> src : edge.getSource()) {
inEdge.getSource().add(src);
}
graph.getEdges().remove(edge);
} else {
inEdges.put(node, edge);
}
}
}
}
/** Discovers predecessors and adds them to the graph. */
private void discoverPredecessors(final ArrayDeque<Integer> todo, int handle) {
final SSAInstruction def = this.defUse.getDef(handle);
if (def == null) {
this.addPossibleConstant(handle);
} else {
def.visit(
new Visitor() {
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
ArrayBoundsGraphBuilder.this.lowerBoundGraph.markAsArrayLength(
instruction.getArrayRef(), instruction.getDef());
ArrayBoundsGraphBuilder.this.upperBoundGraph.markAsArrayLength(
instruction.getArrayRef(), instruction.getDef());
}
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {
if (instruction.getOperator() == ArrayBoundsGraphBuilder.this.SUB
|| instruction.getOperator() == ArrayBoundsGraphBuilder.this.ADD) {
final BinaryOpWithConstant op =
BinaryOpWithConstant.create(instruction, ArrayBoundsGraphBuilder.this.ir);
if (op != null) {
todo.push(op.getOtherVar());
int value = op.getConstantValue();
if (instruction.getOperator() == ArrayBoundsGraphBuilder.this.SUB) {
value = -value;
}
ArrayBoundsGraphBuilder.this.lowerBoundGraph.addAdditionEdge(
op.getOtherVar(), instruction.getDef(), value);
ArrayBoundsGraphBuilder.this.upperBoundGraph.addAdditionEdge(
op.getOtherVar(), instruction.getDef(), value);
}
}
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
int phi = instruction.getDef();
ArrayBoundsGraphBuilder.this.lowerBoundGraph.addPhi(phi);
ArrayBoundsGraphBuilder.this.upperBoundGraph.addPhi(phi);
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
int use = instruction.getUse(i);
todo.push(use);
ArrayBoundsGraphBuilder.this.lowerBoundGraph.addEdge(use, phi);
ArrayBoundsGraphBuilder.this.upperBoundGraph.addEdge(use, phi);
}
}
@Override
public void visitPi(SSAPiInstruction instruction) {
final SSAConditionalBranchInstruction branch =
(SSAConditionalBranchInstruction) instruction.getCause();
assert branch.getNumberOfUses() == 2;
final Integer piVar = instruction.getDef();
final Integer piParent = instruction.getUse(0);
final ConditionNormalizer cnd =
new ConditionNormalizer(
branch,
piParent,
ArrayBoundsGraphBuilder.this.isBranchTaken(instruction, branch));
final Integer piRestrictor = cnd.getRhs();
todo.push(piParent);
todo.push(piRestrictor);
ArrayBoundsGraphBuilder.this.addPiStructure(
piVar, piParent, piRestrictor, cnd.getOp());
}
});
}
}
private void exploreIr() {
final Set<Integer> variablesUsedAsIndex = new HashSet<>();
for (final Set<Integer> variables : this.lowerBoundGraph.getArrayAccess().values()) {
variablesUsedAsIndex.addAll(variables);
}
for (final Integer variable : variablesUsedAsIndex) {
this.startDFS(variable);
}
}
private void findArrayAccess() {
this.ir.visitNormalInstructions(
new Visitor() {
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
ArrayBoundsGraphBuilder.this.lowerBoundGraph.markAsArrayAccess(
instruction.getArrayRef(), instruction.getIndex());
ArrayBoundsGraphBuilder.this.upperBoundGraph.markAsArrayAccess(
instruction.getArrayRef(), instruction.getIndex());
ArrayBoundsGraphBuilder.this.arrayReferenceInstructions.add(instruction);
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
ArrayBoundsGraphBuilder.this.lowerBoundGraph.markAsArrayAccess(
instruction.getArrayRef(), instruction.getIndex());
ArrayBoundsGraphBuilder.this.upperBoundGraph.markAsArrayAccess(
instruction.getArrayRef(), instruction.getIndex());
ArrayBoundsGraphBuilder.this.arrayReferenceInstructions.add(instruction);
}
});
}
public Set<SSAArrayReferenceInstruction> getArrayReferenceInstructions() {
return this.arrayReferenceInstructions;
}
public ArrayBoundsGraph getLowerBoundGraph() {
return this.lowerBoundGraph;
}
public ArrayBoundsGraph getUpperBoundGraph() {
return this.upperBoundGraph;
}
private boolean isBranchTaken(SSAPiInstruction pi, SSAConditionalBranchInstruction cnd) {
final BasicBlock branchTargetBlock =
this.ir.getControlFlowGraph().getBlockForInstruction(cnd.getTarget());
return branchTargetBlock.getNumber() == pi.getSuccessor();
}
/** Explore the DefUse-Chain with depth-first-search to add constraints to the given variable. */
private void startDFS(int index) {
final ArrayDeque<Integer> todo = new ArrayDeque<>();
todo.push(index);
while (!todo.isEmpty()) {
final int next = todo.pop();
if (this.foundVariables.add(next)) {
this.lowerBoundGraph.addNode(next);
this.upperBoundGraph.addNode(next);
this.discoverPredecessors(todo, next);
}
}
}
}
| 13,865
| 36.885246
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/ArrayOutOfBoundsAnalysis.java
|
package com.ibm.wala.analysis.arraybounds;
import com.ibm.wala.analysis.arraybounds.hypergraph.HyperNode;
import com.ibm.wala.analysis.arraybounds.hypergraph.algorithms.ShortestPath;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.NormalOrder;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.ReverseOrder;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
import com.ibm.wala.core.util.ssa.InstructionByIIndexMap;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAArrayReferenceInstruction;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* The array out of bounds analysis uses the inequality graph as described in [1]. And a shortest
* path computation as suggested ibid. as possible solver for the inequality graph.
*
* <p>[1] Bodík, Rastislav, Rajiv Gupta, and Vivek Sarkar. "ABCD: eliminating array bounds checks on
* demand." ACM SIGPLAN Notices. Vol. 35. No. 5. ACM, 2000.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ArrayOutOfBoundsAnalysis {
public enum UnnecessaryCheck {
NONE,
UPPER,
LOWER,
BOTH;
public UnnecessaryCheck union(UnnecessaryCheck other) {
final Set<UnnecessaryCheck> set = new HashSet<>();
set.add(this);
set.add(other);
set.remove(NONE);
if (set.contains(BOTH) || (set.contains(UPPER) && set.contains(LOWER))) {
return BOTH;
} else if (set.size() == 0) {
return NONE;
} else if (set.size() == 1) {
return set.iterator().next();
} else {
throw new RuntimeException(
"Case that should not happen, this method is implemented wrong.");
}
}
}
private ArrayBoundsGraph lowerBoundGraph;
private ArrayBoundsGraph upperBoundGraph;
/** List of variables, that are used for array access and if they are neccessary */
private final Map<SSAArrayReferenceInstruction, UnnecessaryCheck> boundsCheckUnnecessary;
/**
* Create and perform the array out of bounds analysis.
*
* <p>Make sure, the given IR was created with pi nodes for each variable, that is part of a
* branch instruction! Otherwise the results will be poor.
*/
public ArrayOutOfBoundsAnalysis(IR ir) {
this.boundsCheckUnnecessary = new InstructionByIIndexMap<>();
this.buildInequalityGraphs(ir);
this.computeLowerBound();
this.computeUpperBounds();
this.lowerBoundGraph = null;
this.upperBoundGraph = null;
}
private void addUnnecessaryCheck(
SSAArrayReferenceInstruction instruction, UnnecessaryCheck checkToAdd) {
final UnnecessaryCheck oldCheck = this.boundsCheckUnnecessary.get(instruction);
final UnnecessaryCheck newCheck = oldCheck.union(checkToAdd);
this.boundsCheckUnnecessary.put(instruction, newCheck);
}
private void buildInequalityGraphs(IR ir) {
ArrayBoundsGraphBuilder builder = new ArrayBoundsGraphBuilder(ir);
this.lowerBoundGraph = builder.getLowerBoundGraph();
this.upperBoundGraph = builder.getUpperBoundGraph();
for (final SSAArrayReferenceInstruction instruction : builder.getArrayReferenceInstructions()) {
this.boundsCheckUnnecessary.put(instruction, UnnecessaryCheck.NONE);
}
builder = null;
}
/** compute lower bound */
private void computeLowerBound() {
final HyperNode<Integer> zero = this.lowerBoundGraph.getNodes().get(ArrayBoundsGraph.ZERO);
ShortestPath.compute(this.lowerBoundGraph, zero, new NormalOrder());
for (final SSAArrayReferenceInstruction instruction : this.boundsCheckUnnecessary.keySet()) {
Weight weight = this.lowerBoundGraph.getVariableWeight(instruction.getIndex());
if (weight.getType() == Weight.Type.NUMBER && weight.getNumber() >= 0) {
this.addUnnecessaryCheck(instruction, UnnecessaryCheck.LOWER);
}
}
}
/** compute upper bound for each array */
private void computeUpperBounds() {
final Map<Integer, Integer> arrayLengths = this.upperBoundGraph.getArrayLength();
for (final Map.Entry<Integer, Integer> entry : arrayLengths.entrySet()) {
final HyperNode<Integer> arrayNode = this.upperBoundGraph.getNodes().get(entry.getValue());
ShortestPath.compute(this.upperBoundGraph, arrayNode, new ReverseOrder());
for (final SSAArrayReferenceInstruction instruction : this.boundsCheckUnnecessary.keySet()) {
if (instruction.getArrayRef() == entry.getKey()) {
Weight weight = this.upperBoundGraph.getVariableWeight(instruction.getIndex());
if (weight.getType() == Weight.Type.NUMBER && weight.getNumber() <= -1) {
this.addUnnecessaryCheck(instruction, UnnecessaryCheck.UPPER);
}
}
}
}
}
/**
* @return for each array reference instruction (load or store), if both, lower bound, upper bound
* or no check is unnecessary.
*/
public Map<SSAArrayReferenceInstruction, UnnecessaryCheck> getBoundsCheckNecessary() {
return this.boundsCheckUnnecessary;
}
}
| 4,997
| 36.578947
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/BinaryOpWithConstant.java
|
package com.ibm.wala.analysis.arraybounds;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.IOperator;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.Operator;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
/**
* Normalizes a binary operation with a constant by providing direct access to assigned = other op
* constant.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class BinaryOpWithConstant {
/** @return normalized BinaryOpWithConstant or null, if normalization was not successful. */
public static BinaryOpWithConstant create(SSABinaryOpInstruction instruction, IR ir) {
BinaryOpWithConstant result = null;
if (instruction.mayBeIntegerOp()) {
assert instruction.getNumberOfUses() == 2;
Integer other = null;
Integer value = null;
int constantPos = -1;
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
final int constant = instruction.getUse(i);
if (ir.getSymbolTable().isIntegerConstant(constant)) {
other = instruction.getUse((i + 1) % 2);
value = ir.getSymbolTable().getIntValue(constant);
constantPos = i;
}
}
final IOperator op = instruction.getOperator();
if (constantPos != -1) {
if (op == Operator.ADD || op == Operator.SUB && constantPos == 1) {
result = new BinaryOpWithConstant(op, other, value, instruction.getDef());
}
}
}
return result;
}
private final IOperator op;
private final Integer other;
private final Integer value;
private final Integer assigned;
private BinaryOpWithConstant(IOperator op, Integer other, Integer value, Integer assigned) {
super();
this.op = op;
this.other = other;
this.value = value;
this.assigned = assigned;
}
public Integer getAssignedVar() {
return this.assigned;
}
public Integer getConstantValue() {
return this.value;
}
public IOperator getOp() {
return this.op;
}
public Integer getOtherVar() {
return this.other;
}
}
| 2,086
| 26.103896
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/ConditionNormalizer.java
|
package com.ibm.wala.analysis.arraybounds;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction.Operator;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
/**
* ConditionNormalizer normalizes a branch condition. See Constructor for more information.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ConditionNormalizer {
private final int lhs;
private int rhs;
private Operator op;
/**
* Creates a normalization of cnd such that lhs op rhs is true.
*
* <p>Normalization means, that the given variable lhs, will be on the left hand side of the
* comparison, also if the branch is not taken, the operation needs to be negated.
*
* <p>p.a. the condition is !(rhs >= lhs), it will be normalized to lhs > rhs
*
* @param cnd condition to normalize
* @param lhs variable, that should be on the left hand side
* @param branchIsTaken if the condition is for the branching case or not
*/
public ConditionNormalizer(SSAConditionalBranchInstruction cnd, int lhs, boolean branchIsTaken) {
this.lhs = lhs;
if (cnd.getNumberOfUses() != 2) {
throw new IllegalArgumentException("Condition uses not exactly two variables.");
}
this.op = (Operator) cnd.getOperator();
for (int i = 0; i < cnd.getNumberOfUses(); i++) {
final int var = cnd.getUse(i);
if ((var != lhs)) {
if (cnd.getUse((i + 1) % 2) != lhs) {
throw new IllegalArgumentException("Lhs not contained in condition.");
}
if (i == 0) {
// make sure the other is lhs
this.op = swapOperator(this.op);
}
if (!branchIsTaken) {
this.op = negateOperator(this.op);
}
this.rhs = var;
}
}
}
public int getLhs() {
return this.lhs;
}
public Operator getOp() {
return this.op;
}
public int getRhs() {
return this.rhs;
}
private static Operator negateOperator(Operator op) {
switch (op) {
case EQ:
return Operator.NE;
case NE:
return Operator.EQ;
case LT:
return Operator.GE;
case GE:
return Operator.LT;
case GT:
return Operator.LE;
case LE:
return Operator.GT;
default:
throw new RuntimeException("Programming Error: Got unknown operator.");
}
}
private static Operator swapOperator(Operator op) {
switch (op) {
case EQ:
case NE:
return op;
case LT:
return Operator.GT;
case GE:
return Operator.LE;
case GT:
return Operator.LT;
case LE:
return Operator.GE;
default:
throw new RuntimeException("Programming Error: Got unknown operator.");
}
}
}
| 2,759
| 25.538462
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/DirectedHyperEdge.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.edgeweights.EdgeWeight;
import java.util.HashSet;
import java.util.Set;
/**
* A DirectedHyperEdge is an edge of a {@link DirectedHyperGraph}.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
* @param <T> Type used in HyperNodes (HyperNode<T>)
*/
public class DirectedHyperEdge<T> {
/** Contains all destinations of this HyperEdge */
private final Set<HyperNode<T>> tail;
/** Contains multiple sources of this HyperEdge */
private final Set<HyperNode<T>> head;
private EdgeWeight weight;
public DirectedHyperEdge() {
this.tail = new HashSet<>();
this.head = new HashSet<>();
}
public Set<HyperNode<T>> getDestination() {
return this.head;
}
public Set<HyperNode<T>> getSource() {
return this.tail;
}
public EdgeWeight getWeight() {
return this.weight;
}
public void setWeight(EdgeWeight weight) {
this.weight = weight;
}
}
| 1,012
| 23.119048
| 82
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/DirectedHyperGraph.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Implementation of a directed hyper graph. In a hyper graph an edge can have more than one head
* and more than one tail.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class DirectedHyperGraph<T> {
private final Map<T, HyperNode<T>> nodes;
private final Set<DirectedHyperEdge<T>> edges;
public DirectedHyperGraph() {
this.nodes = new HashMap<>();
this.edges = new HashSet<>();
}
public Set<DirectedHyperEdge<T>> getEdges() {
return this.edges;
}
public Map<T, HyperNode<T>> getNodes() {
return this.nodes;
}
/** Resets the weight of all nodes. */
public void reset() {
for (final HyperNode<T> node : this.getNodes().values()) {
node.setWeight(Weight.NOT_SET);
node.setNewWeight(Weight.NOT_SET);
}
}
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
for (final DirectedHyperEdge<T> edge : this.getEdges()) {
buffer.append(edge.getSource());
buffer.append(" -- ");
buffer.append(edge.getWeight());
buffer.append(" --> ");
buffer.append(edge.getDestination());
buffer.append('\n');
}
return buffer.toString();
}
/**
* The outdEdges of a node may not have been set on construction. Use this method to set them
* based on the edges of this HyperGraph.
*/
public void updateNodeEdges() {
for (final HyperNode<T> node : this.getNodes().values()) {
node.setOutEdges(new HashSet<>());
node.setInEdges(new HashSet<>());
}
for (final DirectedHyperEdge<T> edge : this.edges) {
for (final HyperNode<T> node : edge.getSource()) {
node.getOutEdges().add(edge);
}
for (final HyperNode<T> node : edge.getDestination()) {
node.getInEdges().add(edge);
}
}
}
}
| 2,030
| 26.445946
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/HyperNode.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
import java.util.HashSet;
import java.util.Set;
/**
* A HyperNode is a node of a {@link DirectedHyperGraph}.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class HyperNode<T> {
private Weight weight;
private Weight newWeight;
/**
* Set of edges, which have this node as source, can be set automatically with {@link
* DirectedHyperGraph#updateNodeEdges()}
*/
private Set<DirectedHyperEdge<T>> outEdges;
/**
* Set of edges, which have this node as source, can be set automatically with {@link
* DirectedHyperGraph#updateNodeEdges()}
*/
private Set<DirectedHyperEdge<T>> inEdges;
private T value;
public HyperNode(T value) {
this.value = value;
this.outEdges = new HashSet<>();
this.weight = Weight.NOT_SET;
this.newWeight = Weight.NOT_SET;
}
public Set<DirectedHyperEdge<T>> getInEdges() {
return this.inEdges;
}
public Weight getNewWeight() {
return this.newWeight;
}
public Set<DirectedHyperEdge<T>> getOutEdges() {
return this.outEdges;
}
public T getValue() {
return this.value;
}
public Weight getWeight() {
return this.weight;
}
public void setInEdges(Set<DirectedHyperEdge<T>> inEdges) {
this.inEdges = inEdges;
}
public void setNewWeight(Weight newWeight) {
this.newWeight = newWeight;
}
public void setOutEdges(Set<DirectedHyperEdge<T>> outEdges) {
this.outEdges = outEdges;
}
public void setValue(T value) {
this.value = value;
}
public void setWeight(Weight weight) {
this.weight = weight;
}
@Override
public String toString() {
if (this.weight == Weight.NOT_SET) {
return this.value.toString();
} else {
return this.value.toString() + ": " + this.weight;
}
}
}
| 1,890
| 21.247059
| 87
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/SoftFinalHyperNode.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.analysis.arraybounds.hypergraph;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
public class SoftFinalHyperNode<T> extends HyperNode<T> {
public SoftFinalHyperNode(T value) {
super(value);
}
@Override
public void setWeight(Weight weight) {
if (weight.equals(Weight.NOT_SET) || this.getWeight().equals(Weight.NOT_SET)) {
super.setWeight(weight);
}
}
}
| 792
| 27.321429
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/package-info.java
|
/**
* This package contains a generic implementation of directed hypergraphs. The implementation is
* optimized for shortest path search, with {@link
* com.ibm.wala.analysis.arraybounds.hypergraph.algorithms.ShortestPath#compute(com.ibm.wala.analysis.arraybounds.hypergraph.DirectedHyperGraph,
* com.ibm.wala.analysis.arraybounds.hypergraph.HyperNode, java.util.Comparator) ShortestPath}
*/
package com.ibm.wala.analysis.arraybounds.hypergraph;
| 450
| 55.375
| 144
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/algorithms/ShortestPath.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph.algorithms;
import com.ibm.wala.analysis.arraybounds.hypergraph.DirectedHyperEdge;
import com.ibm.wala.analysis.arraybounds.hypergraph.DirectedHyperGraph;
import com.ibm.wala.analysis.arraybounds.hypergraph.HyperNode;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight.Type;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.edgeweights.EdgeWeight;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
/**
* @author Stephan Gocht {@code <stephan@gobro.de>}
* @param <T> NodeValueType
* @see ShortestPath#compute(DirectedHyperGraph, HyperNode, Comparator)
*/
public class ShortestPath<T> {
/**
* Computes all shortest paths from source. The result is stored in {@link HyperNode#getWeight()}.
*
* <p>This is using a variation of Bellman-Ford for hyper graphs.
*
* @param comparator defines order on weights.
*/
public static <NodeValueType> void compute(
DirectedHyperGraph<NodeValueType> graph,
HyperNode<NodeValueType> source,
Comparator<Weight> comparator) {
graph.reset();
source.setWeight(Weight.ZERO);
new ShortestPath<>(graph, comparator);
}
private Set<DirectedHyperEdge<T>> updatedEdges;
private final Comparator<Weight> comparator;
private final DirectedHyperGraph<T> graph;
private boolean setUnlimitedOnChange = false;
private boolean hasNegativeCycle = false;
/**
* @param graph Source nodes for shortest path computation should be set to 0, other nodes should
* be set to {@link Weight#NOT_SET}.
* @param comparator defines order on weights.
*/
private ShortestPath(DirectedHyperGraph<T> graph, Comparator<Weight> comparator) {
this.comparator = comparator;
this.graph = graph;
this.computeShortestPaths();
this.hasNegativeCycle = (this.updatedEdges.size() > 0);
if (this.hasNegativeCycle) {
// trigger, that changing values are set to infty in writeChanges:
this.setUnlimitedOnChange = true;
// we need to propagate negative cycle to all connected nodes
this.computeShortestPaths();
}
}
private void computeShortestPaths() {
this.updatedEdges = this.graph.getEdges();
final int nodeCount = this.graph.getNodes().size();
for (int i = 0; i < nodeCount - 1; i++) {
this.updateAllEdges();
if (this.updatedEdges.size() == 0) {
break;
}
}
}
/** @return weight > otherWeight */
private boolean greaterThen(Weight weight, Weight otherWeight) {
return otherWeight.getType() == Type.NOT_SET
|| this.comparator.compare(weight, otherWeight) > 0;
}
/** @return weight < otherWeight */
private boolean lessThen(Weight weight, Weight otherWeight) {
return otherWeight.getType() == Type.NOT_SET
|| this.comparator.compare(weight, otherWeight) < 0;
}
/**
* Maximum of source weights, modified by the value of the edge. Note that every weight is larger
* than {@link Weight#NOT_SET} for max computation. This allows distances to propagate, even if
* not all nodes are connected to the source of the shortest path computation. Otherwise (source,
* other)->(sink) would not have a path from source to sink.
*
* @return max{edgeValue.newValue(sourceWeight) | sourceWeight \in edge.getSources()}
*/
private Weight maxOfSources(final DirectedHyperEdge<T> edge) {
final EdgeWeight edgeValue = edge.getWeight();
Weight newWeight = Weight.NOT_SET;
for (final HyperNode<T> node : edge.getSource()) {
final Weight nodeWeight = node.getWeight();
if (nodeWeight.getType() != Type.NOT_SET) {
final Weight temp = edgeValue.newValue(nodeWeight);
if (this.greaterThen(temp, newWeight)) {
newWeight = temp;
}
} else {
newWeight = Weight.NOT_SET;
break;
}
}
return newWeight;
}
/**
* We do not need to iterate all edges, but edges of which the source weight was changed, other
* edges will not lead to a change of the destination weight. For correct updating of the
* destination weight, we need to consider all incoming edges. (The minimum of in edges is
* computed per round, not global - see {@link
* ShortestPath#updateDestinationsWithMin(DirectedHyperEdge, Weight)} )
*
* @return A set of edges, that may lead to changes of weights.
*/
private HashSet<DirectedHyperEdge<T>> selectEdgesToIterate() {
final HashSet<DirectedHyperEdge<T>> edgesToIterate = new HashSet<>();
for (final DirectedHyperEdge<T> edge : this.updatedEdges) {
for (final HyperNode<T> node : edge.getDestination()) {
edgesToIterate.addAll(node.getInEdges());
}
}
return edgesToIterate;
}
private void updateAllEdges() {
for (final DirectedHyperEdge<T> edge : this.selectEdgesToIterate()) {
final Weight maxOfSources = this.maxOfSources(edge);
if (maxOfSources.getType() != Type.NOT_SET) {
this.updateDestinationsWithMin(edge, maxOfSources);
}
}
this.writeChanges();
}
/**
* Updates Nodes with the minimum of all incoming edges. The minimum is computed over the minimum
* of all edges that were processed in this round ( {@link ShortestPath#selectEdgesToIterate()}).
*
* <p>This is necessary for the feature described in {@link
* ShortestPath#maxOfSources(DirectedHyperEdge)} to work properly: The result of different rounds
* is not always monotonous, p.a.:
*
* <pre>
* (n1, n2)->(n3)
* Round 1: n1 = unset, n2 = -3 -> n3 = max(unset,-3) = -3
* Round 2: n1 = 1, n2 = -3 -> n3 = max(1,-3) = 1
* </pre>
*
* Would we compute the minimum of n3 over all rounds, it would be -3, but 1 is correct.
*
* <p>Note: that every weight is smaller than {@link Weight#NOT_SET} for min computation. This
* allows distances to propagate, even if not all nodes are connected to the source of the
* shortest path computation. Otherwise (source)->(sink), (other)->(sink), would not have a path
* from source to sink.
*/
private void updateDestinationsWithMin(final DirectedHyperEdge<T> edge, Weight newWeight) {
if (!newWeight.equals(Weight.NOT_SET)) {
for (final HyperNode<T> node : edge.getDestination()) {
if (this.lessThen(newWeight, node.getNewWeight())) {
node.setNewWeight(newWeight);
}
}
}
}
/**
* This method is necessary, as the min is updated per round. (See {@link
* ShortestPath#updateDestinationsWithMin(DirectedHyperEdge, Weight)} )
*/
private void writeChanges() {
final HashSet<DirectedHyperEdge<T>> newUpdatedEdges = new HashSet<>();
for (final HyperNode<T> node : this.graph.getNodes().values()) {
final Weight oldWeight = node.getWeight();
final Weight newWeight = node.getNewWeight();
if (!newWeight.equals(Weight.NOT_SET) && !oldWeight.equals(newWeight)) {
// node weight has changed, so out edges have to be updated next
// round:
newUpdatedEdges.addAll(node.getOutEdges());
if (this.setUnlimitedOnChange) {
node.setWeight(Weight.UNLIMITED);
} else {
node.setWeight(node.getNewWeight());
}
}
node.setNewWeight(Weight.NOT_SET);
}
this.updatedEdges = newUpdatedEdges;
}
}
| 7,415
| 35.53202
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/weight/NormalOrder.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph.weight;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight.Type;
import java.util.Comparator;
/**
* Defines a normal Order on Weight: unlimited < ... < -1 < 0 < 1 < ... not_set is
* not comparable
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class NormalOrder implements Comparator<Weight> {
@Override
public int compare(Weight o1, Weight o2) {
int result = 0;
if (o1.getType() == Type.NOT_SET || o2.getType() == Type.NOT_SET) {
throw new IllegalArgumentException("Tried to compare weights, which are not set yet.");
}
if (o1.getType() == o2.getType()) {
if (o1.getType() == Type.NUMBER) {
result = o1.getNumber() - o2.getNumber();
} else {
result = 0;
}
} else {
if (o1.getType() == Type.UNLIMITED) {
result = -1;
} else if (o2.getType() == Type.UNLIMITED) {
result = 1;
} else {
throw new IllegalArgumentException("Programming error, expected no cases to be left.");
}
}
return result;
}
}
| 1,126
| 26.487805
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/weight/ReverseOrder.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph.weight;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight.Type;
import java.util.Comparator;
/**
* Defines a reverse Order on Weight: ... > 1 > 0 > -1 > ... > unlimited not_set is
* not comparable
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ReverseOrder implements Comparator<Weight> {
private final NormalOrder normalOrder;
public ReverseOrder() {
this.normalOrder = new NormalOrder();
}
@Override
public int compare(Weight o1, Weight o2) {
int result;
if (o1.getType() == Type.UNLIMITED) {
result = -1;
} else if (o2.getType() == Type.UNLIMITED) {
result = 1;
} else {
result = -this.normalOrder.compare(o1, o2);
}
return result;
}
}
| 814
| 22.970588
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/weight/Weight.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph.weight;
/**
* A weight may be not set, a number or unlimited, note that the meaning of unlimited is given by
* the chosen order (see {@link NormalOrder} and {@link ReverseOrder}).
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class Weight {
public enum Type {
NUMBER,
NOT_SET,
UNLIMITED
}
public static final Weight UNLIMITED = new Weight(Type.UNLIMITED, 0);
public static final Weight NOT_SET = new Weight(Type.NOT_SET, 0);
public static final Weight ZERO = new Weight(Type.NUMBER, 0);
private final Type type;
private final int number;
public Weight(int number) {
this.type = Type.NUMBER;
this.number = number;
}
public Weight(Type type, int number) {
super();
this.type = type;
this.number = number;
}
/**
* Returns this + other. If this is not Number this will be returned, if other is not number other
* will be returned
*
* @return this + other
*/
public Weight add(Weight other) {
Weight result = null;
if (this.getType() == Type.NUMBER) {
if (other.getType() == Type.NUMBER) {
result = new Weight(Type.NUMBER, this.getNumber() + other.getNumber());
} else {
result = other;
}
} else {
result = this;
}
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final Weight other = (Weight) obj;
if (this.number != other.number) {
return false;
}
if (this.type != other.type) {
return false;
}
return true;
}
public int getNumber() {
return this.number;
}
public Type getType() {
return this.type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.number;
result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
return result;
}
@Override
public String toString() {
if (this.type == Type.NUMBER) {
return Integer.toString(this.number);
} else {
if (this.type == Type.NOT_SET) {
return "NOT_SET";
} else if (this.type == Type.UNLIMITED) {
return "UNLIMITED";
} else {
return "Type: " + this.type;
}
}
}
}
| 2,438
| 21.376147
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/weight/edgeweights/AdditiveEdgeWeight.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph.weight.edgeweights;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
/**
* EdgeWeight that adds a specific value.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class AdditiveEdgeWeight implements EdgeWeight {
private final Weight value;
public AdditiveEdgeWeight(Weight value) {
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final AdditiveEdgeWeight other = (AdditiveEdgeWeight) obj;
if (this.value == null) {
if (other.value != null) {
return false;
}
} else if (!this.value.equals(other.value)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.value == null) ? 0 : this.value.hashCode());
return result;
}
@Override
public Weight newValue(Weight weight) {
return weight.add(this.value);
}
@Override
public String toString() {
return this.value.toString();
}
}
| 1,244
| 20.842105
| 81
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/arraybounds/hypergraph/weight/edgeweights/EdgeWeight.java
|
package com.ibm.wala.analysis.arraybounds.hypergraph.weight.edgeweights;
import com.ibm.wala.analysis.arraybounds.hypergraph.weight.Weight;
/**
* The weight of an edge can produce a new value for the tail nodes given the head nodes.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public interface EdgeWeight {
Weight newValue(Weight weight);
}
| 361
| 26.846154
| 89
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/CGIntraproceduralExceptionAnalysis.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.analysis.exceptionanalysis;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.InterproceduralExceptionFilter;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.TypeReference;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* Wrapper to store multiple intraprocedural analysis for a call graph.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class CGIntraproceduralExceptionAnalysis {
private final Map<CGNode, IntraproceduralExceptionAnalysis> analysis;
private final Set<TypeReference> exceptions;
private final CallGraph callGraph;
public CGIntraproceduralExceptionAnalysis(
CallGraph cg,
PointerAnalysis<InstanceKey> pointerAnalysis,
ClassHierarchy cha,
InterproceduralExceptionFilter<SSAInstruction> filter) {
this.callGraph = cg;
this.exceptions = new LinkedHashSet<>();
this.analysis = new LinkedHashMap<>();
for (CGNode node : cg) {
if (node.getIR() == null || node.getIR().isEmptyIR()) {
analysis.put(node, IntraproceduralExceptionAnalysis.newDummy());
} else {
IntraproceduralExceptionAnalysis intraEA;
intraEA =
new IntraproceduralExceptionAnalysis(
node, filter.getFilter(node), cha, pointerAnalysis);
analysis.put(node, intraEA);
exceptions.addAll(intraEA.getExceptions());
exceptions.addAll(intraEA.getPossiblyCaughtExceptions());
}
}
}
/** @return IntraproceduralExceptionAnalysis for given node. */
public IntraproceduralExceptionAnalysis getAnalysis(CGNode node) {
if (!callGraph.containsNode(node)) {
throw new IllegalArgumentException(
"The given CG node has to be part " + "of the call graph given during construction.");
}
IntraproceduralExceptionAnalysis result = analysis.get(node);
if (result == null) {
throw new RuntimeException("Internal Error: No result for the given node.");
}
return result;
}
/**
* Return a set of all Exceptions, which might occur within the given call graph.
*
* @return all exceptions, which might occur.
*/
public Set<TypeReference> getExceptions() {
return exceptions;
}
}
| 2,906
| 34.45122
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/Exception2BitvectorTransformer.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.analysis.exceptionanalysis;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.ObjectArrayMapping;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.HashSet;
import java.util.Set;
public class Exception2BitvectorTransformer {
private OrdinalSetMapping<TypeReference> values;
public OrdinalSetMapping<TypeReference> getValues() {
return values;
}
public Exception2BitvectorTransformer(Set<TypeReference> exceptions) {
createValues(exceptions);
for (TypeReference exception : exceptions) {
BitVector bv = new BitVector(values.getSize());
bv.set(values.getMappedIndex(exception));
}
}
private void createValues(Set<TypeReference> exceptions) {
TypeReference[] exceptionsArray = new TypeReference[exceptions.size()];
exceptions.toArray(exceptionsArray);
values = new ObjectArrayMapping<>(exceptionsArray);
}
public BitVector computeBitVector(Set<TypeReference> exceptions) {
BitVector result = new BitVector(values.getSize());
for (TypeReference exception : exceptions) {
int pos = values.getMappedIndex(exception);
if (pos != -1) {
result.set(pos);
} else {
throw new IllegalArgumentException(
"Got exception I don't know about,"
+ "make sure only to use exceptions given to the constructor ");
}
}
return result;
}
public Set<TypeReference> computeExceptions(BitVector bitVector) {
assert bitVector.length() == values.getSize();
Set<TypeReference> result = new HashSet<>();
for (int i = 0; i < bitVector.length(); i++) {
if (bitVector.get(i)) {
result.add(values.getMappedObject(i));
}
}
return result;
}
public Set<TypeReference> computeExceptions(BitVectorVariable bitVector) {
Set<TypeReference> result = new HashSet<>();
for (int i = 0; i < values.getSize(); i++) {
if (bitVector.get(i)) {
result.add(values.getMappedObject(i));
}
}
return result;
}
}
| 2,513
| 31.230769
| 80
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/ExceptionAnalysis.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.analysis.exceptionanalysis;
import com.ibm.wala.analysis.arraybounds.ArrayOutOfBoundsAnalysis;
import com.ibm.wala.analysis.nullpointer.IntraproceduralNullPointerAnalysis;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.dataflow.graph.BitVectorFramework;
import com.ibm.wala.dataflow.graph.BitVectorSolver;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionMatcher;
import com.ibm.wala.ipa.cfg.exceptionpruning.filter.DummyFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.IgnoreExceptionsInterFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.interprocedural.InterproceduralExceptionFilter;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.Visitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.impl.InvertedGraph;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
/**
* This class analyzes the exceptional control flow. Use {@link ExceptionAnalysis2EdgeFilter} to
* remove infeasible edges.
*
* <p>In a first step an intraprocedural analysis is performed, to collect the thrown exceptions and
* collect the exceptions caught, per invoke instruction. The results of the intraprocedural
* analysis are used for a GenKill data flow analysis on the call graph. (Each node generates
* intraprocedural thrown exceptions and along invoke edges, caught exceptions are removed.)
*
* <p>Notice: Only exceptions, which are part of the analysis scope are considered.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ExceptionAnalysis {
private final BitVectorSolver<CGNode> solver;
private final Exception2BitvectorTransformer transformer;
private final InterproceduralExceptionFilter<SSAInstruction> filter;
private final ClassHierarchy cha;
private final CGIntraproceduralExceptionAnalysis intraResult;
private final CallGraph cg;
private boolean isSolved = false;
public ExceptionAnalysis(
CallGraph callgraph, PointerAnalysis<InstanceKey> pointerAnalysis, ClassHierarchy cha) {
this(callgraph, pointerAnalysis, cha, null);
}
/**
* @param filter a filter to include results of other analysis (like {@link
* ArrayOutOfBoundsAnalysis} or {@link IntraproceduralNullPointerAnalysis}) or to ignore
* exceptions completely.
*/
public ExceptionAnalysis(
CallGraph callgraph,
PointerAnalysis<InstanceKey> pointerAnalysis,
ClassHierarchy cha,
InterproceduralExceptionFilter<SSAInstruction> filter) {
this.cha = cha;
this.cg = callgraph;
this.filter =
Objects.requireNonNullElseGet(
filter, () -> new IgnoreExceptionsInterFilter<>(new DummyFilter<>()));
intraResult =
new CGIntraproceduralExceptionAnalysis(callgraph, pointerAnalysis, cha, this.filter);
transformer = new Exception2BitvectorTransformer(intraResult.getExceptions());
ExceptionTransferFunctionProvider transferFunctionProvider =
new ExceptionTransferFunctionProvider(intraResult, callgraph, transformer);
Graph<CGNode> graph = new InvertedGraph<>(callgraph);
BitVectorFramework<CGNode, TypeReference> problem =
new BitVectorFramework<>(graph, transferFunctionProvider, transformer.getValues());
solver = new InitializedBitVectorSolver(problem);
solver.initForFirstSolve();
}
public void solve() {
try {
solver.solve(null);
} catch (CancelException e) {
throw new RuntimeException(
"Internal Error: Got Cancel Exception, " + "but didn't use Progressmonitor!", e);
}
this.isSolved = true;
}
public void solve(IProgressMonitor monitor) throws CancelException {
solver.solve(monitor);
this.isSolved = true;
}
public boolean catchesException(
CGNode node, ISSABasicBlock throwBlock, ISSABasicBlock catchBlock) {
if (!isSolved) {
throw new IllegalStateException("You need to use .solve() first!");
}
if (node.getIR().getControlFlowGraph().getExceptionalSuccessors(throwBlock).contains(catchBlock)
&& catchBlock.isCatchBlock()) {
SSAInstruction instruction =
IntraproceduralExceptionAnalysis.getThrowingInstruction(throwBlock);
assert instruction != null;
Iterator<TypeReference> caughtExceptions = catchBlock.getCaughtExceptionTypes();
Set<TypeReference> thrownExceptions = this.getExceptions(node, instruction);
boolean isCaught = false;
while (caughtExceptions.hasNext() && !isCaught) {
TypeReference caughtException = caughtExceptions.next();
IClass caughtExceptionClass = cha.lookupClass(caughtException);
if (caughtExceptionClass == null) {
// for now, assume it is not caught
continue;
}
for (TypeReference thrownException : thrownExceptions) {
IClass thrownExceptionClass = cha.lookupClass(thrownException);
if (thrownExceptionClass == null) {
// for now, assume it is not caught
continue;
}
isCaught |= cha.isAssignableFrom(caughtExceptionClass, thrownExceptionClass);
if (isCaught) break;
}
}
return isCaught;
} else {
return false;
}
}
/** @return if the block has uncaught exceptions */
public boolean hasUncaughtExceptions(CGNode node, ISSABasicBlock block) {
if (!isSolved) {
throw new IllegalStateException("You need to use .solve() first!");
}
SSAInstruction instruction = IntraproceduralExceptionAnalysis.getThrowingInstruction(block);
if (instruction != null) {
Set<TypeReference> exceptions = this.getExceptions(node, instruction);
boolean allCaught = true;
for (TypeReference thrownException : exceptions) {
boolean isCaught = false;
for (ISSABasicBlock catchBlock :
node.getIR().getControlFlowGraph().getExceptionalSuccessors(block)) {
Iterator<TypeReference> caughtExceptions = catchBlock.getCaughtExceptionTypes();
while (caughtExceptions.hasNext() && !isCaught) {
TypeReference caughtException = caughtExceptions.next();
isCaught |=
cha.isAssignableFrom(
cha.lookupClass(caughtException), cha.lookupClass(thrownException));
if (isCaught) break;
}
if (isCaught) break;
}
allCaught &= isCaught;
if (!allCaught) break;
}
return !allCaught;
} else {
return false;
}
}
/**
* Returns all exceptions, which may be raised by this instruction. This includes exceptions from
* throw and invoke statements.
*
* @return all exceptions, which may be raised by this instruction
*/
public Set<TypeReference> getExceptions(final CGNode node, SSAInstruction instruction) {
if (!isSolved) {
throw new IllegalStateException("You need to use .solve() first!");
}
final Set<TypeReference> thrown =
intraResult.getAnalysis(node).collectThrownExceptions(instruction);
instruction.visit(
new Visitor() {
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
CallSiteReference site = instruction.getCallSite();
Set<CGNode> targets = cg.getPossibleTargets(node, site);
for (CGNode target : targets) {
thrown.addAll(getCGNodeExceptions(target));
}
}
});
Set<TypeReference> result = thrown;
if (filter != null) {
ExceptionFilter<SSAInstruction> nodeFilter = filter.getFilter(node);
result =
ExceptionMatcher.retainedExceptions(
thrown, nodeFilter.filteredExceptions(instruction), cha);
}
return result;
}
/**
* @return all exceptions, which might be thrown by the method represented through the call graph
* node.
*/
public Set<TypeReference> getCGNodeExceptions(CGNode node) {
if (!isSolved) {
throw new IllegalStateException("You need to use .solve() first!");
}
BitVectorVariable nodeResult = solver.getOut(node);
if (nodeResult != null) {
return transformer.computeExceptions(nodeResult);
} else {
return null;
}
}
/** @return the used filter */
public InterproceduralExceptionFilter<SSAInstruction> getFilter() {
if (!isSolved) {
throw new IllegalStateException("You need to use .solve() first!");
}
return filter;
}
}
| 9,473
| 37.048193
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/ExceptionAnalysis2EdgeFilter.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.analysis.exceptionanalysis;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.EdgeFilter;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
/**
* Converter to use the results of the exception analysis with an edge filter.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class ExceptionAnalysis2EdgeFilter implements EdgeFilter<ISSABasicBlock> {
private final ExceptionAnalysis analysis;
private final CGNode node;
public ExceptionAnalysis2EdgeFilter(ExceptionAnalysis analysis, CGNode node) {
this.analysis = analysis;
this.node = node;
}
@Override
public boolean hasNormalEdge(ISSABasicBlock src, ISSABasicBlock dst) {
boolean originalEdge =
node.getIR().getControlFlowGraph().getNormalSuccessors(src).contains(dst);
boolean result = originalEdge;
SSAInstruction instruction = IntraproceduralExceptionAnalysis.getThrowingInstruction(src);
if (instruction != null) {
if (analysis.getFilter().getFilter(node).alwaysThrowsException(instruction)) {
result = false;
}
}
return result;
}
@Override
public boolean hasExceptionalEdge(ISSABasicBlock src, ISSABasicBlock dst) {
boolean originalEdge =
node.getIR().getControlFlowGraph().getExceptionalSuccessors(src).contains(dst);
boolean result = originalEdge;
if (dst.isCatchBlock()) {
if (!analysis.catchesException(node, src, dst)) {
result = false;
}
} else {
assert dst.isExitBlock();
result = analysis.hasUncaughtExceptions(node, src);
}
return result;
}
}
| 2,013
| 30.968254
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/ExceptionTransferFunctionProvider.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.analysis.exceptionanalysis;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.dataflow.graph.BitVectorMinusVector;
import com.ibm.wala.dataflow.graph.BitVectorUnion;
import com.ibm.wala.dataflow.graph.BitVectorUnionVector;
import com.ibm.wala.dataflow.graph.ITransferFunctionProvider;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.intset.BitVector;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
public class ExceptionTransferFunctionProvider
implements ITransferFunctionProvider<CGNode, BitVectorVariable> {
private final Exception2BitvectorTransformer transformer;
private final CallGraph cg;
private final CGIntraproceduralExceptionAnalysis intraResult;
public ExceptionTransferFunctionProvider(
CGIntraproceduralExceptionAnalysis intraResult,
CallGraph cg,
Exception2BitvectorTransformer transformer) {
this.cg = cg;
this.transformer = transformer;
this.intraResult = intraResult;
}
@Override
public boolean hasNodeTransferFunctions() {
return true;
}
@Override
public boolean hasEdgeTransferFunctions() {
return true;
}
@Override
public AbstractMeetOperator<BitVectorVariable> getMeetOperator() {
return BitVectorUnion.instance();
}
@Override
public UnaryOperator<BitVectorVariable> getNodeTransferFunction(CGNode node) {
Set<TypeReference> exceptions = intraResult.getAnalysis(node).getExceptions();
BitVector bitVector = transformer.computeBitVector(exceptions);
return new BitVectorUnionVector(bitVector);
}
@Override
public UnaryOperator<BitVectorVariable> getEdgeTransferFunction(CGNode dst, CGNode src) {
/*
* Note, that dst and src are swapped. For the data-flow-analysis we use
* called -> caller, but for the call graph we need caller -> called.
*/
Iterator<CallSiteReference> callsites = cg.getPossibleSites(src, dst);
BitVector filtered = new BitVector(transformer.getValues().getSize());
if (callsites.hasNext()) {
CallSiteReference callsite = callsites.next();
Set<TypeReference> caught =
new LinkedHashSet<>(intraResult.getAnalysis(src).getCaughtExceptions(callsite));
while (callsites.hasNext()) {
callsite = callsites.next();
caught.retainAll(intraResult.getAnalysis(src).getCaughtExceptions(callsite));
}
filtered = transformer.computeBitVector(caught);
return new BitVectorMinusVector(filtered);
} else {
// This case should not happen, as we should only get src, dst pairs,
// which represent an edge in the call graph. For each edge in the call
// graph should be at least one call site.
throw new RuntimeException("Internal Error: Got call graph edge without call site.");
}
}
}
| 3,441
| 34.484536
| 91
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/InitializedBitVectorSolver.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.analysis.exceptionanalysis;
import com.ibm.wala.dataflow.graph.BitVectorSolver;
import com.ibm.wala.dataflow.graph.IKilldallFramework;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.util.intset.BitVector;
public class InitializedBitVectorSolver extends BitVectorSolver<CGNode> {
public InitializedBitVectorSolver(IKilldallFramework<CGNode, BitVectorVariable> problem) {
super(problem);
}
@Override
protected BitVectorVariable makeNodeVariable(CGNode n, boolean IN) {
return newBV();
}
@Override
protected BitVectorVariable makeEdgeVariable(CGNode src, CGNode dst) {
return newBV();
}
private static BitVectorVariable newBV() {
/*
* If we do not initialize BitVectorVariable, with a BitVector, it contains
* null, which may crash in combination with {@link BitVectorMinusVector}
* used in {@link ExceptionTransferFunction}
*/
BitVectorVariable result = new BitVectorVariable();
result.addAll(new BitVector());
return result;
}
}
| 1,453
| 31.311111
| 92
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/IntraproceduralExceptionAnalysis.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.analysis.exceptionanalysis;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.core.util.ssa.InstructionByIIndexMap;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cfg.exceptionpruning.ExceptionFilter;
import com.ibm.wala.ipa.cfg.exceptionpruning.FilteredException;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.Visitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.intset.IntIterator;
import com.ibm.wala.util.intset.IntSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class IntraproceduralExceptionAnalysis {
private final Set<TypeReference> exceptions;
private Set<TypeReference> possiblyCaughtExceptions;
private PointerAnalysis<InstanceKey> pointerAnalysis;
private CGNode node;
private ClassHierarchy classHierachy;
private ExceptionFilter<SSAInstruction> filter;
private IR ir;
private boolean dummy = false;
private Map<SSAInstruction, Boolean> allExceptionsCaught;
public static IntraproceduralExceptionAnalysis newDummy() {
return new IntraproceduralExceptionAnalysis();
}
/** Create a dummy analysis. */
private IntraproceduralExceptionAnalysis() {
this.dummy = true;
this.exceptions = Collections.emptySet();
}
/**
* You can use this method, if you don't have a call graph, but want some exception analysis. But
* as no pointer analysis is given, we can not consider throw instructions.
*/
@Deprecated
public IntraproceduralExceptionAnalysis(
IR ir, ExceptionFilter<SSAInstruction> filter, ClassHierarchy cha) {
this(ir, filter, cha, null, null);
}
/** Create and compute intraprocedural exception analysis. (IR from node.getIR() will be used.) */
public IntraproceduralExceptionAnalysis(
CGNode node,
ExceptionFilter<SSAInstruction> filter,
ClassHierarchy cha,
PointerAnalysis<InstanceKey> pointerAnalysis) {
this(node.getIR(), filter, cha, pointerAnalysis, node);
}
/** Create and compute intraprocedural exception analysis. */
public IntraproceduralExceptionAnalysis(
IR ir,
ExceptionFilter<SSAInstruction> filter,
ClassHierarchy cha,
PointerAnalysis<InstanceKey> pointerAnalysis,
CGNode node) {
this.pointerAnalysis = pointerAnalysis;
this.classHierachy = cha;
this.filter = filter;
this.ir = ir;
this.node = node;
this.exceptions = new LinkedHashSet<>();
this.possiblyCaughtExceptions = new LinkedHashSet<>();
this.allExceptionsCaught = new InstructionByIIndexMap<>();
compute();
}
/**
* Computes thrown exceptions for each basic block of all call graph nodes. Everything, but invoke
* instructions, will be considered. This includes filtered and caught exceptions.
*/
private void compute() {
if (ir != null) {
for (ISSABasicBlock block : ir.getControlFlowGraph()) {
SSAInstruction throwingInstruction = getThrowingInstruction(block);
if (throwingInstruction != null && throwingInstruction.isPEI()) {
Set<TypeReference> thrownExceptions = collectThrownExceptions(throwingInstruction);
Set<TypeReference> caughtExceptions = collectCaughtExceptions(block);
Set<TypeReference> filteredExceptions = collectFilteredExceptions(throwingInstruction);
thrownExceptions.removeAll(filteredExceptions);
thrownExceptions.removeAll(caughtExceptions);
this.allExceptionsCaught.put(throwingInstruction, thrownExceptions.isEmpty());
exceptions.addAll(thrownExceptions);
}
if (block.isCatchBlock()) {
Iterator<TypeReference> it = block.getCaughtExceptionTypes();
while (it.hasNext()) {
possiblyCaughtExceptions.add(it.next());
}
}
}
}
Set<TypeReference> subClasses = new LinkedHashSet<>();
for (TypeReference caught : possiblyCaughtExceptions) {
// ignore exception types that cannot be resolved
if (this.classHierachy.lookupClass(caught) != null) {
for (IClass iclass : this.classHierachy.computeSubClasses(caught)) {
subClasses.add(iclass.getReference());
}
}
}
possiblyCaughtExceptions.addAll(subClasses);
}
/**
* Return all exceptions that could be returned from getCaughtExceptions
*
* @return all exceptions that could be returned from getCaughtExceptions
*/
public Set<TypeReference> getPossiblyCaughtExceptions() {
return possiblyCaughtExceptions;
}
/**
* Returns the set of exceptions, which are to be filtered for throwingInstruction.
*
* @return exceptions, which are to be filtered
*/
private Set<TypeReference> collectFilteredExceptions(SSAInstruction throwingInstruction) {
if (filter != null) {
Set<TypeReference> filtered = new LinkedHashSet<>();
Collection<FilteredException> filters = filter.filteredExceptions(throwingInstruction);
for (FilteredException filter : filters) {
if (filter.isSubclassFiltered()) {
for (IClass iclass : this.classHierachy.computeSubClasses(filter.getException())) {
filtered.add(iclass.getReference());
}
} else {
filtered.add(filter.getException());
}
}
return filtered;
} else {
return Collections.emptySet();
}
}
/**
* Returns a set of exceptions, which might be thrown from this instruction within this method.
*
* <p>This does include exceptions dispatched by throw instructions, but not exceptions from
* method calls.
*
* @return a set of exceptions, which might be thrown from this instruction within this method
*/
public Set<TypeReference> collectThrownExceptions(SSAInstruction throwingInstruction) {
final LinkedHashSet<TypeReference> result =
new LinkedHashSet<>(throwingInstruction.getExceptionTypes());
throwingInstruction.visit(
new Visitor() {
@Override
public void visitThrow(SSAThrowInstruction instruction) {
addThrown(result, instruction);
}
});
return result;
}
/**
* Collects all exceptions, which could be dispatched by the throw instruction, using the pointer
* analysis. Adds the collected exceptions to addTo.
*
* @param addTo set to add the result
* @param instruction the throw instruction
*/
private void addThrown(LinkedHashSet<TypeReference> addTo, SSAThrowInstruction instruction) {
int exceptionVariable = instruction.getException();
if (pointerAnalysis != null) {
PointerKey pointerKey =
pointerAnalysis.getHeapModel().getPointerKeyForLocal(node, exceptionVariable);
Iterator<Object> it = pointerAnalysis.getHeapGraph().getSuccNodes(pointerKey);
while (it.hasNext()) {
Object next = it.next();
if (next instanceof InstanceKey) {
InstanceKey instanceKey = (InstanceKey) next;
IClass iclass = instanceKey.getConcreteType();
addTo.add(iclass.getReference());
} else {
throw new IllegalStateException(
"Internal error: Expected InstanceKey, got " + next.getClass().getName());
}
}
}
}
/**
* @return an instruction which may throw exceptions, or null if this block can't throw exceptions
*/
public static SSAInstruction getThrowingInstruction(ISSABasicBlock block) {
SSAInstruction result = null;
if (block.getLastInstructionIndex() >= 0) {
SSAInstruction lastInstruction = block.getLastInstruction();
if (lastInstruction != null && lastInstruction.isPEI()) {
result = lastInstruction;
}
}
return result;
}
/** @return a set of all exceptions which will be caught, if thrown by the given block. */
private Set<TypeReference> collectCaughtExceptions(ISSABasicBlock block) {
LinkedHashSet<TypeReference> result = new LinkedHashSet<>();
List<ISSABasicBlock> exceptionalSuccessors =
ir.getControlFlowGraph().getExceptionalSuccessors(block);
for (ISSABasicBlock succ : exceptionalSuccessors) {
if (succ.isCatchBlock()) {
Iterator<TypeReference> it = succ.getCaughtExceptionTypes();
while (it.hasNext()) {
result.add(it.next());
}
}
}
Set<TypeReference> subClasses = new LinkedHashSet<>();
for (TypeReference caught : result) {
// ignore exception types that cannot be resolved
if (this.classHierachy.lookupClass(caught) != null) {
for (IClass iclass : this.classHierachy.computeSubClasses(caught)) {
subClasses.add(iclass.getReference());
}
}
}
result.addAll(subClasses);
return result;
}
/**
* Returns all exceptions for the given call site in the given call graph node, which will be
* caught.
*
* @return caught exceptions
*/
public Set<TypeReference> getCaughtExceptions(CallSiteReference callsite) {
Set<TypeReference> result = null;
if (dummy) {
result = Collections.emptySet();
} else {
IntSet iindices = ir.getCallInstructionIndices(callsite);
IntIterator it = iindices.intIterator();
while (it.hasNext()) {
int iindex = it.next();
SSAInstruction instruction = ir.getInstructions()[iindex];
if (!(instruction instanceof SSAInvokeInstruction)) {
throw new IllegalArgumentException(
"The given callsite dose not correspond to an invoke instruction." + instruction);
}
ISSABasicBlock block = ir.getBasicBlockForInstruction(instruction);
if (result == null) {
result = new LinkedHashSet<>(collectCaughtExceptions(block));
} else {
result.retainAll(collectCaughtExceptions(block));
}
}
}
return result;
}
public boolean hasUncaughtExceptions(SSAInstruction instruction) {
Boolean allCaught = this.allExceptionsCaught.get(instruction);
return (allCaught == null ? true : !allCaught);
}
/**
* Returns all exceptions which might be created and thrown but not caught or filtered. (So this
* does not contain exceptions from invoked methods.)
*
* <p>If constructed without points-to-analysis, it does not contain exceptions thrown by throw
* statements.
*
* @return all exceptions created and thrown intraprocedural
*/
public Set<TypeReference> getExceptions() {
return exceptions;
}
}
| 11,391
| 35.050633
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/exceptionanalysis/package-info.java
|
/**
* This package contains an exception analysis. For an interprocedural exception analysis use {@link
* com.ibm.wala.analysis.exceptionanalysis.ExceptionAnalysis}. If you need a CFG without unnecessary
* exception edges use {@link com.ibm.wala.ipa.cfg.PrunedCFG} in combination with {@link
* com.ibm.wala.analysis.exceptionanalysis.ExceptionAnalysis2EdgeFilter}
*/
package com.ibm.wala.analysis.exceptionanalysis;
| 421
| 51.75
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/nullpointer/IntraproceduralNullPointerAnalysis.java
|
package com.ibm.wala.analysis.nullpointer;
import com.ibm.wala.cfg.exc.intra.IntraprocNullPointerAnalysis;
import com.ibm.wala.cfg.exc.intra.NullPointerFrameWork;
import com.ibm.wala.cfg.exc.intra.NullPointerSolver;
import com.ibm.wala.cfg.exc.intra.NullPointerState;
import com.ibm.wala.cfg.exc.intra.NullPointerState.State;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
/**
* Intraprocedural dataflow analysis to detect impossible NullPointerExceptions.
*
* <p>This class is basically a copy of {@link IntraprocNullPointerAnalysis}, but does only provide
* the result of the analysis instead of a pruned CFG.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class IntraproceduralNullPointerAnalysis {
private static final IProgressMonitor NO_PROGRESS_MONITOR = null;
private final NullPointerSolver<ISSABasicBlock> solver;
private final IR ir;
public IntraproceduralNullPointerAnalysis(IR ir) {
if (ir == null || ir.isEmptyIR()) {
throw new IllegalArgumentException("IR may not be null or empty.");
}
this.ir = ir;
final int maxVarNum = ir.getSymbolTable().getMaxValueNumber();
SSACFG cfg = ir.getControlFlowGraph();
final NullPointerFrameWork<ISSABasicBlock> problem = new NullPointerFrameWork<>(cfg, ir);
this.solver = new NullPointerSolver<>(problem, maxVarNum, ir, cfg.entry());
try {
this.solver.solve(NO_PROGRESS_MONITOR);
} catch (final CancelException e) {
// can't happen as we have no monitor
}
}
public State nullPointerExceptionThrowState(SSAInstruction instruction) {
assert instruction != null;
if (instruction.isPEI()
&& instruction.getExceptionTypes().contains(TypeReference.JavaLangNullPointerException)) {
final NullPointerState blockState =
this.solver.getIn(this.ir.getBasicBlockForInstruction(instruction));
final RelevantVariableFinder finder = new RelevantVariableFinder(instruction);
assert finder.getVarNum() >= 0;
return blockState.getState(finder.getVarNum());
}
return State.NOT_NULL;
}
}
| 2,308
| 37.483333
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/nullpointer/RelevantVariableFinder.java
|
package com.ibm.wala.analysis.nullpointer;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.IVisitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
/**
* Helper class to find the variable that may be null.
*
* @author Stephan Gocht {@code <stephan@gobro.de>}
*/
public class RelevantVariableFinder implements IVisitor {
private int varNumNew;
private final int varNum;
public RelevantVariableFinder(SSAInstruction instrcution) {
this.varNumNew = -1;
instrcution.visit(this);
this.varNum = this.varNumNew;
}
public int getVarNum() {
return this.varNum;
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayLength(com.ibm.wala
* .ssa.SSAArrayLengthInstruction)
*/
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
this.varNumNew = instruction.getArrayRef();
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayLoad(com.ibm.wala.
* ssa.SSAArrayLoadInstruction)
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
this.varNumNew = instruction.getArrayRef();
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitArrayStore(com.ibm.wala
* .ssa.SSAArrayStoreInstruction)
*/
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
this.varNumNew = instruction.getArrayRef();
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitBinaryOp(com.ibm.wala.ssa
* .SSABinaryOpInstruction)
*/
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitCheckCast(com.ibm.wala.
* ssa.SSACheckCastInstruction)
*/
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitComparison(com.ibm.wala
* .ssa.SSAComparisonInstruction)
*/
@Override
public void visitComparison(SSAComparisonInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitConditionalBranch(com.ibm
* .wala.ssa.SSAConditionalBranchInstruction)
*/
@Override
public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitConversion(com.ibm.wala
* .ssa.SSAConversionInstruction)
*/
@Override
public void visitConversion(SSAConversionInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGet(com.ibm.wala.ssa.
* SSAGetInstruction)
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
if (!instruction.isStatic()) {
this.varNumNew = instruction.getRef();
}
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGetCaughtException(com.
* ibm.wala.ssa.SSAGetCaughtExceptionInstruction)
*/
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitGoto(com.ibm.wala.ssa.
* SSAGotoInstruction)
*/
@Override
public void visitGoto(SSAGotoInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitInstanceof(com.ibm.wala
* .ssa.SSAInstanceofInstruction)
*/
@Override
public void visitInstanceof(SSAInstanceofInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitInvoke(com.ibm.wala.ssa
* .SSAInvokeInstruction)
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
if (!instruction.isStatic()) {
this.varNumNew = instruction.getReceiver();
}
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitLoadMetadata(com.ibm.wala
* .ssa.SSALoadMetadataInstruction)
*/
@Override
public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitMonitor(com.ibm.wala.ssa
* .SSAMonitorInstruction)
*/
@Override
public void visitMonitor(SSAMonitorInstruction instruction) {
this.varNumNew = instruction.getRef();
}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitNew(com.ibm.wala.ssa.
* SSANewInstruction)
*/
@Override
public void visitNew(SSANewInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPhi(com.ibm.wala.ssa.
* SSAPhiInstruction)
*/
@Override
public void visitPhi(SSAPhiInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPi(com.ibm.wala.ssa.
* SSAPiInstruction)
*/
@Override
public void visitPi(SSAPiInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.ssa.SSAInstruction.IVisitor#visitPut(com.ibm.wala.ssa.
* SSAPutInstruction)
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
if (!instruction.isStatic()) {
this.varNumNew = instruction.getRef();
}
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitReturn(com.ibm.wala.ssa
* .SSAReturnInstruction)
*/
@Override
public void visitReturn(SSAReturnInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitSwitch(com.ibm.wala.ssa
* .SSASwitchInstruction)
*/
@Override
public void visitSwitch(SSASwitchInstruction instruction) {}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitThrow(com.ibm.wala.ssa.
* SSAThrowInstruction)
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {
this.varNumNew = instruction.getException();
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.wala.ssa.SSAInstruction.IVisitor#visitUnaryOp(com.ibm.wala.ssa
* .SSAUnaryOpInstruction)
*/
@Override
public void visitUnaryOp(SSAUnaryOpInstruction instruction) {}
}
| 7,484
| 24.459184
| 86
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/pointers/BasicHeapGraph.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.analysis.pointers;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
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.types.TypeReference;
import com.ibm.wala.util.collections.CompoundIterator;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.IntMapIterator;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.graph.AbstractNumberedGraph;
import com.ibm.wala.util.graph.NumberedEdgeManager;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.graph.NumberedNodeManager;
import com.ibm.wala.util.graph.impl.NumberedNodeIterator;
import com.ibm.wala.util.intset.BasicNaturalRelation;
import com.ibm.wala.util.intset.IBinaryNaturalRelation;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableMapping;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.MutableSparseIntSetFactory;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import com.ibm.wala.util.intset.SparseIntSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.function.IntFunction;
import java.util.stream.Stream;
/** Basic implementation of {@link HeapGraph} */
public class BasicHeapGraph<T extends InstanceKey> extends HeapGraphImpl<T> {
private static final boolean VERBOSE = false;
private static final int VERBOSE_INTERVAL = 10000;
private static final MutableSparseIntSetFactory factory = new MutableSparseIntSetFactory();
/** The backing graph */
private final NumberedGraph<Object> G;
/** governing call graph */
private final CallGraph callGraph;
/**
* @param P governing pointer analysis
* @throws NullPointerException if P is null
*/
public BasicHeapGraph(final PointerAnalysis<T> P, final CallGraph callGraph)
throws NullPointerException {
super(P);
this.callGraph = callGraph;
final OrdinalSetMapping<PointerKey> pointerKeys = getPointerKeys();
final NumberedNodeManager<Object> nodeMgr =
new NumberedNodeManager<>() {
@Override
public Iterator<Object> iterator() {
return new CompoundIterator<>(
pointerKeys.iterator(), P.getInstanceKeyMapping().iterator());
}
@Override
public Stream<Object> stream() {
return Stream.concat(pointerKeys.stream(), P.getInstanceKeyMapping().stream());
}
@Override
public int getNumberOfNodes() {
return pointerKeys.getSize() + P.getInstanceKeyMapping().getSize();
}
@Override
public void addNode(Object n) {
Assertions.UNREACHABLE();
}
@Override
public void removeNode(Object n) {
Assertions.UNREACHABLE();
}
@Override
public int getNumber(Object N) {
if (N instanceof PointerKey) {
return pointerKeys.getMappedIndex(N);
} else {
if (!(N instanceof InstanceKey)) {
Assertions.UNREACHABLE(N.getClass().toString());
}
int inumber = P.getInstanceKeyMapping().getMappedIndex(N);
return (inumber == -1) ? -1 : inumber + pointerKeys.getMaximumIndex() + 1;
}
}
@Override
public Object getNode(int number) {
if (number > pointerKeys.getMaximumIndex()) {
return P.getInstanceKeyMapping().getMappedObject(number - pointerKeys.getSize());
} else {
return pointerKeys.getMappedObject(number);
}
}
@Override
public int getMaxNumber() {
return getNumberOfNodes() - 1;
}
@Override
public boolean containsNode(Object n) {
return getNumber(n) != -1;
}
@Override
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<>(s, this);
}
};
final IBinaryNaturalRelation pred = computePredecessors(nodeMgr);
final IntFunction<Object> toNode = nodeMgr::getNode;
this.G =
new AbstractNumberedGraph<>() {
private final NumberedEdgeManager<Object> edgeMgr =
new NumberedEdgeManager<>() {
@Override
public Iterator<Object> getPredNodes(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p == null) {
return EmptyIterator.instance();
} else {
return new IntMapIterator<>(p.intIterator(), toNode);
}
}
@Override
public IntSet getPredNodeNumbers(Object N) {
int n = nodeMgr.getNumber(N);
IntSet p = pred.getRelated(n);
if (p != null) {
return p;
} else {
return IntSetUtil.make();
}
}
@Override
public int getPredNodeCount(Object N) {
int n = nodeMgr.getNumber(N);
return pred.getRelatedCount(n);
}
@Override
public Iterator<Object> getSuccNodes(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return EmptyIterator.instance();
}
SparseIntSet s = factory.make(succ);
return new IntMapIterator<>(s.intIterator(), toNode);
}
@Override
public IntSet getSuccNodeNumbers(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
if (succ == null) {
return IntSetUtil.make();
} else {
return IntSetUtil.make(succ);
}
}
@Override
public int getSuccNodeCount(Object N) {
int[] succ = computeSuccNodeNumbers(N, nodeMgr);
return succ == null ? 0 : succ.length;
}
@Override
public void addEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
@Override
public void removeEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
}
@Override
public void removeAllIncidentEdges(Object node) {
Assertions.UNREACHABLE();
}
@Override
public void removeIncomingEdges(Object node) {
Assertions.UNREACHABLE();
}
@Override
public void removeOutgoingEdges(Object node) {
Assertions.UNREACHABLE();
}
@Override
public boolean hasEdge(Object src, Object dst) {
Assertions.UNREACHABLE();
return false;
}
};
@Override
protected NumberedNodeManager<Object> getNodeManager() {
return nodeMgr;
}
@Override
protected NumberedEdgeManager<Object> getEdgeManager() {
return edgeMgr;
}
};
}
private OrdinalSetMapping<PointerKey> getPointerKeys() {
MutableMapping<PointerKey> result = MutableMapping.make();
for (PointerKey p : getPointerAnalysis().getPointerKeys()) {
result.add(p);
}
return result;
}
private int[] computeSuccNodeNumbers(Object N, NumberedNodeManager<Object> nodeManager) {
if (N instanceof PointerKey) {
PointerKey P = (PointerKey) N;
OrdinalSet<T> S = getPointerAnalysis().getPointsToSet(P);
int[] result = new int[S.size()];
int i = 0;
for (T t : S) {
result[i] = nodeManager.getNumber(t);
i++;
}
return result;
} else if (N instanceof InstanceKey) {
InstanceKey I = (InstanceKey) N;
TypeReference T = I.getConcreteType().getReference();
assert T != null : "null concrete type from " + I.getClass();
if (T.isArrayType()) {
PointerKey p = getHeapModel().getPointerKeyForArrayContents(I);
if (p == null || !nodeManager.containsNode(p)) {
return null;
} else {
return new int[] {nodeManager.getNumber(p)};
}
} else {
IClass klass = I.getConcreteType();
assert klass != null : "null klass for type " + T;
MutableSparseIntSet result = MutableSparseIntSet.makeEmpty();
for (IField f : klass.getAllInstanceFields()) {
if (!f.getReference().getFieldType().isPrimitiveType()) {
PointerKey p = getHeapModel().getPointerKeyForInstanceField(I, f);
if (p != null && nodeManager.containsNode(p)) {
result.add(nodeManager.getNumber(p));
}
}
}
return result.toIntArray();
}
} else {
Assertions.UNREACHABLE("Unexpected type: " + N.getClass());
return null;
}
}
/** @return R, y \in R(x,y) if the node y is a predecessor of node x */
private IBinaryNaturalRelation computePredecessors(NumberedNodeManager<Object> nodeManager) {
BasicNaturalRelation R =
new BasicNaturalRelation(
new byte[] {BasicNaturalRelation.SIMPLE}, BasicNaturalRelation.SIMPLE);
// we split the following loops to improve temporal locality,
// particularly for locals
computePredecessorsForNonLocals(nodeManager, R);
computePredecessorsForLocals(nodeManager, R);
return R;
}
private void computePredecessorsForNonLocals(
NumberedNodeManager<Object> nodeManager, BasicNaturalRelation R) {
// Note: we run this loop backwards on purpose, to avoid lots of resizing of
// bitvectors
// in the backing relation. i.e., we will add the biggest bits first.
// pretty damn tricky.
for (int i = nodeManager.getMaxNumber(); i >= 0; i--) {
if (VERBOSE) {
if (i % VERBOSE_INTERVAL == 0) {
System.err.println("Building HeapGraph: " + i);
}
}
Object n = nodeManager.getNode(i);
if (!(n instanceof LocalPointerKey)) {
int[] succ = computeSuccNodeNumbers(n, nodeManager);
if (succ != null) {
for (int j : succ) {
R.add(j, i);
}
}
}
}
}
/** traverse locals in order, first by node, then by value number: attempt to improve locality */
private void computePredecessorsForLocals(
NumberedNodeManager<Object> nodeManager, BasicNaturalRelation R) {
ArrayList<LocalPointerKey> list = new ArrayList<>();
for (Object n : nodeManager) {
if (n instanceof LocalPointerKey) {
list.add((LocalPointerKey) n);
}
}
Object[] arr = list.toArray();
Arrays.sort(arr, new LocalPointerComparator());
for (int i = 0; i < arr.length; i++) {
if (VERBOSE) {
if (i % VERBOSE_INTERVAL == 0) {
System.err.println("Building HeapGraph: " + i + " of " + arr.length);
}
}
LocalPointerKey n = (LocalPointerKey) arr[i];
int num = nodeManager.getNumber(n);
int[] succ = computeSuccNodeNumbers(n, nodeManager);
if (succ != null) {
for (int j : succ) {
R.add(j, num);
}
}
}
}
/** sorts local pointers by node, then value number */
private final class LocalPointerComparator implements Comparator<Object> {
@Override
public int compare(Object arg1, Object arg2) {
LocalPointerKey o1 = (LocalPointerKey) arg1;
LocalPointerKey o2 = (LocalPointerKey) arg2;
if (o1.getNode().equals(o2.getNode())) {
return o1.getValueNumber() - o2.getValueNumber();
} else {
return callGraph.getNumber(o1.getNode()) - callGraph.getNumber(o2.getNode());
}
}
}
/** @see com.ibm.wala.util.graph.NumberedNodeManager#getNumber(Object) */
@Override
public int getNumber(Object N) {
return G.getNumber(N);
}
/** @see com.ibm.wala.util.graph.NumberedNodeManager#getNode(int) */
@Override
public Object getNode(int number) {
return G.getNode(number);
}
/** @see com.ibm.wala.util.graph.NumberedNodeManager#getMaxNumber() */
@Override
public int getMaxNumber() {
return G.getMaxNumber();
}
/** @see com.ibm.wala.util.graph.NodeManager#iterator() */
@Override
public Iterator<Object> iterator() {
return G.iterator();
}
/** @see com.ibm.wala.util.graph.NodeManager#iterator() */
@Override
public Stream<Object> stream() {
return G.stream();
}
/** @see com.ibm.wala.util.graph.NodeManager#getNumberOfNodes() */
@Override
public int getNumberOfNodes() {
return G.getNumberOfNodes();
}
/** @see com.ibm.wala.util.graph.EdgeManager#getPredNodes(Object) */
@Override
public Iterator<Object> getPredNodes(Object N) {
return G.getPredNodes(N);
}
/** @see com.ibm.wala.util.graph.EdgeManager#getPredNodeCount(Object) */
@Override
public int getPredNodeCount(Object N) {
return G.getPredNodeCount(N);
}
/** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodes(Object) */
@Override
public Iterator<Object> getSuccNodes(Object N) {
return G.getSuccNodes(N);
}
/** @see com.ibm.wala.util.graph.EdgeManager#getSuccNodeCount(Object) */
@Override
public int getSuccNodeCount(Object N) {
return G.getSuccNodeCount(N);
}
/** @see com.ibm.wala.util.graph.NodeManager#addNode(Object) */
@Override
public void addNode(Object n) throws UnimplementedError {
Assertions.UNREACHABLE();
}
/** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */
@Override
public void removeNode(Object n) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public void addEdge(Object from, Object to) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public void removeEdge(Object from, Object to) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public boolean hasEdge(Object from, Object to) throws UnimplementedError {
Assertions.UNREACHABLE();
return false;
}
@Override
public void removeAllIncidentEdges(Object node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/** @see com.ibm.wala.util.graph.NodeManager#containsNode(Object) */
@Override
public boolean containsNode(Object N) {
return G.containsNode(N);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Nodes:\n");
for (int i = 0; i <= getMaxNumber(); i++) {
Object node = getNode(i);
if (node != null) {
result.append(i).append(" ").append(node).append('\n');
}
}
result.append("Edges:\n");
for (int i = 0; i <= getMaxNumber(); i++) {
Object node = getNode(i);
if (node != null) {
result.append(i).append(" -> ");
for (Object s : Iterator2Iterable.make(getSuccNodes(node))) {
result.append(getNumber(s)).append(' ');
}
result.append('\n');
}
}
return result.toString();
}
@Override
public void removeIncomingEdges(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public void removeOutgoingEdges(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public IntSet getSuccNodeNumbers(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
@Override
public IntSet getPredNodeNumbers(Object node) throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
}
| 16,874
| 31.142857
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/pointers/HeapGraph.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.analysis.pointers;
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.util.graph.Graph;
import com.ibm.wala.util.graph.NumberedGraph;
import java.util.Collection;
import java.util.Set;
/**
* A {@link Graph} view of a pointer analysis solution.
*
* <p>Nodes in the Graph are {@link PointerKey}s and {@link InstanceKey}s.
*
* <p>There is an edge from a PointerKey P to an InstanceKey I iff the PointerAnalysis indicates
* that P may point to I.
*
* <p>There is an edge from an InstanceKey I to a PointerKey P iff - P represents a field of an
* object instance modeled by I, or - P represents the array contents of array instance I.
*/
public interface HeapGraph<T extends InstanceKey> extends NumberedGraph<Object> {
Collection<Object> getReachableInstances(Set<Object> roots);
HeapModel getHeapModel();
PointerAnalysis<T> getPointerAnalysis();
}
| 1,468
| 34.829268
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/pointers/HeapGraphImpl.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.analysis.pointers;
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.util.graph.Graph;
import com.ibm.wala.util.graph.impl.NumberedNodeIterator;
import com.ibm.wala.util.graph.traverse.DFS;
import com.ibm.wala.util.intset.IntSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* A {@link Graph} view of a pointer analysis solution.
*
* <p>Nodes in the Graph are {@link PointerKey}s and {@link InstanceKey}s.
*
* <p>There is an edge from a PointerKey P to an InstanceKey I iff the PointerAnalysis indicates
* that P may point to I.
*
* <p>There is an edge from an InstanceKey I to a PointerKey P iff - P represents a field of an
* object instance modeled by I, or - P represents the array contents of array instance I.
*/
public abstract class HeapGraphImpl<T extends InstanceKey> implements HeapGraph<T> {
private final PointerAnalysis<T> pa;
protected HeapGraphImpl(PointerAnalysis<T> pa) {
if (pa == null) {
throw new IllegalArgumentException("null pa ");
}
this.pa = pa;
}
@Override
public Iterator<Object> iterateNodes(IntSet s) {
return new NumberedNodeIterator<>(s, this);
}
@Override
public Collection<Object> getReachableInstances(Set<Object> roots) {
return DFS.getReachableNodes(this, roots, InstanceKey.class::isInstance);
}
@Override
public void removeNodeAndEdges(Object N) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/** @return the heap model used in this pointer analysis. */
@Override
public HeapModel getHeapModel() {
return pa.getHeapModel();
}
@Override
public PointerAnalysis<T> getPointerAnalysis() {
return pa;
}
}
| 2,311
| 30.671233
| 96
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/AbstractReflectionInterpreter.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.analysis.reflection;
import static com.ibm.wala.types.TypeName.ArrayMask;
import static com.ibm.wala.types.TypeName.ElementMask;
import static com.ibm.wala.types.TypeName.PrimitiveMask;
import com.ibm.wala.analysis.typeInference.ConeType;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.SyntheticMethod;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
/**
* An abstract superclass of various {@link SSAContextInterpreter}s that deal with reflection
* methods.
*/
public abstract class AbstractReflectionInterpreter implements SSAContextInterpreter {
protected static final boolean DEBUG = false;
protected static final int CONE_BOUND = 10;
protected int indexLocal = 100;
protected final Map<TypeReference, Integer> typeIndexMap = HashMapFactory.make();
/** Governing analysis options */
protected AnalysisOptions options;
/** cache of analysis information */
protected IAnalysisCacheView cache;
protected int getLocalForType(TypeReference T) {
Integer I = typeIndexMap.get(T);
if (I == null) {
typeIndexMap.put(T, I = indexLocal += 2);
}
return I;
}
protected int getExceptionsForType(TypeReference T) {
return getLocalForType(T) + 1;
}
protected int getCallSiteForType(TypeReference T) {
return getLocalForType(T);
}
protected int getNewSiteForType(TypeReference T) {
return getLocalForType(T) + 1;
}
/**
* @return a TypeAbstraction object representing this type. We just use ConeTypes by default,
* since we don't propagate information allowing us to distinguish between points and cones
* yet.
*/
protected TypeAbstraction typeRef2TypeAbstraction(IClassHierarchy cha, TypeReference type) {
IClass klass = cha.lookupClass(type);
if (klass != null) {
return new ConeType(klass);
}
Assertions.UNREACHABLE(type.toString());
return null;
}
/** A warning when we expect excessive pollution from a factory method */
protected static class ManySubtypesWarning extends Warning {
final int nImplementors;
final TypeAbstraction T;
ManySubtypesWarning(TypeAbstraction T, int nImplementors) {
super(Warning.MODERATE);
this.T = T;
this.nImplementors = nImplementors;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + T + ' ' + nImplementors;
}
public static ManySubtypesWarning create(TypeAbstraction T, int n) {
return new ManySubtypesWarning(T, n);
}
}
/** A warning when we fail to find subtypes for a factory method */
protected static class NoSubtypesWarning extends Warning {
final TypeAbstraction T;
NoSubtypesWarning(TypeAbstraction T) {
super(Warning.SEVERE);
this.T = T;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + T;
}
public static NoSubtypesWarning create(TypeAbstraction T) {
return new NoSubtypesWarning(T);
}
}
/** A warning when we find flow of a factory allocation to a cast to {@link Serializable} */
protected static class IgnoreSerializableWarning extends Warning {
private static final IgnoreSerializableWarning instance = new IgnoreSerializableWarning();
@Override
public String getMsg() {
return getClass().toString();
}
public static IgnoreSerializableWarning create() {
return instance;
}
}
protected class SpecializedMethod extends SyntheticMethod {
/** Set of types that we have already inserted an allocation for. */
protected final HashSet<TypeReference> typesAllocated = HashSetFactory.make(5);
/** List of synthetic allocation statements we model for this specialized instance */
protected final ArrayList<SSAInstruction> allocations = new ArrayList<>();
/** List of synthetic invoke instructions we model for this specialized instance. */
protected final ArrayList<SSAInstruction> calls = new ArrayList<>();
/** List of all instructions */
protected final ArrayList<SSAInstruction> allInstructions = new ArrayList<>();
private final SSAInstructionFactory insts =
declaringClass.getClassLoader().getInstructionFactory();
public SpecializedMethod(
MethodReference method, IClass declaringClass, boolean isStatic, boolean isFactory) {
super(method, declaringClass, isStatic, isFactory);
}
public SpecializedMethod(
IMethod method, IClass declaringClass, boolean isStatic, boolean isFactory) {
super(method, declaringClass, isStatic, isFactory);
}
/** @param T type allocated by the instruction. */
protected void addInstruction(
final TypeReference T, SSAInstruction instr, boolean isAllocation) {
if (isAllocation) {
if (typesAllocated.contains(T)) {
return;
} else {
typesAllocated.add(T);
}
}
allInstructions.add(instr);
if (isAllocation) {
allocations.add(instr);
}
}
/**
* @param t type of object to allocate
* @return value number of the newly allocated object
*/
protected int addStatementsForConcreteSimpleType(final TypeReference t) {
// assert we haven't allocated this type already.
assert !typesAllocated.contains(t);
if (DEBUG) {
System.err.println(("addStatementsForConcreteType: " + t));
}
NewSiteReference ref = NewSiteReference.make(getNewSiteForType(t), t);
int alloc = getLocalForType(t);
if (t.isArrayType()) {
// for now, just allocate an array of size 1 in each dimension.
int dims = 0;
int dim = t.getDerivedMask();
if ((dim & ElementMask) == PrimitiveMask) {
dim >>= 2;
}
while ((dim & ElementMask) == ArrayMask) {
dims++;
dim >>= 2;
}
int[] extents = new int[dims];
Arrays.fill(extents, 1);
SSANewInstruction a = insts.NewInstruction(allInstructions.size(), alloc, ref, extents);
addInstruction(t, a, true);
} else {
SSANewInstruction a = insts.NewInstruction(allInstructions.size(), alloc, ref);
addInstruction(t, a, true);
addCtorInvokeInstruction(t, alloc);
}
SSAReturnInstruction r = insts.ReturnInstruction(allInstructions.size(), alloc, false);
addInstruction(t, r, false);
return alloc;
}
/**
* Add an instruction to invoke the default constructor on the object of value number alloc of
* type t.
*/
protected void addCtorInvokeInstruction(final TypeReference t, int alloc) {
MethodReference init =
MethodReference.findOrCreate(
t, MethodReference.initAtom, MethodReference.defaultInitDesc);
CallSiteReference site =
CallSiteReference.make(getCallSiteForType(t), init, IInvokeInstruction.Dispatch.SPECIAL);
int[] params = new int[1];
params[0] = alloc;
int exc = getExceptionsForType(t);
SSAAbstractInvokeInstruction s =
insts.InvokeInstruction(allInstructions.size(), params, exc, site, null);
calls.add(s);
allInstructions.add(s);
}
}
}
| 8,635
| 31.961832
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ClassFactoryContextInterpreter.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
/**
* An {@link SSAContextInterpreter} specialized to interpret reflective class factories (e.g.
* Class.forName()) in a {@link JavaTypeContext} which represents the point-type of the class object
* created by the call.
*/
public class ClassFactoryContextInterpreter implements SSAContextInterpreter {
private static final boolean DEBUG = false;
/* BEGIN Custom change: caching */
private final Map<String, IR> cache = HashMapFactory.make();
/* END Custom change: caching */
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
if (DEBUG) {
System.err.println("generating IR for " + node);
}
/* BEGIN Custom change: caching */
final Context context = node.getContext();
final IMethod method = node.getMethod();
final String hashKey = method.toString() + '@' + context.toString();
IR result = cache.get(hashKey);
if (result == null) {
result = makeIR(method, context);
cache.put(hashKey, result);
}
/* END Custom change: caching */
return result;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#understands(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!node.getContext().isA(JavaTypeContext.class)) {
return false;
}
return ClassFactoryContextSelector.isClassFactory(node.getMethod().getReference());
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateNewSites(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
TypeReference tr =
((TypeAbstraction) node.getContext().get(ContextKey.RECEIVER)).getTypeReference();
if (tr != null) {
return new NonNullSingletonIterator<>(NewSiteReference.make(0, tr));
}
return EmptyIterator.instance();
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateCallSites(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
assert understands(node);
return EmptyIterator.instance();
}
private static SSAInstruction[] makeStatements(Context context) {
SSAInstructionFactory insts =
((TypeAbstraction) context.get(ContextKey.RECEIVER))
.getType()
.getClassLoader()
.getInstructionFactory();
ArrayList<SSAInstruction> statements = new ArrayList<>();
// vn1 is the string parameter
int retValue = 2;
TypeReference tr = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getTypeReference();
if (tr != null) {
SSALoadMetadataInstruction l =
insts.LoadMetadataInstruction(
statements.size(), retValue, TypeReference.JavaLangClass, tr);
statements.add(l);
SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), retValue, false);
statements.add(R);
} else {
SSAThrowInstruction t = insts.ThrowInstruction(statements.size(), retValue);
statements.add(t);
}
SSAInstruction[] result = new SSAInstruction[statements.size()];
statements.toArray(result);
return result;
}
private static IR makeIR(IMethod method, Context context) {
SSAInstruction instrs[] = makeStatements(context);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
null);
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 6,353
| 31.090909
| 125
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ClassFactoryContextSelector.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.strings.StringStuff;
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.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
/**
* A {@link ContextSelector} to intercept calls to reflective class factories (e.g. Class.forName())
* when the parameter is a string constant
*/
public class ClassFactoryContextSelector implements ContextSelector {
public static final Atom forNameAtom = Atom.findOrCreateUnicodeAtom("forName");
private static final Descriptor forNameDescriptor =
Descriptor.findOrCreateUTF8("(Ljava/lang/String;)Ljava/lang/Class;");
public static final MethodReference FOR_NAME_REF =
MethodReference.findOrCreate(TypeReference.JavaLangClass, forNameAtom, forNameDescriptor);
public static final Atom loadClassAtom = Atom.findOrCreateUnicodeAtom("loadClass");
private static final Descriptor loadClassDescriptor =
Descriptor.findOrCreateUTF8("(Ljava/lang/String;)Ljava/lang/Class;");
private static final TypeReference CLASSLOADER =
TypeReference.findOrCreate(ClassLoaderReference.Primordial, "Ljava/lang/ClassLoader");
public static final MethodReference LOAD_CLASS_REF =
MethodReference.findOrCreate(CLASSLOADER, loadClassAtom, loadClassDescriptor);
public ClassFactoryContextSelector() {}
public static boolean isClassFactory(MethodReference m) {
if (m.equals(FOR_NAME_REF)) {
return true;
}
if (m.equals(LOAD_CLASS_REF)) {
return true;
}
return false;
}
public int getUseOfStringParameter(SSAAbstractInvokeInstruction call) {
if (call.isStatic()) {
return call.getUse(0);
} else {
return call.getUse(1);
}
}
/**
* If the {@link CallSiteReference} invokes Class.forName(s) and s is a string constant, return a
* {@link JavaTypeContext} representing the type named by s, if we can resolve it in the {@link
* IClassHierarchy}.
*/
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (isClassFactory(callee.getReference())) {
IR ir = caller.getIR();
SymbolTable symbolTable = ir.getSymbolTable();
SSAAbstractInvokeInstruction[] invokeInstructions = caller.getIR().getCalls(site);
if (invokeInstructions.length != 1) {
return null;
}
int use = getUseOfStringParameter(invokeInstructions[0]);
if (symbolTable.isStringConstant(use)) {
String className =
StringStuff.deployment2CanonicalTypeString(symbolTable.getStringValue(use));
TypeReference t =
TypeReference.findOrCreate(
caller.getMethod().getDeclaringClass().getClassLoader().getReference(), className);
IClass klass = caller.getClassHierarchy().lookupClass(t);
if (klass != null) {
return new JavaTypeContext(new PointType(klass));
}
}
int nameVn = callee.isStatic() ? 0 : 1;
if (receiver != null && receiver.length > nameVn) {
if (receiver[nameVn] instanceof ConstantKey) {
ConstantKey<?> ik = (ConstantKey<?>) receiver[nameVn];
if (ik.getConcreteType().getReference().equals(TypeReference.JavaLangString)) {
String className = StringStuff.deployment2CanonicalTypeString(ik.getValue().toString());
for (IClassLoader cl : caller.getClassHierarchy().getLoaders()) {
TypeReference t = TypeReference.findOrCreate(cl.getReference(), className);
IClass klass = caller.getClassHierarchy().lookupClass(t);
if (klass != null) {
return new JavaTypeContext(new PointType(klass));
}
}
}
}
}
}
return null;
}
private static final IntSet thisParameter = IntSetUtil.make(new int[] {0});
private static final IntSet firstParameter = IntSetUtil.make(new int[] {0, 1});
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
IMethod resolved =
caller.getMethod().getClassHierarchy().resolveMethod(site.getDeclaredTarget());
if (isClassFactory(resolved != null ? resolved.getReference() : site.getDeclaredTarget())) {
SSAAbstractInvokeInstruction[] invokeInstructions = caller.getIR().getCalls(site);
if (invokeInstructions.length >= 1) {
if (invokeInstructions[0].isStatic()) {
return thisParameter;
} else {
return firstParameter;
}
} else {
return EmptyIntSet.instance;
}
} else {
return EmptyIntSet.instance;
}
}
}
| 5,903
| 37.588235
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ClassNewInstanceContextInterpreter.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import java.util.Iterator;
import java.util.Map;
/**
* An {@link SSAContextInterpreter} specialized to interpret Class.newInstance in a {@link
* JavaTypeContext} which represents the point-type of the class object created by the call.
*/
public class ClassNewInstanceContextInterpreter extends AbstractReflectionInterpreter {
public static final Atom newInstanceAtom = Atom.findOrCreateUnicodeAtom("newInstance");
private static final Descriptor classNewInstanceDescriptor =
Descriptor.findOrCreateUTF8("()Ljava/lang/Object;");
public static final MethodReference CLASS_NEW_INSTANCE_REF =
MethodReference.findOrCreate(
TypeReference.JavaLangClass, newInstanceAtom, classNewInstanceDescriptor);
private static final Atom defCtorAtom = Atom.findOrCreateUnicodeAtom("<init>");
private static final Descriptor defCtorDescriptor = Descriptor.findOrCreateUTF8("()V");
private static final Selector defCtorSelector = new Selector(defCtorAtom, defCtorDescriptor);
private final IClassHierarchy cha;
/* BEGIN Custom change: caching */
private final Map<String, IR> cache = HashMapFactory.make();
/* END Custom change: caching */
public ClassNewInstanceContextInterpreter(IClassHierarchy cha) {
this.cha = cha;
}
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
if (DEBUG) {
System.err.println("generating IR for " + node);
}
/* BEGIN Custom change: caching */
final Context context = node.getContext();
final IMethod method = node.getMethod();
final String hashKey = method.toString() + '@' + context.toString();
IR result = cache.get(hashKey);
if (result == null) {
result = makeIR(method, context);
cache.put(hashKey, result);
}
/* END Custom change: caching */
return result;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!node.getContext().isA(JavaTypeContext.class)) {
return false;
}
return node.getMethod().getReference().equals(CLASS_NEW_INSTANCE_REF);
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
Context context = node.getContext();
TypeReference tr = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getTypeReference();
if (tr != null) {
return new NonNullSingletonIterator<>(NewSiteReference.make(0, tr));
}
return EmptyIterator.instance();
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
assert understands(node);
return EmptyIterator.instance();
}
private IR makeIR(IMethod method, Context context) {
SSAInstructionFactory insts =
((TypeAbstraction) context.get(ContextKey.RECEIVER))
.getType()
.getClassLoader()
.getInstructionFactory();
TypeReference tr = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getTypeReference();
if (tr != null) {
SpecializedMethod m =
new SpecializedMethod(method, method.getDeclaringClass(), method.isStatic(), false);
IClass klass = cha.lookupClass(tr);
IMethod publicDefaultCtor = getPublicDefaultCtor(klass);
if (publicDefaultCtor != null) {
m.addStatementsForConcreteSimpleType(tr);
} else if (klass.getMethod(defCtorSelector) == null) {
TypeReference instantiationExceptionRef =
TypeReference.findOrCreateClass(
ClassLoaderReference.Primordial, "java/lang", "InstantiationException");
int xobj = method.getNumberOfParameters() + 1;
SSAInstruction newStatement =
insts.NewInstruction(
m.allInstructions.size(),
xobj,
NewSiteReference.make(2, instantiationExceptionRef));
m.addInstruction(tr, newStatement, true);
SSAInstruction throwStatement = insts.ThrowInstruction(m.allInstructions.size(), xobj);
m.addInstruction(tr, throwStatement, false);
} else {
TypeReference illegalAccessExceptionRef =
TypeReference.findOrCreateClass(
ClassLoaderReference.Primordial, "java/lang", "IllegalAccessException");
int xobj = method.getNumberOfParameters() + 1;
SSAInstruction newStatement =
insts.NewInstruction(
m.allInstructions.size(),
xobj,
NewSiteReference.make(2, illegalAccessExceptionRef));
m.addInstruction(tr, newStatement, true);
SSAInstruction throwStatement = insts.ThrowInstruction(m.allInstructions.size(), xobj);
m.addInstruction(tr, throwStatement, false);
}
SSAInstruction[] instrs = new SSAInstruction[m.allInstructions.size()];
m.allInstructions.<SSAInstruction>toArray(instrs);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
null);
}
return null;
}
private static IMethod getPublicDefaultCtor(IClass klass) {
IMethod ctorMethod = klass.getMethod(defCtorSelector);
if (ctorMethod != null && ctorMethod.isPublic() && ctorMethod.getDeclaringClass() == klass) {
return ctorMethod;
}
return null;
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 8,072
| 33.648069
| 97
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ClassNewInstanceContextSelector.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
/** A {@link ContextSelector} to intercept calls to Class.newInstance() */
class ClassNewInstanceContextSelector implements ContextSelector {
public ClassNewInstanceContextSelector() {}
/**
* If receiver is a {@link ConstantKey} whose value is an {@link IClass}, return a {@link
* JavaTypeContext} representing the type of the IClass. (This corresponds to the case where we
* know the exact type that will be allocated by the {@code Class.newInstance()} call.) Otherwise,
* return {@code null}.
*/
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (callee.getReference().equals(ClassNewInstanceContextInterpreter.CLASS_NEW_INSTANCE_REF)
&& isTypeConstant(receiver[0])) {
IClass c = (IClass) ((ConstantKey<?>) receiver[0]).getValue();
if (!c.isAbstract() && !c.isInterface()) {
return new JavaTypeContext(new PointType(c));
}
}
return null;
}
private static boolean isTypeConstant(InstanceKey instance) {
if (instance instanceof ConstantKey) {
ConstantKey<?> c = (ConstantKey<?>) instance;
if (c.getValue() instanceof IClass) {
return true;
}
}
return false;
}
private static final IntSet thisParameter = IntSetUtil.make(new int[] {0});
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (ClassNewInstanceContextInterpreter.CLASS_NEW_INSTANCE_REF.equals(
site.getDeclaredTarget())) {
return thisParameter;
} else {
return EmptyIntSet.instance;
}
}
}
| 2,609
| 35.25
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/CloneInterpreter.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.analysis.reflection;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.ArrayClass;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.CodeScanner;
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.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextUtil;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* A context interpreter for java.lang.Object.clone
*
* <p>TODO: The current implementation does not model CloneNotSupportedExceptions
*/
public class CloneInterpreter implements SSAContextInterpreter {
/** Comment for {@code cloneAtom} */
public static final Atom cloneAtom = Atom.findOrCreateUnicodeAtom("clone");
private static final Descriptor cloneDesc = Descriptor.findOrCreateUTF8("()Ljava/lang/Object;");
/** Comment for {@code CLONE} */
public static final MethodReference CLONE =
MethodReference.findOrCreate(TypeReference.JavaLangObject, cloneAtom, cloneDesc);
private static final TypeReference SYNTHETIC_SYSTEM =
TypeReference.findOrCreate(
ClassLoaderReference.Primordial,
TypeName.string2TypeName("Lcom/ibm/wala/model/java/lang/System"));
private static final Atom arraycopyAtom = Atom.findOrCreateUnicodeAtom("arraycopy");
private static final Descriptor arraycopyDesc =
Descriptor.findOrCreateUTF8("(Ljava/lang/Object;Ljava/lang/Object;)V");
private static final MethodReference SYNTHETIC_ARRAYCOPY =
MethodReference.findOrCreate(SYNTHETIC_SYSTEM, arraycopyAtom, arraycopyDesc);
/**
* If the type is an array, the program counter of the synthesized call to arraycopy. Doesn't
* really matter what it is.
*/
private static final int ARRAYCOPY_PC = 3;
private static final CallSiteReference ARRAYCOPY_SITE =
CallSiteReference.make(ARRAYCOPY_PC, SYNTHETIC_ARRAYCOPY, IInvokeInstruction.Dispatch.STATIC);
private static final int NEW_PC = 0;
/** Mapping from TypeReference -> IR TODO: Soft references? */
private final Map<TypeReference, IR> IRCache = HashMapFactory.make();
private final SSAInstructionFactory insts = Language.JAVA.instructionFactory();
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
IClass cls = ContextUtil.getConcreteClassFromContext(node.getContext());
IR result = IRCache.get(cls.getReference());
if (result == null) {
result = makeIR(node.getMethod(), node.getContext(), cls);
IRCache.put(cls.getReference(), result);
}
return result;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
return (node.getMethod().getReference().equals(CLONE)
&& ContextUtil.getConcreteClassFromContext(node.getContext()) != null);
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
IClass cls = ContextUtil.getConcreteClassFromContext(node.getContext());
return new NonNullSingletonIterator<>(NewSiteReference.make(NEW_PC, cls.getReference()));
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
assert understands(node);
return new NonNullSingletonIterator<>(ARRAYCOPY_SITE);
}
/**
* @return an array of statements that encode the behavior of the clone method for a given type.
*/
private SSAInstruction[] makeStatements(IClass klass) {
assert klass != null;
ArrayList<SSAInstruction> statements = new ArrayList<>();
// value number 1 is "this".
int nextLocal = 2;
int retValue = nextLocal++;
// value number of the result of the clone()
NewSiteReference ref = NewSiteReference.make(NEW_PC, klass.getReference());
SSANewInstruction N = null;
if (klass.isArrayClass()) {
int length = nextLocal++;
statements.add(insts.ArrayLengthInstruction(statements.size(), length, 1));
int[] sizes = new int[((ArrayClass) klass).getDimensionality()];
Arrays.fill(sizes, length);
N = insts.NewInstruction(statements.size(), retValue, ref, sizes);
} else {
N = insts.NewInstruction(statements.size(), retValue, ref);
}
statements.add(N);
int exceptionValue = nextLocal++;
if (klass.getReference().isArrayType()) {
// generate a synthetic arraycopy from this (v.n. 1) to the clone
int[] params = new int[2];
params[0] = 1;
params[1] = retValue;
SSAAbstractInvokeInstruction S =
insts.InvokeInstruction(statements.size(), params, exceptionValue, ARRAYCOPY_SITE, null);
statements.add(S);
} else {
// copy the fields over, one by one.
// TODO:
IClass k = klass;
while (k != null) {
for (IField f : klass.getDeclaredInstanceFields()) {
int tempValue = nextLocal++;
SSAGetInstruction G =
insts.GetInstruction(statements.size(), tempValue, 1, f.getReference());
statements.add(G);
SSAPutInstruction P =
insts.PutInstruction(statements.size(), retValue, tempValue, f.getReference());
statements.add(P);
}
k = k.getSuperclass();
}
}
SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), retValue, false);
statements.add(R);
return statements.toArray(new SSAInstruction[0]);
}
/** @return an IR that encodes the behavior of the clone method for a given type. */
private IR makeIR(IMethod method, Context context, IClass klass) {
assert klass != null;
SSAInstruction instrs[] = makeStatements(klass);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
null);
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
SSAInstruction[] statements = getIR(node).getInstructions();
return CodeScanner.getFieldsRead(statements).iterator();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
SSAInstruction[] statements = getIR(node).getInstructions();
return CodeScanner.getFieldsWritten(statements).iterator();
}
public Set<TypeReference> getCaughtExceptions(CGNode node) {
SSAInstruction[] statements = getIR(node).getInstructions();
return CodeScanner.getCaughtExceptions(statements);
}
public boolean hasObjectArrayLoad(CGNode node) {
SSAInstruction[] statements = getIR(node).getInstructions();
return CodeScanner.hasObjectArrayLoad(statements);
}
public boolean hasObjectArrayStore(CGNode node) {
SSAInstruction[] statements = getIR(node).getInstructions();
return CodeScanner.hasObjectArrayStore(statements);
}
public Iterator<TypeReference> iterateCastTypes(CGNode node) {
SSAInstruction[] statements = getIR(node).getInstructions();
return CodeScanner.iterateCastTypes(statements);
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 9,471
| 33.95203
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/FactoryBypassInterpreter.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.analysis.reflection;
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.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.ArrayClass;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.CodeScanner;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.SyntheticMethod;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.summaries.SummarizedMethod;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
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.debug.Assertions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Logic to interpret "factory" methods in context. */
public class FactoryBypassInterpreter extends AbstractReflectionInterpreter {
/**
* A Map from CallerSiteContext -> Set <TypeReference>represents the types a factory
* method might create in a particular context
*/
private final Map<Context, Set<TypeReference>> map = HashMapFactory.make();
/** A cache of synthetic method implementations, indexed by Context */
private final Map<Context, SpecializedFactoryMethod> syntheticMethodCache = HashMapFactory.make();
/** @param options governing analysis options */
public FactoryBypassInterpreter(AnalysisOptions options, IAnalysisCacheView iAnalysisCacheView) {
this.options = options;
this.cache = iAnalysisCacheView;
}
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (DEBUG) {
System.err.println("generating IR for " + node);
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
return cache.getIR(m, node.getContext());
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
private Set<TypeReference> getTypesForContext(Context context) {
// first try user spec
// XMLReflectionReader spec = (XMLReflectionReader) userSpec;
// if (spec != null && context instanceof CallerSiteContext) {
// CallerSiteContext site = (CallerSiteContext) context;
// MemberReference m = site.getCaller().getMethod().getReference();
// ReflectionSummary summary = spec.getSummary(m);
// if (summary != null) {
// Set<TypeReference> types =
// summary.getTypesForProgramLocation(site.getCallSite().getProgramCounter());
// if (types != null) {
// return types;
// }
// }
// }
Set<TypeReference> types = map.get(context);
return types;
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getNumberOfStatements(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public int getNumberOfStatements(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
return m.allInstructions.size();
}
/** @see com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#understands(CGNode) */
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (node.getMethod().isWalaSynthetic()) {
SyntheticMethod s = (SyntheticMethod) node.getMethod();
if (s.isFactoryMethod()) {
return getTypesForContext(node.getContext()) != null;
}
}
return false;
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
HashSet<NewSiteReference> result = HashSetFactory.make(5);
for (SSAInstruction ssaInstruction : m.getAllocationStatements()) {
SSANewInstruction s = (SSANewInstruction) ssaInstruction;
result.add(s.getNewSite());
}
return result.iterator();
}
public Iterator<SSAInstruction> getInvokeStatements(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
return m.getInvokeStatements().iterator();
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
final Iterator<SSAInstruction> I = getInvokeStatements(node);
return new Iterator<>() {
@Override
public boolean hasNext() {
return I.hasNext();
}
@Override
public CallSiteReference next() {
SSAInvokeInstruction s = (SSAInvokeInstruction) I.next();
return s.getCallSite();
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
public boolean recordType(IClassHierarchy cha, Context context, TypeReference type) {
Set<TypeReference> types = map.get(context);
if (types == null) {
types = HashSetFactory.make(2);
map.put(context, types);
}
if (!types.add(type)) {
return false;
} else {
// update any extant synthetic method
SpecializedFactoryMethod m = syntheticMethodCache.get(context);
if (m != null) {
TypeAbstraction T = typeRef2TypeAbstraction(cha, type);
m.addStatementsForTypeAbstraction(T);
cache.invalidate(m, context);
}
return true;
}
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#recordFactoryType(com.ibm.wala.ipa.callgraph.CGNode,
* com.ibm.wala.classLoader.IClass)
*/
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
if (klass == null) {
throw new IllegalArgumentException("klass is null");
}
if (node == null) {
throw new IllegalArgumentException("node is null");
}
return recordType(
node.getMethod().getClassHierarchy(), node.getContext(), klass.getReference());
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
try {
return CodeScanner.getFieldsRead(m).iterator();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
try {
return CodeScanner.getFieldsWritten(m).iterator();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
private SpecializedFactoryMethod findOrCreateSpecializedFactoryMethod(CGNode node) {
SpecializedFactoryMethod m = syntheticMethodCache.get(node.getContext());
if (m == null) {
Set<TypeReference> types = getTypesForContext(node.getContext());
m =
new SpecializedFactoryMethod(
(SummarizedMethod) node.getMethod(), node.getContext(), types);
syntheticMethodCache.put(node.getContext(), m);
}
return m;
}
public Set<TypeReference> getCaughtExceptions(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
try {
return CodeScanner.getCaughtExceptions(m);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
public boolean hasObjectArrayLoad(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
try {
return CodeScanner.hasObjectArrayLoad(m);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return false;
}
}
public boolean hasObjectArrayStore(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
try {
return CodeScanner.hasObjectArrayStore(m);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return false;
}
}
public Iterator<TypeReference> iterateCastTypes(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
try {
return CodeScanner.iterateCastTypes(m);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getCFG(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
// SpecializedFactoryMethod m = findOrCreateSpecializedFactoryMethod(node);
return cache.getDefUse(getIR(node));
}
protected class SpecializedFactoryMethod extends SpecializedMethod {
/** List of synthetic invoke instructions we model for this specialized instance. */
private final ArrayList<SSAInstruction> calls = new ArrayList<>();
/** The method being modelled */
private final IMethod method;
/** Context being modelled */
private final Context context;
/** next free local value number; */
private int nextLocal;
/** value number for integer constant 1 */
private int valueNumberForConstantOne = -1;
private final SSAInstructionFactory insts =
declaringClass.getClassLoader().getInstructionFactory();
private void initValueNumberForConstantOne() {
if (valueNumberForConstantOne == -1) {
valueNumberForConstantOne = nextLocal++;
}
}
protected SpecializedFactoryMethod(
final SummarizedMethod m, Context context, final Set<TypeReference> S) {
super(m, m.getDeclaringClass(), m.isStatic(), true);
this.context = context;
if (DEBUG) {
System.err.println(("Create SpecializedFactoryMethod " + m + S));
}
this.method = m;
assert S != null;
assert m.getDeclaringClass() != null : "null declaring class for " + m;
// add original statements from the method summary
nextLocal = addOriginalStatements(m);
for (TypeReference type : S) {
TypeAbstraction T = typeRef2TypeAbstraction(m.getClassHierarchy(), type);
addStatementsForTypeAbstraction(T);
}
}
protected void addStatementsForTypeAbstraction(TypeAbstraction T) {
if (DEBUG) {
System.err.println(("adding " + T + " to " + method));
}
T = interceptType(T);
if (T == null) {
return;
}
if ((T instanceof PointType) || (T instanceof ConeType)) {
TypeReference ref = T.getType().getReference();
NewSiteReference site = NewSiteReference.make(0, ref);
if (DEBUG) {
IClass klass = options.getClassTargetSelector().getAllocatedTarget(null, site);
System.err.println(("Selected allocated target: " + klass + " for " + T));
}
if (T instanceof PointType) {
if (!typesAllocated.contains(ref)) {
addStatementsForConcreteType(ref);
}
} else if (T instanceof ConeType) {
if (DEBUG) {
System.err.println(("Cone clause for " + T));
}
if (((ConeType) T).isInterface()) {
Set<IClass> implementors = T.getType().getClassHierarchy().getImplementors(ref);
if (DEBUG) {
System.err.println(("Implementors for " + T + ' ' + implementors));
}
if (implementors.isEmpty()) {
if (DEBUG) {
System.err.println(("Found no implementors of type " + T));
}
Warnings.add(NoSubtypesWarning.create(T));
}
if (implementors.size() > CONE_BOUND) {
Warnings.add(ManySubtypesWarning.create(T, implementors.size()));
}
addStatementsForSetOfTypes(implementors.iterator());
} else {
Collection<IClass> subclasses = T.getType().getClassHierarchy().computeSubClasses(ref);
if (DEBUG) {
System.err.println(("Subclasses for " + T + ' ' + subclasses));
}
if (subclasses.isEmpty()) {
if (DEBUG) {
System.err.println(("Found no subclasses of type " + T));
}
Warnings.add(NoSubtypesWarning.create(T));
}
if (subclasses.size() > CONE_BOUND) {
Warnings.add(ManySubtypesWarning.create(T, subclasses.size()));
}
addStatementsForSetOfTypes(subclasses.iterator());
}
} else {
Assertions.UNREACHABLE("Unexpected type " + T.getClass());
}
} else {
Assertions.UNREACHABLE("Unexpected type " + T.getClass());
}
}
private TypeAbstraction interceptType(TypeAbstraction T) {
TypeReference type = T.getType().getReference();
if (type.equals(TypeReference.JavaIoSerializable)) {
Warnings.add(IgnoreSerializableWarning.create());
return null;
} else {
return T;
}
}
/** Set up a method summary which allocates and returns an instance of concrete type T. */
private void addStatementsForConcreteType(final TypeReference T) {
int alloc = addStatementsForConcreteSimpleType(T);
if (alloc == -1) {
return;
}
if (T.isArrayType()) {
MethodReference init =
MethodReference.findOrCreate(
T, MethodReference.initAtom, MethodReference.defaultInitDesc);
CallSiteReference site =
CallSiteReference.make(
getCallSiteForType(T), init, IInvokeInstruction.Dispatch.SPECIAL);
int[] params = new int[1];
params[0] = alloc;
int exc = getExceptionsForType(T);
SSAAbstractInvokeInstruction s =
insts.InvokeInstruction(allInstructions.size(), params, exc, site, null);
calls.add(s);
allInstructions.add(s);
}
}
private int addOriginalStatements(SummarizedMethod m) {
SSAInstruction[] original = m.getStatements(options.getSSAOptions());
// local value number 1 is "this", so the next free value number is 2
int nextLocal = 2;
for (SSAInstruction s : original) {
allInstructions.add(s);
if (s instanceof SSAInvokeInstruction) {
calls.add(s);
}
if (s instanceof SSANewInstruction) {
allocations.add(s);
}
for (int j = 0; j < s.getNumberOfDefs(); j++) {
int def = s.getDef(j);
if (def >= nextLocal) {
nextLocal = def + 1;
}
}
for (int j = 0; j < s.getNumberOfUses(); j++) {
int use = s.getUse(j);
if (use >= nextLocal) {
nextLocal = use + 1;
}
}
}
return nextLocal;
}
private void addStatementsForSetOfTypes(Iterator<IClass> it) {
if (!it.hasNext()) { // Uh. No types. Hope the caller reported a warning.
SSAReturnInstruction r = insts.ReturnInstruction(allInstructions.size(), nextLocal, false);
allInstructions.add(r);
}
for (IClass klass : Iterator2Iterable.make(it)) {
TypeReference T = klass.getReference();
if (klass.isAbstract() || klass.isInterface() || typesAllocated.contains(T)) {
continue;
}
typesAllocated.add(T);
int i = getLocalForType(T);
NewSiteReference ref = NewSiteReference.make(getNewSiteForType(T), T);
SSANewInstruction a = null;
if (T.isArrayType()) {
int[] sizes = new int[((ArrayClass) klass).getDimensionality()];
initValueNumberForConstantOne();
Arrays.fill(sizes, valueNumberForConstantOne);
a = insts.NewInstruction(allInstructions.size(), i, ref, sizes);
} else {
a = insts.NewInstruction(allInstructions.size(), i, ref);
}
allocations.add(a);
allInstructions.add(a);
SSAReturnInstruction r = insts.ReturnInstruction(allInstructions.size(), i, false);
allInstructions.add(r);
MethodReference init =
MethodReference.findOrCreate(
T, MethodReference.initAtom, MethodReference.defaultInitDesc);
CallSiteReference site =
CallSiteReference.make(
getCallSiteForType(T), init, IInvokeInstruction.Dispatch.SPECIAL);
int[] params = new int[1];
params[0] = i;
SSAAbstractInvokeInstruction s =
insts.InvokeInstruction(
allInstructions.size(), params, getExceptionsForType(T), site, null);
calls.add(s);
allInstructions.add(s);
}
}
public List<SSAInstruction> getAllocationStatements() {
return allocations;
}
public List<SSAInstruction> getInvokeStatements() {
return calls;
}
/**
* Two specialized methods can be different, even if they represent the same source method. So,
* revert to object identity for testing equality. TODO: this is non-optimal; could try to
* re-use specialized methods that have the same context.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public int hashCode() { // TODO: change this to avoid non-determinism!
return System.identityHashCode(this);
}
@Override
public String toString() {
return super.toString();
}
@Override
public SSAInstruction[] getStatements() {
SSAInstruction[] result = new SSAInstruction[allInstructions.size()];
int i = 0;
for (SSAInstruction ssaInstruction : allInstructions) {
result[i++] = ssaInstruction;
}
return result;
}
@Override
public IClass getDeclaringClass() {
assert method.getDeclaringClass() != null
: "null declaring class for original method " + method;
return method.getDeclaringClass();
}
@Override
public int getNumberOfParameters() {
return method.getNumberOfParameters();
}
@Override
public TypeReference getParameterType(int i) {
return method.getParameterType(i);
}
@Override
public IR makeIR(Context C, SSAOptions options) {
SSAInstruction[] instrs = getStatements();
Map<Integer, ConstantValue> constants = null;
if (valueNumberForConstantOne > -1) {
constants = HashMapFactory.make(1);
constants.put(valueNumberForConstantOne, new ConstantValue(Integer.valueOf(1)));
}
return new SyntheticIR(
this, context, new InducedCFG(instrs, this, context), instrs, options, constants);
}
}
}
| 21,345
| 32.775316
| 126
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/FactoryContextSelector.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.analysis.reflection;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.SyntheticMethod;
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.CallString;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallStringContext;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
/** For synthetic methods marked as "Factories", we analyze in a context defined by the caller. */
class FactoryContextSelector implements ContextSelector {
public FactoryContextSelector() {}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (callee == null) {
throw new IllegalArgumentException("callee is null");
}
if (callee.isWalaSynthetic()) {
SyntheticMethod s = (SyntheticMethod) callee;
if (s.isFactoryMethod()) {
return new CallStringContext(new CallString(site, caller.getMethod()));
}
}
return null;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return EmptyIntSet.instance;
}
}
| 1,759
| 34.2
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/GetClassContextInterpeter.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
/**
* {@link SSAContextInterpreter} specialized to interpret Object.getClass() in a {@link
* JavaTypeContext}
*/
public class GetClassContextInterpeter implements SSAContextInterpreter {
/* BEGIN Custom change: caching */
private final Map<String, IR> cache = HashMapFactory.make();
/* END Custom change: caching */
private static final boolean DEBUG = false;
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
if (DEBUG) {
System.err.println("generating IR for " + node);
}
/* BEGIN Custom change: caching */
final Context context = node.getContext();
final IMethod method = node.getMethod();
final String hashKey = method.toString() + '@' + context.toString();
IR result = cache.get(hashKey);
if (result == null) {
result = makeIR(method, context);
cache.put(hashKey, result);
}
/* END Custom change: caching */
return result;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!node.getContext().isA(JavaTypeContext.class)) {
return false;
}
return node.getMethod().getReference().equals(GetClassContextSelector.GET_CLASS);
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
return EmptyIterator.instance();
}
private static SSAInstruction[] makeStatements(Context context) {
ArrayList<SSAInstruction> statements = new ArrayList<>();
int nextLocal = 2;
int retValue = nextLocal++;
TypeReference tr = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getTypeReference();
SSAInstructionFactory insts =
((TypeAbstraction) context.get(ContextKey.RECEIVER))
.getType()
.getClassLoader()
.getInstructionFactory();
if (tr != null) {
SSALoadMetadataInstruction l =
insts.LoadMetadataInstruction(
statements.size(), retValue, TypeReference.JavaLangClass, tr);
statements.add(l);
SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), retValue, false);
statements.add(R);
}
return statements.toArray(new SSAInstruction[0]);
}
private static IR makeIR(IMethod method, Context context) {
SSAInstruction instrs[] = makeStatements(context);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
null);
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 5,135
| 29.571429
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/GetClassContextSelector.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
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.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
/** A {@link ContextSelector} to intercept calls to Object.getClass() */
public class GetClassContextSelector implements ContextSelector {
public static final MethodReference GET_CLASS =
MethodReference.findOrCreate(TypeReference.JavaLangObject, "getClass", "()Ljava/lang/Class;");
public GetClassContextSelector() {}
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (callee.getReference().equals(GET_CLASS)) {
return new JavaTypeContext(new PointType(receiver[0].getConcreteType()));
}
return null;
}
private static final IntSet thisParameter = IntSetUtil.make(new int[] {0});
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (site.getDeclaredTarget().equals(GET_CLASS)) {
return thisParameter;
} else {
return EmptyIntSet.instance;
}
}
}
| 1,901
| 34.222222
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/GetMethodContext.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
/**
* A context which may be used if
*
* <ul>
* <li>the method to be interpreted is either {@link java.lang.Class#getMethod(String, Class...)}
* or {@link java.lang.Class#getDeclaredMethod(String, Class...)},
* <li>the type of the "this" argument is known and
* <li>the value of the first argument (the method name) is a constant.
* </ul>
*
* In the special case described above, {@link GetMethodContextInterpreter} and {@link
* GetMethodContextSelector} should be preferred over {@link JavaLangClassContextInterpreter} and
* {@link JavaLangClassContextSelector}, as {@link GetMethodContextInterpreter} and {@link
* GetMethodContextSelector} drastically reduce the number of methods returned increasing the
* precision of the analysis. Thus, {@link GetMethodContextInterpreter} and {@link
* GetMethodContextSelector} should be placed in be placed in front of {@link
* JavaLangClassContextInterpreter} and {@link JavaLangClassContextSelector} .
*
* @author Michael Heilmann
* @see com.ibm.wala.analysis.reflection.GetMethodContextInterpreter
* @see com.ibm.wala.analysis.reflection.GetMethodContextSelector TODO Do the same for {@link
* Class#getField(String)} and {@link Class#getDeclaredField(String)}.
*/
public class GetMethodContext implements Context {
/** The type abstraction. */
private final TypeAbstraction type;
/** The method name. */
private final ConstantKey<String> name;
/**
* Construct this GetMethodContext.
*
* @param type the type
* @param name the name of the method
*/
public GetMethodContext(TypeAbstraction type, ConstantKey<String> name) {
if (type == null) {
throw new IllegalArgumentException("null == type");
}
this.type = type;
if (name == null) {
throw new IllegalArgumentException("null == name");
}
this.name = name;
}
class NameItem implements ContextItem {
String name() {
return getName();
}
};
@Override
public ContextItem get(ContextKey name) {
if (name == ContextKey.RECEIVER) {
return type;
} else if (name == ContextKey.NAME) {
return new NameItem();
} else if (name == ContextKey.PARAMETERS[0]) {
if (type instanceof PointType) {
IClass cls = ((PointType) type).getIClass();
return new FilteredPointerKey.SingleClassFilter(cls);
} else {
return null;
}
} else if (name == ContextKey.PARAMETERS[1]) {
return new FilteredPointerKey.SingleClassFilter(this.name.getConcreteType());
} else {
return null;
}
}
@Override
public String toString() {
return "GetMethodContext<" + type + ", " + name + '>';
}
@Override
public int hashCode() {
return 6367 * type.hashCode() * name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
GetMethodContext other = (GetMethodContext) obj;
return type.equals(other.type) && name.equals(other.name);
} else {
return false;
}
}
/**
* Get the type.
*
* @return the type
*/
public TypeAbstraction getType() {
return type;
}
/**
* Get the name.
*
* @return the name
*/
public String getName() {
return name.getValue();
}
}
| 4,141
| 29.233577
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/GetMethodContextInterpreter.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.analysis.reflection;
import com.ibm.wala.analysis.reflection.GetMethodContext.NameItem;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.debug.Assertions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* Understands {@link com.ibm.wala.analysis.reflection.GetMethodContext}.
*
* @author Michael Heilmann
* @see com.ibm.wala.analysis.reflection.GetMethodContext
* @see com.ibm.wala.analysis.reflection.GetMethodContextSelector
*/
public class GetMethodContextInterpreter implements SSAContextInterpreter {
/** TODO MH: Maybe hard-code those in {@link com.ibm.wala.types.MethodReference}? */
public static final MethodReference GET_METHOD =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getMethod",
"(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
/** TODO MH: Maybe hard-code those in {@link com.ibm.wala.types.MethodReference}? */
public static final MethodReference GET_DECLARED_METHOD =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getDeclaredMethod",
"(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
private static final boolean DEBUG = false;
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
if (DEBUG) {
System.err.println("generating IR for " + node);
}
IMethod method = node.getMethod();
Context context = node.getContext();
Map<Integer, ConstantValue> constants = HashMapFactory.make();
if (method.getReference().equals(GET_METHOD)) {
Atom name = Atom.findOrCreateAsciiAtom(((NameItem) context.get(ContextKey.NAME)).name());
SSAInstruction instrs[] = makeGetMethodStatements(context, constants, name);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_DECLARED_METHOD)) {
Atom name = Atom.findOrCreateAsciiAtom(((NameItem) context.get(ContextKey.NAME)).name());
SSAInstruction instrs[] = makeGetDeclaredMethodStatements(context, constants, name);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
Assertions.UNREACHABLE("Unexpected method " + node);
return null;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!node.getContext().isA(GetMethodContext.class)) {
return false;
}
MethodReference mRef = node.getMethod().getReference();
return mRef.equals(GET_METHOD) || mRef.equals(GET_DECLARED_METHOD);
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
GetMethodContext context = (GetMethodContext) node.getContext();
TypeReference tr = context.getType().getTypeReference();
if (tr != null) {
return new NonNullSingletonIterator<>(NewSiteReference.make(0, tr));
}
return EmptyIterator.instance();
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
assert understands(node);
return EmptyIterator.instance();
}
/**
* Get all non-constructor, non-class-initializer methods declared by a class if their name is
* equal to the specified name.
*
* @param cls the class
* @param name the name
*/
private static Collection<IMethod> getDeclaredNormalMethods(IClass cls, Atom name) {
Collection<IMethod> result = HashSetFactory.make();
for (IMethod m : cls.getDeclaredMethods()) {
if (!m.isInit() && !m.isClinit() && m.getSelector().getName().equals(name)) {
result.add(m);
}
}
return result;
}
/**
* Get all non-constructor, non-class-initializer methods declared by a class and all its
* superclasses if their name is equal to the specified name.
*
* @param cls the class
* @param name the name
*/
private static Collection<IMethod> getAllNormalPublicMethods(IClass cls, Atom name) {
Collection<IMethod> result = HashSetFactory.make();
Collection<? extends IMethod> allMethods = cls.getAllMethods();
for (IMethod m : allMethods) {
if (!m.isInit() && !m.isClinit() && m.isPublic() && m.getSelector().getName().equals(name)) {
result.add(m);
}
}
return result;
}
/**
* Create statements for methods like getMethod() and getDeclaredMethod(), which return a single
* method. This creates a return statement for each possible return value, each of which is a
* {@link ConstantValue} for an {@link IMethod}.
*
* @param returnValues the possible return values for this method
* @return the statements
*/
private static SSAInstruction[] getParticularMethodStatements(
MethodReference ref,
Collection<IMethod> returnValues,
Context context,
Map<Integer, ConstantValue> constants) {
ArrayList<SSAInstruction> statements = new ArrayList<>();
int nextLocal = ref.getNumberOfParameters() + 2;
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
SSAInstructionFactory insts =
((TypeAbstraction) context.get(ContextKey.RECEIVER))
.getType()
.getClassLoader()
.getInstructionFactory();
if (cls != null) {
for (IMethod m : returnValues) {
int c = nextLocal++;
constants.put(c, new ConstantValue(m));
SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), c, false);
statements.add(R);
}
} else {
// SJF: This is incorrect. TODO: fix and enable.
// SSAThrowInstruction t = insts.ThrowInstruction(retValue);
// statements.add(t);
}
return statements.toArray(new SSAInstruction[0]);
}
private static SSAInstruction[] makeGetMethodStatements(
Context context, Map<Integer, ConstantValue> constants, Atom name) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getParticularMethodStatements(GET_METHOD, null, context, constants);
} else {
return getParticularMethodStatements(
GET_METHOD, getAllNormalPublicMethods(cls, name), context, constants);
}
}
/** Create statements for {@link Class#getDeclaredMethod(String, Class...)}. */
private static SSAInstruction[] makeGetDeclaredMethodStatements(
Context context, Map<Integer, ConstantValue> constants, Atom name) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getParticularMethodStatements(GET_DECLARED_METHOD, null, context, constants);
} else {
return getParticularMethodStatements(
GET_DECLARED_METHOD, getDeclaredNormalMethods(cls, name), context, constants);
}
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 9,725
| 34.49635
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/GetMethodContextSelector.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import java.util.Arrays;
import java.util.Collection;
/**
* Produces {@link com.ibm.wala.analysis.reflection.GetMethodContext} if appropriate.
*
* @author Michael Heilmann
* @see com.ibm.wala.analysis.reflection.GetMethodContext
* @see com.ibm.wala.analysis.reflection.GetMethodContextInterpreter
*/
public class GetMethodContextSelector implements ContextSelector {
/** If {@code true}, debug information is emitted. */
protected static final boolean DEBUG = false;
/** whether to only follow get method calls on application classes, ignoring system ones */
private final boolean applicationClassesOnly;
public GetMethodContextSelector(boolean applicationClassesOnly) {
this.applicationClassesOnly = applicationClassesOnly;
}
/**
* If
*
* <ul>
* <li>the {@link CallSiteReference} invokes either {@link java.lang.Class#getMethod} or {@link
* java.lang.Class#getDeclaredMethod},
* <li>and the receiver is a type constant and
* <li>the first argument is a constant,
* </ul>
*
* then return a {@code GetMethodContextSelector}.
*/
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (receiver != null && receiver.length > 0 && mayUnderstand(callee, receiver[0])) {
if (DEBUG) {
System.out.print("site := " + site + ", receiver := " + receiver[0]);
}
// If the first argument is a constant ...
IR ir = caller.getIR();
SymbolTable symbolTable = ir.getSymbolTable();
SSAAbstractInvokeInstruction[] invokeInstructions = caller.getIR().getCalls(site);
if (invokeInstructions.length != 1) {
return null;
}
int use = invokeInstructions[0].getUse(1);
if (symbolTable.isStringConstant(invokeInstructions[0].getUse(1))) {
String sym = symbolTable.getStringValue(use);
if (DEBUG) {
System.out.println(Arrays.toString(invokeInstructions));
System.out.println(", with constant := `" + sym + '`');
for (InstanceKey instanceKey : receiver) {
System.out.println(" " + instanceKey);
}
}
// ... return an GetMethodContext.
ConstantKey<String> ck = makeConstantKey(caller.getClassHierarchy(), sym);
if (DEBUG) {
System.out.println(ck);
}
IClass type = getTypeConstant(receiver[0]);
if (!applicationClassesOnly
|| !(type.getClassLoader().getReference().equals(ClassLoaderReference.Primordial)
|| type.getClassLoader().getReference().equals(ClassLoaderReference.Extension))) {
return new GetMethodContext(new PointType(type), ck);
}
}
if (DEBUG) {
System.out.println(", with constant := no");
}
// Otherwise, return null.
// TODO Remove this, just fall-through.
return null;
}
return null;
}
/**
* If {@code instance} is a {@link ConstantKey} and its value is an instance of {@link IClass},
* return that value. Otherwise, return {@code null}.
*/
private static IClass getTypeConstant(InstanceKey instance) {
if (instance instanceof ConstantKey) {
ConstantKey<?> c = (ConstantKey<?>) instance;
if (c.getValue() instanceof IClass) {
return (IClass) c.getValue();
}
}
return null;
}
/**
* Create a constant key for a string.
*
* @param cha the class hierarchy
* @param str the string
* @return the constant key
*/
protected static ConstantKey<String> makeConstantKey(IClassHierarchy cha, String str) {
IClass cls = cha.lookupClass(TypeReference.JavaLangString);
ConstantKey<String> ck = new ConstantKey<>(str, cls);
return ck;
}
private static final Collection<MethodReference> UNDERSTOOD_METHOD_REFS = HashSetFactory.make();
static {
UNDERSTOOD_METHOD_REFS.add(GetMethodContextInterpreter.GET_METHOD);
UNDERSTOOD_METHOD_REFS.add(GetMethodContextInterpreter.GET_DECLARED_METHOD);
}
/**
* This object understands a dispatch to {@link java.lang.Class#getMethod(String, Class...)} or
* {@link java.lang.Class#getDeclaredMethod} when the receiver is a type constant.
*/
private static boolean mayUnderstand(IMethod targetMethod, InstanceKey instance) {
return UNDERSTOOD_METHOD_REFS.contains(targetMethod.getReference())
&& getTypeConstant(instance) != null;
}
/**
* TODO MH: Shouldn't be the first TWO parameters be relevant? Documentation is not too helpful
* about the implications.
*/
private static final IntSet thisParameter = IntSetUtil.make(new int[] {0});
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (UNDERSTOOD_METHOD_REFS.contains(site.getDeclaredTarget())) {
return thisParameter;
} else {
return EmptyIntSet.instance;
}
}
}
| 6,234
| 35.25
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/IllegalArgumentExceptionContext.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.analysis.reflection;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextKey;
public class IllegalArgumentExceptionContext implements Context {
@Override
public ContextItem get(ContextKey name) {
return null;
}
}
| 694
| 27.958333
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/InstanceKeyWithNode.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.analysis.reflection;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
/** An instance key which has an associated {@link CGNode}. */
public interface InstanceKeyWithNode extends InstanceKey {
/** @return the node which created this instance. */
CGNode getNode();
}
| 720
| 31.772727
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/JavaLangClassContextInterpreter.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.debug.Assertions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* An {@link SSAContextInterpreter} specialized to interpret methods on java.lang.Class in a {@link
* JavaTypeContext} which represents the point-type of the class object created by the call.
*
* <p>Currently supported methods:
*
* <ul>
* <li>getConstructor
* <li>getConstructors
* <li>getMethod
* <li>getMethods
* <li>getDeclaredConstructor
* <li>getDeclaredConstructors
* <li>getDeclaredMethod
* <li>getDeclaredMethods
* </ul>
*/
public class JavaLangClassContextInterpreter implements SSAContextInterpreter {
public static final MethodReference GET_CONSTRUCTOR =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getConstructor",
"([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;");
public static final MethodReference GET_CONSTRUCTORS =
MethodReference.findOrCreate(
TypeReference.JavaLangClass, "getConstructors", "()[Ljava/lang/reflect/Constructor;");
public static final MethodReference GET_METHOD =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getMethod",
"(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
public static final MethodReference GET_METHODS =
MethodReference.findOrCreate(
TypeReference.JavaLangClass, "getMethods", "()[Ljava/lang/reflect/Method;");
public static final MethodReference GET_DECLARED_CONSTRUCTOR =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getDeclaredConstructor",
"([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;");
public static final MethodReference GET_DECLARED_CONSTRUCTORS =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getDeclaredConstructors",
"()[Ljava/lang/reflect/Constructor;");
public static final MethodReference GET_DECLARED_METHOD =
MethodReference.findOrCreate(
TypeReference.JavaLangClass,
"getDeclaredMethod",
"(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;");
public static final MethodReference GET_DECLARED_METHODS =
MethodReference.findOrCreate(
TypeReference.JavaLangClass, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;");
private static final boolean DEBUG = false;
/* BEGIN Custom change: caching */
private final Map<String, IR> cache = HashMapFactory.make();
/* END Custom change: caching */
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
if (DEBUG) {
System.err.println("generating IR for " + node);
}
/* BEGIN Custom change: caching */
final Context context = node.getContext();
final IMethod method = node.getMethod();
final String hashKey = method.toString() + '@' + context.toString();
IR result = cache.get(hashKey);
if (result == null) {
result = makeIR(method, context);
if (result == null) {
Assertions.UNREACHABLE("Unexpected method " + node);
}
cache.put(hashKey, result);
}
return result;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
private static IR makeIR(IMethod method, Context context) {
Map<Integer, ConstantValue> constants = HashMapFactory.make();
if (method.getReference().equals(GET_CONSTRUCTOR)) {
SSAInstruction instrs[] = makeGetCtorStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_CONSTRUCTORS)) {
SSAInstruction instrs[] = makeGetCtorsStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_METHOD)) {
SSAInstruction instrs[] = makeGetMethodStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_METHODS)) {
SSAInstruction instrs[] = makeGetMethodsStatments(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_DECLARED_CONSTRUCTOR)) {
SSAInstruction instrs[] = makeGetDeclCtorStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_DECLARED_CONSTRUCTORS)) {
SSAInstruction instrs[] = makeGetDeclCtorsStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_DECLARED_METHOD)) {
SSAInstruction instrs[] = makeGetDeclaredMethodStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
if (method.getReference().equals(GET_DECLARED_METHODS)) {
SSAInstruction instrs[] = makeGetDeclaredMethodsStatements(context, constants);
return new SyntheticIR(
method,
context,
new InducedCFG(instrs, method, context),
instrs,
SSAOptions.defaultOptions(),
constants);
}
Assertions.UNREACHABLE("Unexpected method " + method);
return null;
}
/* END Custom change: caching */
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#understands(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!node.getContext().isA(JavaTypeContext.class)) {
return false;
}
MethodReference mRef = node.getMethod().getReference();
return mRef.equals(GET_CONSTRUCTOR)
|| mRef.equals(GET_CONSTRUCTORS)
|| mRef.equals(GET_METHOD)
|| mRef.equals(GET_METHODS)
|| mRef.equals(GET_DECLARED_CONSTRUCTOR)
|| mRef.equals(GET_DECLARED_CONSTRUCTORS)
|| mRef.equals(GET_DECLARED_METHOD)
|| mRef.equals(GET_DECLARED_METHODS);
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
Context context = node.getContext();
TypeReference tr = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getTypeReference();
if (tr != null) {
return new NonNullSingletonIterator<>(NewSiteReference.make(0, tr));
}
return EmptyIterator.instance();
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
assert understands(node);
return EmptyIterator.instance();
}
/** Get all non-constructor, non-class-initializer methods declared by a class */
private static Collection<IMethod> getDeclaredNormalMethods(IClass cls) {
Collection<IMethod> result = HashSetFactory.make();
for (IMethod m : cls.getDeclaredMethods()) {
if (!m.isInit() && !m.isClinit()) {
result.add(m);
}
}
return result;
}
/**
* Get all non-constructor, non-class-initializer methods declared by a class and all its
* superclasses
*/
private static Collection<IMethod> getAllNormalPublicMethods(IClass cls) {
Collection<IMethod> result = HashSetFactory.make();
Collection<? extends IMethod> allMethods = cls.getAllMethods();
for (IMethod m : allMethods) {
if (!m.isInit() && !m.isClinit() && m.isPublic()) {
result.add(m);
}
}
return result;
}
/** Get all the constructors of a class */
private static Collection<IMethod> getConstructors(IClass cls) {
Collection<IMethod> result = HashSetFactory.make();
for (IMethod m : cls.getDeclaredMethods()) {
if (m.isInit()) {
result.add(m);
}
}
return result;
}
/** Get all the public constructors of a class */
private static Collection<IMethod> getPublicConstructors(IClass cls) {
Collection<IMethod> result = HashSetFactory.make();
for (IMethod m : cls.getDeclaredMethods()) {
if (m.isInit() && m.isPublic()) {
result.add(m);
}
}
return result;
}
/**
* create statements for methods like getConstructors() and getMethods(), which return an array of
* methods.
*
* @param returnValues the possible return values for this method.
*/
private static SSAInstruction[] getMethodArrayStatements(
MethodReference ref,
Collection<IMethod> returnValues,
Context context,
Map<Integer, ConstantValue> constants) {
ArrayList<SSAInstruction> statements = new ArrayList<>();
int nextLocal = ref.getNumberOfParameters() + 2;
int retValue = nextLocal++;
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
SSAInstructionFactory insts =
((TypeAbstraction) context.get(ContextKey.RECEIVER))
.getType()
.getClassLoader()
.getInstructionFactory();
if (cls != null) {
TypeReference arrType = ref.getReturnType();
NewSiteReference site = new NewSiteReference(retValue, arrType);
int sizeVn = nextLocal++;
constants.put(sizeVn, new ConstantValue(returnValues.size()));
SSANewInstruction allocArr =
insts.NewInstruction(statements.size(), retValue, site, new int[] {sizeVn});
statements.add(allocArr);
int i = 0;
for (IMethod m : returnValues) {
int c = nextLocal++;
constants.put(c, new ConstantValue(m));
int index = i++;
int indexVn = nextLocal++;
constants.put(indexVn, new ConstantValue(index));
SSAArrayStoreInstruction store =
insts.ArrayStoreInstruction(
statements.size(), retValue, indexVn, c, TypeReference.JavaLangReflectConstructor);
statements.add(store);
}
SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), retValue, false);
statements.add(R);
} else {
// SJF: This is incorrect. TODO: fix and enable.
// SSAThrowInstruction t = insts.ThrowInstruction(retValue);
// statements.add(t);
}
return statements.toArray(new SSAInstruction[0]);
}
/**
* create statements for methods like getConstructor() and getDeclaredMethod(), which return a
* single method. This creates a return statement for each possible return value, each of which is
* a {@link ConstantValue} for an {@link IMethod}.
*
* @param returnValues the possible return values for this method.
*/
private static SSAInstruction[] getParticularMethodStatements(
MethodReference ref,
Collection<IMethod> returnValues,
Context context,
Map<Integer, ConstantValue> constants) {
ArrayList<SSAInstruction> statements = new ArrayList<>();
int nextLocal = ref.getNumberOfParameters() + 2;
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
SSAInstructionFactory insts =
((TypeAbstraction) context.get(ContextKey.RECEIVER))
.getType()
.getClassLoader()
.getInstructionFactory();
if (cls != null) {
for (IMethod m : returnValues) {
int c = nextLocal++;
constants.put(c, new ConstantValue(m));
SSAReturnInstruction R = insts.ReturnInstruction(statements.size(), c, false);
statements.add(R);
}
} else {
// SJF: This is incorrect. TODO: fix and enable.
// SSAThrowInstruction t = insts.ThrowInstruction(retValue);
// statements.add(t);
}
return statements.toArray(new SSAInstruction[0]);
}
/** create statements for getConstructor() */
private static SSAInstruction[] makeGetCtorStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getParticularMethodStatements(GET_CONSTRUCTOR, null, context, constants);
} else {
return getParticularMethodStatements(
GET_CONSTRUCTOR, getPublicConstructors(cls), context, constants);
}
}
// TODO
private static SSAInstruction[] makeGetCtorsStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getMethodArrayStatements(GET_DECLARED_CONSTRUCTORS, null, context, constants);
} else {
return getMethodArrayStatements(
GET_DECLARED_CONSTRUCTORS, getPublicConstructors(cls), context, constants);
}
}
private static SSAInstruction[] makeGetMethodStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getParticularMethodStatements(GET_METHOD, null, context, constants);
} else {
return getParticularMethodStatements(
GET_METHOD, getAllNormalPublicMethods(cls), context, constants);
}
}
private static SSAInstruction[] makeGetMethodsStatments(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getMethodArrayStatements(GET_METHODS, null, context, constants);
} else {
return getMethodArrayStatements(
GET_METHODS, getAllNormalPublicMethods(cls), context, constants);
}
}
/** create statements for getConstructor() */
private static SSAInstruction[] makeGetDeclCtorStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getParticularMethodStatements(GET_DECLARED_CONSTRUCTOR, null, context, constants);
} else {
return getParticularMethodStatements(
GET_DECLARED_CONSTRUCTOR, getConstructors(cls), context, constants);
}
}
private static SSAInstruction[] makeGetDeclCtorsStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getMethodArrayStatements(GET_DECLARED_CONSTRUCTORS, null, context, constants);
} else {
return getMethodArrayStatements(
GET_DECLARED_CONSTRUCTORS, getConstructors(cls), context, constants);
}
}
/** create statements for getDeclaredMethod() */
private static SSAInstruction[] makeGetDeclaredMethodStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getParticularMethodStatements(GET_DECLARED_METHOD, null, context, constants);
} else {
return getParticularMethodStatements(
GET_DECLARED_METHOD, getDeclaredNormalMethods(cls), context, constants);
}
}
/** create statements for getDeclaredMethod() */
private static SSAInstruction[] makeGetDeclaredMethodsStatements(
Context context, Map<Integer, ConstantValue> constants) {
IClass cls = ((TypeAbstraction) context.get(ContextKey.RECEIVER)).getType();
if (cls == null) {
return getMethodArrayStatements(GET_DECLARED_METHODS, null, context, constants);
} else {
return getMethodArrayStatements(
GET_DECLARED_METHODS, getDeclaredNormalMethods(cls), context, constants);
}
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 19,100
| 34.569832
| 120
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/JavaLangClassContextSelector.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import java.util.Collection;
/**
* A {@link ContextSelector} to intercept calls to certain methods on java.lang.Class when the
* receiver is a type constant
*
* <p>Currently supported methods:
*
* <ul>
* <li>getConstructor
* <li>getConstructors
* <li>getDeclaredMethod
* <li>getMethods
* </ul>
*/
class JavaLangClassContextSelector implements ContextSelector {
public JavaLangClassContextSelector() {}
/**
* If the {@link CallSiteReference} invokes a method we understand and c is a type constant,
* return a {@link JavaTypeContext} representing the type named by s, if we can resolve it in the
* {@link IClassHierarchy}.
*/
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (receiver != null && receiver.length > 0 && mayUnderstand(callee, receiver[0])) {
return new JavaTypeContext(new PointType(getTypeConstant(receiver[0])));
}
return null;
}
private static IClass getTypeConstant(InstanceKey instance) {
if (instance instanceof ConstantKey) {
ConstantKey<?> c = (ConstantKey<?>) instance;
if (c.getValue() instanceof IClass) {
return (IClass) c.getValue();
}
}
return null;
}
private static final Collection<MethodReference> UNDERSTOOD_METHOD_REFS = HashSetFactory.make();
static {
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_CONSTRUCTOR);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_CONSTRUCTORS);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_METHOD);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_METHODS);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_DECLARED_CONSTRUCTOR);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_DECLARED_CONSTRUCTORS);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_DECLARED_METHOD);
UNDERSTOOD_METHOD_REFS.add(JavaLangClassContextInterpreter.GET_DECLARED_METHODS);
}
/**
* This object may understand a dispatch to Class.getContructor when the receiver is a type
* constant.
*/
private static boolean mayUnderstand(IMethod targetMethod, InstanceKey instance) {
return UNDERSTOOD_METHOD_REFS.contains(targetMethod.getReference())
&& getTypeConstant(instance) != null;
}
private static final IntSet thisParameter = IntSetUtil.make(new int[] {0});
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (UNDERSTOOD_METHOD_REFS.contains(site.getDeclaredTarget())) {
return thisParameter;
} else {
return EmptyIntSet.instance;
}
}
}
| 3,831
| 35.846154
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/JavaTypeContext.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.analysis.reflection;
import com.ibm.wala.analysis.typeInference.PointType;
import com.ibm.wala.analysis.typeInference.TypeAbstraction;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.FilteredPointerKey;
/**
* Implements a Context which corresponds to a given type abstraction. Thus, this maps the name
* "TYPE" to a JavaTypeAbstraction. TODO This context maps {@link
* com.ibm.wala.ipa.callgraph.ContextKey#RECEIVER} to a {@link TypeAbstraction}.
*/
public class JavaTypeContext implements Context {
private final TypeAbstraction type;
public JavaTypeContext(TypeAbstraction type) {
if (type == null) {
throw new IllegalArgumentException("null type");
}
this.type = type;
}
@Override
public ContextItem get(ContextKey name) {
if (name == ContextKey.RECEIVER) {
return type;
} else if (name == ContextKey.PARAMETERS[0]) {
if (type instanceof PointType) {
IClass cls = ((PointType) type).getIClass();
return new FilteredPointerKey.SingleClassFilter(cls);
} else {
return null;
}
} else {
return null;
}
}
@Override
public String toString() {
return "JavaTypeContext<" + type + '>';
}
@Override
public int hashCode() {
return 6367 * type.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
JavaTypeContext other = (JavaTypeContext) obj;
return type.equals(other.type);
} else {
return false;
}
}
public TypeAbstraction getType() {
return type;
}
}
| 2,190
| 26.3875
| 95
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ReflectionContextInterpreter.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.analysis.reflection;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DelegatingSSAContextInterpreter;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.FieldReference;
import java.util.Iterator;
/** {@link SSAContextInterpreter} to handle all reflection procession. */
public class ReflectionContextInterpreter {
public static SSAContextInterpreter createReflectionContextInterpreter(
IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView iAnalysisCacheView) {
if (options == null) {
throw new IllegalArgumentException("null options");
}
// start with a dummy interpreter that understands nothing
SSAContextInterpreter result =
new SSAContextInterpreter() {
@Override
public boolean understands(CGNode node) {
return false;
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
// TODO Auto-generated method stub
return false;
}
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getNumberOfStatements(CGNode node) {
// TODO Auto-generated method stub
return 0;
}
@Override
public IR getIR(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public DefUse getDU(CGNode node) {
// TODO Auto-generated method stub
return null;
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode n) {
// TODO Auto-generated method stub
return null;
}
};
if (options.getReflectionOptions().getNumFlowToCastIterations() > 0) {
// need the factory bypass interpreter
result =
new DelegatingSSAContextInterpreter(
new FactoryBypassInterpreter(options, iAnalysisCacheView), result);
}
if (!options.getReflectionOptions().isIgnoreStringConstants()) {
result =
new DelegatingSSAContextInterpreter(
new GetClassContextInterpeter(),
new DelegatingSSAContextInterpreter(
new DelegatingSSAContextInterpreter(
new ClassFactoryContextInterpreter(),
new ClassNewInstanceContextInterpreter(cha)),
result));
}
if (!options.getReflectionOptions().isIgnoreMethodInvoke()) {
result =
new DelegatingSSAContextInterpreter(
new ReflectiveInvocationInterpreter(),
new DelegatingSSAContextInterpreter(new JavaLangClassContextInterpreter(), result));
}
// if NEITHER string constants NOR method invocations are ignored
if (!options.getReflectionOptions().isIgnoreStringConstants()
&& !options.getReflectionOptions().isIgnoreMethodInvoke()) {
result = new DelegatingSSAContextInterpreter(new GetMethodContextInterpreter(), result);
}
return result;
}
}
| 4,813
| 33.633094
| 98
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ReflectionContextSelector.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.analysis.reflection;
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.ContextSelector;
import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
/** A {@link ContextSelector} to handle default reflection logic. */
public class ReflectionContextSelector {
public static ContextSelector createReflectionContextSelector(AnalysisOptions options) {
if (options == null) {
throw new IllegalArgumentException("null options");
}
// start with a dummy
ContextSelector result =
new ContextSelector() {
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
return null;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
return EmptyIntSet.instance;
}
};
if (options.getReflectionOptions().getNumFlowToCastIterations() > 0) {
result = new DelegatingContextSelector(new FactoryContextSelector(), result);
}
if (!options.getReflectionOptions().isIgnoreStringConstants()) {
result =
new DelegatingContextSelector(
new DelegatingContextSelector(
new DelegatingContextSelector(
new ClassFactoryContextSelector(), new GetClassContextSelector()),
new ClassNewInstanceContextSelector()),
result);
}
if (!options.getReflectionOptions().isIgnoreMethodInvoke()) {
result =
new DelegatingContextSelector(
new ReflectiveInvocationSelector(),
new DelegatingContextSelector(new JavaLangClassContextSelector(), result));
}
// if NEITHER string constants NOR method invocations are ignored
if (!options.getReflectionOptions().isIgnoreStringConstants()
&& !options.getReflectionOptions().isIgnoreMethodInvoke()) {
result =
new DelegatingContextSelector(
new GetMethodContextSelector(
options.getReflectionOptions().isApplicationClassesOnly()),
result);
}
return result;
}
}
| 2,914
| 36.857143
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ReflectiveInvocationInterpreter.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.analysis.reflection;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.ReceiverInstanceContext;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.summaries.SyntheticIR;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.Iterator;
import java.util.Map;
/**
* An {@link SSAContextInterpreter} specialized to interpret reflective invocations such as
* Constructor.newInstance and Method.invoke on an {@link IMethod} constant.
*/
public class ReflectiveInvocationInterpreter extends AbstractReflectionInterpreter {
public static final MethodReference CTOR_NEW_INSTANCE =
MethodReference.findOrCreate(
TypeReference.JavaLangReflectConstructor,
"newInstance",
"([Ljava/lang/Object;)Ljava/lang/Object;");
public static final MethodReference METHOD_INVOKE =
MethodReference.findOrCreate(
TypeReference.JavaLangReflectMethod,
"invoke",
"(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;");
/* BEGIN Custom change: caching */
private final Map<String, IR> cache = HashMapFactory.make();
/* END Custom change: caching */
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getIR(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public IR getIR(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
if (DEBUG) {
System.err.println("generating IR for " + node);
}
Context recv = node.getContext();
@SuppressWarnings("unchecked")
ConstantKey<IMethod> c = (ConstantKey<IMethod>) recv.get(ContextKey.RECEIVER);
IMethod m = c.getValue();
/* BEGIN Custom change: caching */
final IMethod method = node.getMethod();
final String hashKey = method.toString() + '@' + recv;
IR result = cache.get(hashKey);
if (result == null) {
result = makeIR(method, m, recv);
cache.put(hashKey, result);
}
/* END Custom change: caching */
return result;
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter#getNumberOfStatements(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public int getNumberOfStatements(CGNode node) {
assert understands(node);
return getIR(node).getInstructions().length;
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#understands(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public boolean understands(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
if (!node.getContext().isA(ReceiverInstanceContext.class)) {
return false;
}
Context r = node.getContext();
if (!(r.get(ContextKey.RECEIVER) instanceof ConstantKey)) {
return false;
}
return node.getMethod().getReference().equals(METHOD_INVOKE)
|| node.getMethod().getReference().equals(CTOR_NEW_INSTANCE);
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateNewSites(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
if (node == null) {
throw new IllegalArgumentException("node is null");
}
assert understands(node);
return getIR(node).iterateNewSites();
}
/**
* @see
* com.ibm.wala.ipa.callgraph.propagation.rta.RTAContextInterpreter#iterateCallSites(com.ibm.wala.ipa.callgraph.CGNode)
*/
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
assert understands(node);
return getIR(node).iterateCallSites();
}
/**
* TODO: clean this up. Create the IR for the synthetic method (e.g. Method.invoke)
*
* @param method is something like Method.invoke or Construction.newInstance
* @param target is the method being called reflectively
*/
private IR makeIR(IMethod method, IMethod target, Context recv) {
SSAInstructionFactory insts =
method.getDeclaringClass().getClassLoader().getInstructionFactory();
SpecializedMethod m =
new SpecializedMethod(method, method.getDeclaringClass(), method.isStatic(), false);
Map<Integer, ConstantValue> constants = HashMapFactory.make();
int nextLocal = method.getNumberOfParameters() + 1; // nextLocal = first free value number
int nargs =
target.getNumberOfParameters(); // nargs := number of parameters to target, including "this"
// pointer
int args[] = new int[nargs];
int pc = 0;
int parametersVn = -1; // parametersVn will hold the value number of parameters array
if (method.getReference().equals(CTOR_NEW_INSTANCE)) {
// allocate the new object constructed
TypeReference allocatedType = target.getDeclaringClass().getReference();
m.addInstruction(
allocatedType,
insts.NewInstruction(
m.allInstructions.size(),
args[0] = nextLocal++,
NewSiteReference.make(pc++, allocatedType)),
true);
parametersVn = 2;
} else {
// for Method.invoke, v3 is the parameter to the method being called
parametersVn = 3;
if (target.isStatic()) {
// do nothing
} else {
// set up args[0] == the receiver for method.invoke, held in v2.
// insert a cast for v2 to filter out bogus types
args[0] = nextLocal++;
TypeReference type = target.getParameterType(0);
SSACheckCastInstruction cast =
insts.CheckCastInstruction(m.allInstructions.size(), args[0], 2, type, true);
m.addInstruction(null, cast, false);
}
}
int nextArg =
target.isStatic()
? 0
: 1; // nextArg := next index in args[] array that needs to be initialized
int nextParameter =
0; // nextParameter := next index in the parameters[] array that needs to be copied into the
// args[] array.
// load each of the parameters into a local variable, args[something]
for (int j = nextArg; j < nargs; j++) {
// load the next parameter into v_temp.
int indexConst = nextLocal++;
constants.put(indexConst, new ConstantValue(nextParameter++));
int temp = nextLocal++;
m.addInstruction(
null,
insts.ArrayLoadInstruction(
m.allInstructions.size(),
temp,
parametersVn,
indexConst,
TypeReference.JavaLangObject),
false);
pc++;
// cast v_temp to the appropriate type and store it in args[j]
args[j] = nextLocal++;
TypeReference type = target.getParameterType(j);
// we insert a cast to filter out bogus types
SSACheckCastInstruction cast =
insts.CheckCastInstruction(m.allInstructions.size(), args[j], temp, type, true);
m.addInstruction(null, cast, false);
pc++;
}
int exceptions = nextLocal++;
int result = -1;
// emit the dispatch and return instructions
if (method.getReference().equals(CTOR_NEW_INSTANCE)) {
m.addInstruction(
null,
insts.InvokeInstruction(
m.allInstructions.size(),
args,
exceptions,
CallSiteReference.make(
pc++, target.getReference(), IInvokeInstruction.Dispatch.SPECIAL),
null),
false);
m.addInstruction(
null, insts.ReturnInstruction(m.allInstructions.size(), args[0], false), false);
} else {
Dispatch d = target.isStatic() ? Dispatch.STATIC : Dispatch.VIRTUAL;
if (target.getReturnType().equals(TypeReference.Void)) {
m.addInstruction(
null,
insts.InvokeInstruction(
m.allInstructions.size(),
args,
exceptions,
CallSiteReference.make(pc++, target.getReference(), d),
null),
false);
} else {
result = nextLocal++;
m.addInstruction(
null,
insts.InvokeInstruction(
m.allInstructions.size(),
result,
args,
exceptions,
CallSiteReference.make(pc++, target.getReference(), d),
null),
false);
m.addInstruction(
null, insts.ReturnInstruction(m.allInstructions.size(), result, false), false);
}
}
SSAInstruction[] instrs = new SSAInstruction[m.allInstructions.size()];
m.allInstructions.<SSAInstruction>toArray(instrs);
return new SyntheticIR(
method,
recv,
new InducedCFG(instrs, method, recv),
instrs,
SSAOptions.defaultOptions(),
constants);
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return EmptyIterator.instance();
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return EmptyIterator.instance();
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode N) {
return getIR(N).getControlFlowGraph();
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
}
| 10,952
| 32.805556
| 126
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/ReflectiveInvocationSelector.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.analysis.reflection;
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.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.ReceiverInstanceContext;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
/**
* A {@link ContextSelector} to intercept calls to reflective method invocations such as
* Constructor.newInstance and Method.invoke
*/
class ReflectiveInvocationSelector implements ContextSelector {
public ReflectiveInvocationSelector() {}
/**
* Creates a callee target based on the following criteria:
*
* <ol>
* <li>If the method being invoked through reflection is definitely static, then do not create a
* callee target for any {@code callee} method that is not static. In this case, return
* {@code null}.
* <li>If the method being invoked through reflection takes a constant number of parameters,
* {@code n}, then do not create a callee target for any {@code callee} method that takes a
* number of parameters different from {@code n}. In this case, return {@code null}.
* <li>Otherwise, return a new {@link ReceiverInstanceContext} for {@code receiver}.
* </ol>
*/
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receiver) {
if (receiver == null || receiver.length == 0 || !mayUnderstand(callee, receiver[0])) {
return null;
}
IR ir = caller.getIR();
SSAAbstractInvokeInstruction[] invokeInstructions = ir.getCalls(site);
if (invokeInstructions.length != 1) {
return new ReceiverInstanceContext(receiver[0]);
}
SymbolTable st = ir.getSymbolTable();
@SuppressWarnings("unchecked")
ConstantKey<IMethod> receiverConstantKey = (ConstantKey<IMethod>) receiver[0];
IMethod m = receiverConstantKey.getValue();
boolean isStatic = m.isStatic();
boolean isConstructor = isConstructorConstant(receiver[0]);
// If the method being invoked through reflection is not a constructor and is definitely static,
// then
// we should not create a callee target for any method that is not static
if (!isConstructor) {
int recvUse = invokeInstructions[0].getUse(1);
if (st.isNullConstant(recvUse) && !isStatic) {
return null;
}
}
// If the method being invoked through reflection is being passed n parameters,
// then we should not create a callee target for any method that takes a number
// of parameters different from n
int numberOfParams = isStatic ? m.getNumberOfParameters() : m.getNumberOfParameters() - 1;
// instruction[0] is a call to Method.invoke(), where the receiver is a specific method,
// the first parameter is the receiver of the method invocation, and the second parameter
// is an array of objects corresponding to the parameters passed to the method.
int paramIndex = isConstructor ? 1 : 2;
int paramUse = invokeInstructions[0].getUse(paramIndex);
SSAInstruction instr = caller.getDU().getDef(paramUse);
if (!(instr instanceof SSANewInstruction)) {
return new ReceiverInstanceContext(receiver[0]);
}
SSANewInstruction newInstr = (SSANewInstruction) instr;
if (!newInstr.getConcreteType().isArrayType()) {
return null;
}
int vn = newInstr.getUse(0);
try {
int arrayLength = st.getIntValue(vn);
if (arrayLength == numberOfParams) {
return new ReceiverInstanceContext(receiver[0]);
} else {
return new IllegalArgumentExceptionContext();
}
} catch (IllegalArgumentException e) {
return new ReceiverInstanceContext(receiver[0]);
}
}
/** This object may understand a dispatch to Constructor.newInstance(). */
private static boolean mayUnderstand(IMethod targetMethod, InstanceKey instance) {
if (instance instanceof ConstantKey) {
if (targetMethod.getReference().equals(ReflectiveInvocationInterpreter.METHOD_INVOKE)
|| isConstructorConstant(instance)
&& targetMethod
.getReference()
.equals(ReflectiveInvocationInterpreter.CTOR_NEW_INSTANCE)) {
return true;
}
}
return false;
}
private static boolean isConstructorConstant(InstanceKey instance) {
if (instance instanceof ConstantKey) {
ConstantKey<?> c = (ConstantKey<?>) instance;
if (c.getConcreteType().getReference().equals(TypeReference.JavaLangReflectConstructor)) {
return true;
}
}
return false;
}
private static final IntSet thisParameter = IntSetUtil.make(new int[] {0});
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
if (site.getDeclaredTarget().equals(ReflectiveInvocationInterpreter.METHOD_INVOKE)
|| site.getDeclaredTarget().equals(ReflectiveInvocationInterpreter.CTOR_NEW_INSTANCE)) {
return thisParameter;
} else {
return EmptyIntSet.instance;
}
}
}
| 5,942
| 39.705479
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/reflection/java7/MethodHandles.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.analysis.reflection.java7;
import com.ibm.wala.cfg.ControlFlowGraph;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.classLoader.SyntheticMethod;
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.ContextKey;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DelegatingSSAContextInterpreter;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.ipa.summaries.SummarizedMethod;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAFieldAccessInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAOptions;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.MapIterator;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Predicate;
public class MethodHandles {
private static final IntSet params = IntSetUtil.make(new int[] {1, 2});
private static final IntSet self = IntSetUtil.make(new int[0]);
private static final ContextKey METHOD_KEY =
new ContextKey() {
@Override
public String toString() {
return "METHOD_KEY";
}
};
private static final ContextKey CLASS_KEY =
new ContextKey() {
@Override
public String toString() {
return "CLASS_KEY";
}
};
private static final ContextKey NAME_KEY =
new ContextKey() {
@Override
public String toString() {
return "NAME_KEY";
}
};
private static class HandlesItem<T> implements ContextItem {
private final T item;
public HandlesItem(T method) {
this.item = method;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((item == null) ? 0 : item.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HandlesItem<?> other = (HandlesItem<?>) obj;
if (item == null) {
if (other.item != null) return false;
} else if (!item.equals(other.item)) return false;
return true;
}
}
public static class FindContext implements Context {
private final Context base;
private final TypeReference cls;
private final String selector;
public FindContext(Context base, TypeReference cls, String methodName) {
this.base = base;
this.cls = cls;
this.selector = methodName;
}
@Override
public ContextItem get(ContextKey name) {
if (CLASS_KEY.equals(name)) {
return new HandlesItem<>(cls);
} else if (NAME_KEY.equals(name)) {
return new HandlesItem<>(selector);
} else {
return base.get(name);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + ((cls == null) ? 0 : cls.hashCode());
result = prime * result + ((selector == null) ? 0 : selector.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
FindContext other = (FindContext) obj;
if (base == null) {
if (other.base != null) return false;
} else if (!base.equals(other.base)) return false;
if (cls == null) {
if (other.cls != null) return false;
} else if (!cls.equals(other.cls)) return false;
if (selector == null) {
if (other.selector != null) return false;
} else if (!selector.equals(other.selector)) return false;
return true;
}
}
private static class MethodContext implements Context {
private final Context base;
private final MethodReference method;
public MethodContext(Context base, MethodReference method) {
this.base = base;
this.method = method;
}
@Override
public ContextItem get(ContextKey name) {
if (METHOD_KEY.equals(name)) {
return new HandlesItem<>(method);
} else {
return base.get(name);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + ((method == null) ? 0 : method.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MethodContext other = (MethodContext) obj;
if (base == null) {
if (other.base != null) return false;
} else if (!base.equals(other.base)) return false;
if (method == null) {
if (other.method != null) return false;
} else if (!method.equals(other.method)) return false;
return true;
}
@Override
public String toString() {
return "ctxt:" + method.getName();
}
}
private static class ContextSelectorImpl implements ContextSelector {
private final ContextSelector base;
public ContextSelectorImpl(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 ((isInvoke(callee) || isType(callee))
&& callee
.getReference()
.getDeclaringClass()
.getName()
.equals(TypeReference.JavaLangInvokeMethodHandle.getName())) {
if (actualParameters != null && actualParameters.length > 0) {
InstanceKey selfKey = actualParameters[0];
if (selfKey instanceof ConstantKey
&& ((ConstantKey<?>) selfKey)
.getConcreteType()
.getReference()
.equals(TypeReference.JavaLangInvokeMethodHandle)) {
MethodReference ref = ((IMethod) ((ConstantKey<?>) selfKey).getValue()).getReference();
return new MethodContext(baseContext, ref);
}
}
}
if (isFindStatic(callee)
&& callee
.getDeclaringClass()
.getReference()
.equals(TypeReference.JavaLangInvokeMethodHandlesLookup)) {
if (actualParameters != null && actualParameters.length > 2) {
InstanceKey classKey = actualParameters[1];
InstanceKey nameKey = actualParameters[2];
if (classKey instanceof ConstantKey
&& ((ConstantKey<?>) classKey)
.getConcreteType()
.getReference()
.equals(TypeReference.JavaLangClass)
&& nameKey instanceof ConstantKey
&& ((ConstantKey<?>) nameKey)
.getConcreteType()
.getReference()
.equals(TypeReference.JavaLangString)) {
return new FindContext(
baseContext,
((IClass) ((ConstantKey<?>) classKey).getValue()).getReference(),
(String) ((ConstantKey<?>) nameKey).getValue());
}
}
}
return baseContext;
}
@Override
public IntSet getRelevantParameters(CGNode caller, CallSiteReference site) {
MutableIntSet x = IntSetUtil.makeMutableCopy(base.getRelevantParameters(caller, site));
x.addAll(isFindStatic(site.getDeclaredTarget()) ? params : self);
return x;
}
}
private static class InvokeExactTargetSelector implements MethodTargetSelector {
private final MethodTargetSelector base;
private final Map<MethodReference, SyntheticMethod> impls = HashMapFactory.make();
public InvokeExactTargetSelector(MethodTargetSelector base) {
this.base = base;
}
@Override
public IMethod getCalleeTarget(CGNode caller, CallSiteReference site, IClass receiver) {
MethodReference target = site.getDeclaredTarget();
if (isInvokeExact(target)) {
if (!impls.containsKey(target)) {
SyntheticMethod invokeExactTrampoline =
new SyntheticMethod(
target,
receiver
.getClassHierarchy()
.lookupClass(TypeReference.JavaLangInvokeMethodHandle),
false,
false) {
@Override
public IR makeIR(Context context, SSAOptions options) throws UnimplementedError {
// MS: On JDK 17, sometimes makeIR() is getting called, and the default
// implementation fails with an error. I don't fully understand the invariants of
// this class, but overriding and returning null makes the tests pass.
// Eventually, we should document this class and figure out if this is the right
// fix.
return null;
}
};
impls.put(target, invokeExactTrampoline);
}
return impls.get(target);
}
return base.getCalleeTarget(caller, site, receiver);
}
}
private static boolean isInvokeExact(MethodReference target) {
return target
.getDeclaringClass()
.getName()
.equals(TypeReference.JavaLangInvokeMethodHandle.getName())
&& target.getName().toString().equals("invokeExact");
}
private static boolean isFindStatic(MethodReference node) {
return node.getName().toString().startsWith("findStatic");
}
private static boolean isFindStatic(IMethod node) {
return isFindStatic(node.getReference());
}
private static boolean isInvoke(IMethod node) {
return node.getName().toString().startsWith("invoke");
}
private static boolean isType(IMethod node) {
return node.getName().toString().equals("type");
}
private static boolean isInvoke(CGNode node) {
return isInvoke(node.getMethod());
}
private static boolean isType(CGNode node) {
return isType(node.getMethod());
}
private static boolean isFindStatic(CGNode node) {
return isFindStatic(node.getMethod());
}
private abstract static class HandlersContextInterpreterImpl implements SSAContextInterpreter {
protected final Map<CGNode, SoftReference<IR>> irs = HashMapFactory.make();
@Override
public Iterator<NewSiteReference> iterateNewSites(CGNode node) {
return getIR(node).iterateNewSites();
}
public Iterator<FieldReference> iterateFields(CGNode node, Predicate<SSAInstruction> filter) {
return new MapIterator<>(
new FilterIterator<>(getIR(node).iterateNormalInstructions(), filter),
object -> ((SSAFieldAccessInstruction) object).getDeclaredField());
}
@Override
public Iterator<FieldReference> iterateFieldsRead(CGNode node) {
return iterateFields(node, SSAGetInstruction.class::isInstance);
}
@Override
public Iterator<FieldReference> iterateFieldsWritten(CGNode node) {
return iterateFields(node, SSAPutInstruction.class::isInstance);
}
@Override
public boolean recordFactoryType(CGNode node, IClass klass) {
return false;
}
@Override
public Iterator<CallSiteReference> iterateCallSites(CGNode node) {
return getIR(node).iterateCallSites();
}
@Override
public IRView getIRView(CGNode node) {
return getIR(node);
}
@Override
public DefUse getDU(CGNode node) {
return new DefUse(getIR(node));
}
@Override
public int getNumberOfStatements(CGNode node) {
return getIR(node).getInstructions().length;
}
@Override
public ControlFlowGraph<SSAInstruction, ISSABasicBlock> getCFG(CGNode n) {
return getIR(n).getControlFlowGraph();
}
}
private static class FindContextInterpreterImpl extends HandlersContextInterpreterImpl {
@Override
public boolean understands(CGNode node) {
return isFindStatic(node) && node.getContext().isA(FindContext.class);
}
@Override
public IR getIR(CGNode node) {
if (!irs.containsKey(node) || irs.get(node).get() == null) {
MethodSummary code = new MethodSummary(node.getMethod().getReference());
SummarizedMethod m =
new SummarizedMethod(
node.getMethod().getReference(), code, node.getMethod().getDeclaringClass());
SSAInstructionFactory insts =
node.getMethod()
.getDeclaringClass()
.getClassLoader()
.getLanguage()
.instructionFactory();
assert node.getContext().isA(FindContext.class);
@SuppressWarnings("unchecked")
IClass cls =
node.getClassHierarchy()
.lookupClass(((HandlesItem<TypeReference>) node.getContext().get(CLASS_KEY)).item);
@SuppressWarnings("unchecked")
String selector = ((HandlesItem<String>) node.getContext().get(NAME_KEY)).item;
int vn = 10;
for (IMethod handleMethod : cls.getAllMethods()) {
if (handleMethod.getName().toString().contains(selector)) {
code.addStatement(
insts.LoadMetadataInstruction(
code.getNumberOfStatements(),
vn,
TypeReference.JavaLangInvokeMethodHandle,
handleMethod.getReference()));
code.addStatement(insts.ReturnInstruction(code.getNumberOfStatements(), vn, false));
vn++;
}
}
irs.put(
node, new SoftReference<>(m.makeIR(node.getContext(), SSAOptions.defaultOptions())));
}
return irs.get(node).get();
}
}
private static class InvokeContextInterpreterImpl extends HandlersContextInterpreterImpl {
@Override
public boolean understands(CGNode node) {
return (isInvoke(node) || isType(node)) && node.getContext().isA(MethodContext.class);
}
@Override
public IR getIR(CGNode node) {
if (!irs.containsKey(node) || irs.get(node).get() == null) {
MethodSummary code = new MethodSummary(node.getMethod().getReference());
SummarizedMethod m =
new SummarizedMethod(
node.getMethod().getReference(), code, node.getMethod().getDeclaringClass());
SSAInstructionFactory insts =
node.getMethod()
.getDeclaringClass()
.getClassLoader()
.getLanguage()
.instructionFactory();
assert node.getContext().isA(MethodContext.class);
MethodReference ref = ((MethodContext) node.getContext()).method;
boolean isStatic = node.getClassHierarchy().resolveMethod(ref).isStatic();
boolean isVoid = ref.getReturnType().equals(TypeReference.Void);
if (isInvoke(node)) {
String name = node.getMethod().getName().toString();
switch (name) {
case "invokeWithArguments":
{
int nargs = ref.getNumberOfParameters();
int params[] = new int[nargs];
for (int i = 0; i < nargs; i++) {
code.addConstant(i + nargs + 3, new ConstantValue(i));
code.addStatement(
insts.ArrayLoadInstruction(
code.getNumberOfStatements(),
i + 3,
1,
i + nargs + 3,
TypeReference.JavaLangObject));
params[i] = i + 3;
}
CallSiteReference site =
CallSiteReference.make(
nargs + 1, ref, isStatic ? Dispatch.STATIC : Dispatch.SPECIAL);
code.addStatement(
insts.InvokeInstruction(
code.getNumberOfStatements(),
2 * nargs + 3,
params,
2 * nargs + 4,
site,
null));
code.addStatement(
insts.ReturnInstruction(code.getNumberOfStatements(), 2 * nargs + 3, false));
break;
}
case "invokeExact":
{
int nargs = node.getMethod().getReference().getNumberOfParameters();
int params[] = new int[nargs];
if (nargs == ref.getNumberOfParameters() + (isStatic ? 0 : 1)) {
for (int i = 0; i < nargs; i++) {
params[i] = i + 2;
}
CallSiteReference site =
CallSiteReference.make(0, ref, isStatic ? Dispatch.STATIC : Dispatch.SPECIAL);
if (isVoid) {
code.addStatement(
insts.InvokeInstruction(
code.getNumberOfStatements(), params, nargs + 2, site, null));
} else {
code.addStatement(
insts.InvokeInstruction(
code.getNumberOfStatements(),
nargs + 2,
params,
nargs + 3,
site,
null));
code.addStatement(
insts.ReturnInstruction(code.getNumberOfStatements(), nargs + 2, false));
}
}
break;
}
}
} else {
assert isType(node);
code.addStatement(
insts.LoadMetadataInstruction(
code.getNumberOfStatements(),
2,
TypeReference.JavaLangInvokeMethodType,
ref.getDescriptor()));
code.addStatement(insts.ReturnInstruction(code.getNumberOfStatements(), 2, false));
}
irs.put(
node, new SoftReference<>(m.makeIR(node.getContext(), SSAOptions.defaultOptions())));
}
return irs.get(node).get();
}
}
public static void analyzeMethodHandles(
AnalysisOptions options, SSAPropagationCallGraphBuilder builder) {
options.setSelector(new InvokeExactTargetSelector(options.getMethodTargetSelector()));
builder.setContextSelector(new ContextSelectorImpl(builder.getContextSelector()));
builder.setContextInterpreter(
new DelegatingSSAContextInterpreter(
new InvokeContextInterpreterImpl(), builder.getCFAContextInterpreter()));
builder.setContextInterpreter(
new DelegatingSSAContextInterpreter(
new FindContextInterpreterImpl(), builder.getCFAContextInterpreter()));
}
}
| 20,739
| 34.452991
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/stackMachine/AbstractIntStackMachine.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.analysis.stackMachine;
import com.ibm.wala.cfg.ShrikeCFG;
import com.ibm.wala.cfg.ShrikeCFG.BasicBlock;
import com.ibm.wala.core.util.CancelRuntimeException;
import com.ibm.wala.core.util.shrike.ShrikeUtil;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.dataflow.graph.BasicFramework;
import com.ibm.wala.dataflow.graph.DataflowSolver;
import com.ibm.wala.dataflow.graph.IKilldallFramework;
import com.ibm.wala.dataflow.graph.ITransferFunctionProvider;
import com.ibm.wala.fixpoint.AbstractStatement;
import com.ibm.wala.fixpoint.AbstractVariable;
import com.ibm.wala.fixpoint.FixedPointConstants;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.shrike.shrikeBT.ArrayLengthInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayLoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.IComparisonInstruction;
import com.ibm.wala.shrike.shrikeBT.IConditionalBranchInstruction;
import com.ibm.wala.shrike.shrikeBT.IConversionInstruction;
import com.ibm.wala.shrike.shrikeBT.IGetInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstanceofInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.ILoadInstruction;
import com.ibm.wala.shrike.shrikeBT.IPutInstruction;
import com.ibm.wala.shrike.shrikeBT.IShiftInstruction;
import com.ibm.wala.shrike.shrikeBT.IStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IUnaryOpInstruction;
import com.ibm.wala.shrike.shrikeBT.MonitorInstruction;
import com.ibm.wala.shrike.shrikeBT.NewInstruction;
import com.ibm.wala.shrike.shrikeBT.PopInstruction;
import com.ibm.wala.shrike.shrikeBT.SwapInstruction;
import com.ibm.wala.shrike.shrikeBT.SwitchInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.graph.INodeWithNumber;
import java.util.Arrays;
/**
* Skeleton of functionality to propagate information through the Java bytecode stack machine using
* ShrikeBT.
*
* <p>This class computes properties the Java operand stack and of the local variables at the
* beginning of each basic block.
*
* <p>In this implementation, each dataflow variable value is an integer, and the "meeter" object
* provides the meets
*/
public abstract class AbstractIntStackMachine implements FixedPointConstants {
private static final boolean DEBUG = false;
public static final int TOP = -1;
public static final int BOTTOM = -2;
public static final int UNANALYZED = -3;
public static final int IGNORE = -4;
/** The solver */
private DataflowSolver<BasicBlock, MachineState> solver;
/** The control flow graph to analyze */
private final ShrikeCFG cfg;
/** Should uninitialized variables be considered TOP (optimistic) or BOTTOM (pessimistic); */
public static final boolean OPTIMISTIC = true;
protected AbstractIntStackMachine(final ShrikeCFG G) {
if (G == null) {
throw new IllegalArgumentException("G is null");
}
this.cfg = G;
}
protected void init(Meeter meeter, final FlowProvider flow) {
final MeetOperator meet = new MeetOperator(meeter);
ITransferFunctionProvider<BasicBlock, MachineState> xferFunctions =
new ITransferFunctionProvider<>() {
@Override
public boolean hasNodeTransferFunctions() {
return flow.needsNodeFlow();
}
@Override
public boolean hasEdgeTransferFunctions() {
return flow.needsEdgeFlow();
}
@Override
public UnaryOperator<MachineState> getNodeTransferFunction(final BasicBlock node) {
return new UnaryOperator<>() {
@Override
public byte evaluate(MachineState lhs, MachineState rhs) {
MachineState exit = lhs;
MachineState entry = rhs;
MachineState newExit = flow.flow(entry, node);
if (newExit.stateEquals(exit)) {
return NOT_CHANGED;
} else {
exit.copyState(newExit);
return CHANGED;
}
}
@Override
public String toString() {
return "NODE-FLOW";
}
@Override
public int hashCode() {
return 9973 * node.hashCode();
}
@Override
public boolean equals(Object o) {
return this == o;
}
};
}
@Override
public UnaryOperator<MachineState> getEdgeTransferFunction(
final BasicBlock from, final BasicBlock to) {
return new UnaryOperator<>() {
@Override
public byte evaluate(MachineState lhs, MachineState rhs) {
MachineState exit = lhs;
MachineState entry = rhs;
MachineState newExit = flow.flow(entry, from, to);
if (newExit.stateEquals(exit)) {
return NOT_CHANGED;
} else {
exit.copyState(newExit);
return CHANGED;
}
}
@Override
public String toString() {
return "EDGE-FLOW";
}
@Override
public int hashCode() {
return 9973 * (from.hashCode() ^ to.hashCode());
}
@Override
public boolean equals(Object o) {
return this == o;
}
};
}
@Override
public AbstractMeetOperator<MachineState> getMeetOperator() {
return meet;
}
};
IKilldallFramework<BasicBlock, MachineState> problem = new BasicFramework<>(cfg, xferFunctions);
solver =
new DataflowSolver<>(problem) {
private MachineState entry;
@Override
protected MachineState makeNodeVariable(BasicBlock n, boolean IN) {
assert n != null;
MachineState result = new MachineState(n);
if (IN && n.equals(cfg.entry())) {
entry = result;
}
return result;
}
@Override
protected MachineState makeEdgeVariable(BasicBlock from, BasicBlock to) {
assert from != null;
assert to != null;
MachineState result = new MachineState(from);
return result;
}
@Override
protected void initializeWorkList() {
super.buildEquations(false, false);
/*
* Add only the entry variable to the work list.
*/
for (INodeWithNumber s :
Iterator2Iterable.make(getFixedPointSystem().getStatementsThatUse(entry))) {
addToWorkList((AbstractStatement<?, ?>) s);
}
}
@Override
protected void initializeVariables() {
super.initializeVariables();
AbstractIntStackMachine.this.initializeVariables();
}
@Override
protected MachineState[] makeStmtRHS(int size) {
return new MachineState[size];
}
};
}
public boolean solve() {
try {
return solver.solve(null);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
}
/** Convenience method ... a little ugly .. perhaps delete later. */
protected void initializeVariables() {}
public MachineState getEntryState() {
return solver.getIn(cfg.entry());
}
/** @return the state at the entry to a given block */
public MachineState getIn(ShrikeCFG.BasicBlock bb) {
return solver.getIn(bb);
}
private class MeetOperator extends AbstractMeetOperator<MachineState> {
private final Meeter meeter;
MeetOperator(Meeter meeter) {
this.meeter = meeter;
}
@Override
public boolean isUnaryNoOp() {
return false;
}
@Override
public byte evaluate(MachineState lhs, MachineState[] rhs) {
BasicBlock bb = lhs.getBasicBlock();
if (!bb.isCatchBlock()) {
return meet(lhs, rhs, bb, meeter) ? CHANGED : NOT_CHANGED;
} else {
return meetForCatchBlock(lhs, rhs, bb, meeter) ? CHANGED : NOT_CHANGED;
}
}
@Override
public int hashCode() {
return 72223 * meeter.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof MeetOperator) {
MeetOperator other = (MeetOperator) o;
return meeter.equals(other.meeter);
} else {
return false;
}
}
@Override
public String toString() {
return "MEETER";
}
}
/**
* A Meeter object provides the dataflow logic needed to meet the abstract machine state for a
* dataflow meet.
*/
protected interface Meeter {
/**
* Return the integer that represents the meet of a particular stack slot at the entry to a
* basic block.
*
* @param slot The stack slot to meet
* @param rhs The values to meet
* @param bb The basic block at whose entry this meet occurs
* @return The value result of the meet
*/
int meetStack(int slot, int[] rhs, BasicBlock bb);
/**
* Return the integer that represents stack slot 0 after a meet at the entry to a catch block.
*
* @param bb The basic block at whose entry this meet occurs
* @return The value of stack slot 0 after the meet
*/
int meetStackAtCatchBlock(BasicBlock bb);
/**
* Return the integer that represents the meet of a particular local at the entry to a basic
* block.
*
* @param n The number of the local
* @param rhs The values to meet
* @param bb The basic block at whose entry this meet occurs
* @return The value of local n after the meet.
*/
int meetLocal(int n, int[] rhs, BasicBlock bb);
}
/**
* Evaluate a meet of machine states.
*
* <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor.
*
* @param bb the basic block at whose entry the meet occurs
* @return true if the lhs value changes. false otherwise.
*/
private static boolean meet(MachineState lhs, MachineState[] rhs, BasicBlock bb, Meeter meeter) {
boolean changed = meetStacks(lhs, rhs, bb, meeter);
changed |= meetLocals(lhs, rhs, bb, meeter);
return changed;
}
/**
* Evaluate a meet of machine states at a catch block.
*
* <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor.
*
* @param bb the basic block at whose entry the meet occurs
* @return true if the lhs value changes. false otherwise.
*/
private static boolean meetForCatchBlock(
MachineState lhs, MachineState[] rhs, BasicBlock bb, Meeter meeter) {
boolean changed = meetStacksAtCatchBlock(lhs, bb, meeter);
changed |= meetLocals(lhs, rhs, bb, meeter);
return changed;
}
/**
* Evaluate a meet of the stacks of machine states at the entry of a catch block.
*
* <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor.
*
* @param bb the basic block at whose entry the meet occurs
* @return true if the lhs value changes. false otherwise.
*/
private static boolean meetStacksAtCatchBlock(MachineState lhs, BasicBlock bb, Meeter meeter) {
boolean changed = false;
// evaluate the meet of the stack of height 1, which holds the exception
// object.
// allocate lhs.stack if it's
// not already allocated.
if (lhs.stack == null) {
lhs.allocateStack(1);
lhs.stackHeight = 1;
}
int meet = meeter.meetStackAtCatchBlock(bb);
if (lhs.stack[0] == TOP) {
if (meet != TOP) {
changed = true;
lhs.stack[0] = meet;
}
} else if (meet != lhs.stack[0]) {
changed = true;
lhs.stack[0] = meet;
}
return changed;
}
/**
* Evaluate a meet of the stacks of machine states at the entry of a basic block.
*
* <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor.
*
* @param bb the basic block at whose entry the meet occurs
* @return true if the lhs value changes. false otherwise.
*/
private static boolean meetStacks(
MachineState lhs, MachineState[] rhs, BasicBlock bb, Meeter meeter) {
boolean changed = false;
// evaluate the element-wise meet over the stacks
// first ... how high are the stacks?
int height = computeMeetStackHeight(rhs);
// if there's any stack height to meet, allocate lhs.stack if it's
// not already allocated.
if (height > -1 && (lhs.stack == null || lhs.stack.length < height)) {
lhs.allocateStack(height);
lhs.stackHeight = height;
changed = true;
}
// now do the element-wise meet.
for (int i = 0; i < height; i++) {
int[] R = new int[rhs.length];
for (int j = 0; j < R.length; j++) {
MachineState m = rhs[j];
if (m.stack == null || m.stack.length < i + 1) {
R[j] = TOP;
} else {
R[j] = m.stack[i];
if (R[j] == 0) {
R[j] = TOP;
}
}
}
int meet = meeter.meetStack(i, R, bb);
if (lhs.stack[i] == TOP) {
if (meet != TOP) {
changed = true;
lhs.stack[i] = meet;
}
} else if (meet != lhs.stack[i]) {
changed = true;
lhs.stack[i] = meet;
}
}
return changed;
}
/**
* Evaluate a meet of locals of machine states at the entry to a basic block.
*
* <p>TODO: add some efficiency shortcuts. TODO: clean up and refactor.
*
* @param bb the basic block at whose entry the meet occurs
* @return true if the lhs value changes. false otherwise.
*/
private static boolean meetLocals(
MachineState lhs, MachineState[] rhs, BasicBlock bb, Meeter meeter) {
boolean changed = false;
// need we allocate lhs.locals?
int nLocals = computeMeetNLocals(rhs);
if (nLocals > -1 && (lhs.locals == null || lhs.locals.length < nLocals)) {
lhs.allocateLocals(nLocals);
}
// evaluate the element-wise meet over the locals.
for (int i = 0; i < nLocals; i++) {
int[] R = new int[rhs.length];
for (int j = 0; j < rhs.length; j++) {
R[j] = rhs[j].getLocal(i);
}
int meet = meeter.meetLocal(i, R, bb);
if (lhs.locals[i] == TOP) {
if (meet != TOP) {
changed = true;
lhs.locals[i] = meet;
}
} else if (meet != lhs.locals[i]) {
changed = true;
lhs.locals[i] = meet;
}
}
return changed;
}
/**
* @return the number of locals to meet. Return -1 if there is no local meet necessary.
* @param operands The operands for this operator. operands[0] is the left-hand side.
*/
private static int computeMeetNLocals(MachineState[] operands) {
MachineState lhs = operands[0];
int nLocals = -1;
if (lhs.locals != null) {
nLocals = lhs.locals.length;
} else {
for (int i = 1; i < operands.length; i++) {
MachineState rhs = operands[i];
if (rhs.locals != null) {
nLocals = rhs.locals.length;
break;
}
}
}
return nLocals;
}
/**
* @return the height of stacks that are being meeted. Return -1 if there is no stack meet
* necessary.
* @param operands The operands for this operator. operands[0] is the left-hand side.
*/
private static int computeMeetStackHeight(MachineState[] operands) {
MachineState lhs = operands[0];
int height = -1;
if (lhs.stack != null) {
height = lhs.stackHeight;
} else {
for (int i = 1; i < operands.length; i++) {
MachineState rhs = operands[i];
if (rhs.stack != null) {
height = rhs.stackHeight;
break;
}
}
}
return height;
}
/** Representation of the state of the JVM stack machine at some program point. */
public class MachineState extends AbstractVariable<MachineState> {
private int[] stack;
private int[] locals;
// NOTE: stackHeight == -1 is a special code meaning "this variable is TOP"
private int stackHeight;
private final BasicBlock bb;
/**
* I'm not using clone because I don't want to necessarily inherit the AbstractVariable state
* from the superclass
*/
public MachineState duplicate() {
MachineState result = new MachineState(bb);
result.copyState(this);
return result;
}
public MachineState(BasicBlock bb) {
setTOP();
this.bb = bb;
}
public BasicBlock getBasicBlock() {
return bb;
}
void setTOP() {
stackHeight = -1;
stack = null;
}
boolean isTOP() {
return stackHeight == -1;
}
public void push(int i) {
if (stack == null || stackHeight >= stack.length) allocateStack(stackHeight + 1);
stack[stackHeight++] = i;
}
public int pop() {
if (stackHeight <= 0) {
assert stackHeight > 0 : "can't pop stack of height " + stackHeight;
}
stackHeight -= 1;
return stack[stackHeight];
}
public int peek() {
return stack[stackHeight - 1];
}
public void swap() {
int temp = stack[stackHeight - 1];
stack[stackHeight - 1] = stack[stackHeight - 2];
stack[stackHeight - 2] = temp;
}
private void allocateStack(int stackHeight) {
if (stack == null) {
stack = new int[stackHeight + 1];
this.stackHeight = 0;
} else {
stack = Arrays.copyOf(stack, Math.max(stack.length, stackHeight) * 2 + 1);
}
}
private void allocateLocals(int maxLocals) {
int[] result = new int[maxLocals];
int start = 0;
if (locals != null) {
System.arraycopy(locals, 0, result, 0, locals.length);
start = locals.length;
}
for (int i = start; i < maxLocals; i++) {
result[i] = OPTIMISTIC ? TOP : BOTTOM;
}
locals = result;
}
public void clearStack() {
stackHeight = 0;
}
/** set the value of local i to symbol j */
public void setLocal(int i, int j) {
if (locals == null || locals.length < i + 1) {
if (OPTIMISTIC && (j == TOP)) {
return;
} else {
allocateLocals(i + 1);
}
}
locals[i] = j;
}
/** @return the number of the symbol corresponding to local i */
public int getLocal(int i) {
if (locals == null || locals.length < i + 1) {
if (OPTIMISTIC) {
return TOP;
} else {
return BOTTOM;
}
} else {
return locals[i];
}
}
public void replaceValue(int from, int to) {
if (stack != null) for (int i = 0; i < stackHeight; i++) if (stack[i] == from) stack[i] = to;
if (locals != null)
for (int i = 0; i < locals.length; i++) if (locals[i] == from) locals[i] = to;
}
public boolean hasValue(int val) {
if (stack != null) for (int i = 0; i < stackHeight; i++) if (stack[i] == val) return true;
if (locals != null) for (int local : locals) if (local == val) return true;
return false;
}
@Override
public String toString() {
if (isTOP()) {
return "<TOP>@" + System.identityHashCode(this);
}
StringBuilder result = new StringBuilder("<");
result.append('S');
if (stackHeight == 0) {
result.append("[empty]");
} else {
result.append(array2StringBuffer(stack, stackHeight));
}
result.append('L');
result.append(array2StringBuffer(locals, locals == null ? 0 : locals.length));
result.append('>');
return result.toString();
}
private StringBuilder array2StringBuffer(int[] array, int n) {
StringBuilder result = new StringBuilder("[");
if (array == null) {
result.append(OPTIMISTIC ? "TOP" : "BOTTOM");
} else {
for (int i = 0; i < n - 1; i++) {
result.append(array[i]).append(',');
}
result.append(array[n - 1]);
}
result.append(']');
return result;
}
@Override
public void copyState(MachineState other) {
stack = other.stack == null ? null : other.stack.clone();
locals = other.locals == null ? null : other.locals.clone();
stackHeight = other.stackHeight;
}
boolean stateEquals(MachineState exit) {
if (stackHeight != exit.stackHeight) return false;
if (locals == null) {
if (exit.locals != null) return false;
} else {
if (exit.locals == null) return false;
else if (locals.length != exit.locals.length) return false;
}
for (int i = 0; i < stackHeight; i++) {
if (stack[i] != exit.stack[i]) return false;
}
if (locals != null) {
for (int i = 0; i < locals.length; i++) {
if (locals[i] == TOP) {
if (exit.locals[i] != TOP) return false;
}
if (locals[i] != exit.locals[i]) return false;
}
}
return true;
}
/**
* Returns the stackHeight.
*
* @return int
*/
public int getStackHeight() {
return stackHeight;
}
/** Use with care. */
public int[] getLocals() {
return locals;
}
}
/** Interface which defines a flow function for a basic block */
public interface FlowProvider {
boolean needsNodeFlow();
boolean needsEdgeFlow();
/**
* Compute the MachineState at the exit of a basic block, given a MachineState at the block's
* entry.
*/
MachineState flow(MachineState entry, BasicBlock basicBlock);
/**
* Compute the MachineState at the end of an edge, given a MachineState at the edges's entry.
*/
MachineState flow(MachineState entry, BasicBlock from, BasicBlock to);
}
/**
* This gives some basic facilities for shoving things around on the stack. Client analyses should
* subclass this as needed.
*/
protected abstract static class BasicStackFlowProvider implements FlowProvider, Constants {
private final ShrikeCFG cfg;
protected MachineState workingState;
private BasicStackMachineVisitor visitor;
private com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor edgeVisitor;
private int currentInstructionIndex = 0;
private BasicBlock currentBlock;
private BasicBlock currentSuccessorBlock;
/** Only subclasses can instantiate */
protected BasicStackFlowProvider(ShrikeCFG cfg) {
this.cfg = cfg;
}
/** Initialize the visitors used to perform the flow functions */
protected void init(
BasicStackMachineVisitor v, com.ibm.wala.shrike.shrikeBT.IInstruction.Visitor ev) {
this.visitor = v;
this.edgeVisitor = ev;
}
@Override
public boolean needsNodeFlow() {
return true;
}
@Override
public boolean needsEdgeFlow() {
return false;
}
@Override
public MachineState flow(MachineState entry, BasicBlock basicBlock) {
workingState = entry.duplicate();
currentBlock = basicBlock;
currentSuccessorBlock = null;
IInstruction[] instructions = getInstructions();
if (DEBUG) {
System.err.println(("Entry to BB" + cfg.getNumber(basicBlock) + ' ' + workingState));
}
for (int i = basicBlock.getFirstInstructionIndex();
i <= basicBlock.getLastInstructionIndex();
i++) {
currentInstructionIndex = i;
instructions[i].visit(visitor);
if (DEBUG) {
System.err.println(("After " + instructions[i] + ' ' + workingState));
}
}
return workingState;
}
@Override
public MachineState flow(MachineState entry, BasicBlock from, BasicBlock to) {
workingState = entry.duplicate();
currentBlock = from;
currentSuccessorBlock = to;
IInstruction[] instructions = getInstructions();
if (DEBUG) {
System.err.println(("Entry to BB" + cfg.getNumber(from) + ' ' + workingState));
}
for (int i = from.getFirstInstructionIndex(); i <= from.getLastInstructionIndex(); i++) {
currentInstructionIndex = i;
instructions[i].visit(edgeVisitor);
if (DEBUG) {
System.err.println(("After " + instructions[i] + ' ' + workingState));
}
}
return workingState;
}
protected int getCurrentInstructionIndex() {
return currentInstructionIndex;
}
protected int getCurrentProgramCounter() {
return cfg.getProgramCounter(currentInstructionIndex);
}
protected BasicBlock getCurrentBlock() {
return currentBlock;
}
protected BasicBlock getCurrentSuccessor() {
return currentSuccessorBlock;
}
public abstract IInstruction[] getInstructions();
/** Update the machine state to account for an instruction */
protected class BasicStackMachineVisitor extends IInstruction.Visitor {
@Override
public void visitArrayLength(ArrayLengthInstruction instruction) {
workingState.pop();
workingState.push(UNANALYZED);
}
@Override
public void visitArrayLoad(IArrayLoadInstruction instruction) {
workingState.pop();
workingState.pop();
workingState.push(UNANALYZED);
}
@Override
public void visitArrayStore(IArrayStoreInstruction instruction) {
workingState.pop();
workingState.pop();
workingState.pop();
}
@Override
public void visitBinaryOp(IBinaryOpInstruction instruction) {
workingState.pop();
}
@Override
public void visitComparison(IComparisonInstruction instruction) {
workingState.pop();
workingState.pop();
workingState.push(UNANALYZED);
}
@Override
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {
workingState.pop();
workingState.pop();
}
@Override
public void visitConstant(ConstantInstruction instruction) {
workingState.push(UNANALYZED);
}
@Override
public void visitConversion(IConversionInstruction instruction) {
workingState.pop();
workingState.push(UNANALYZED);
}
@Override
public void visitDup(DupInstruction instruction) {
int size = instruction.getSize();
int delta = instruction.getDelta();
assert size == 1 || size == 2;
assert delta == 0 || delta == 1 || delta == 2;
int toPop = size + delta;
int v1 = workingState.pop();
int v2 = (toPop > 1) ? workingState.pop() : IGNORE;
int v3 = (toPop > 2) ? workingState.pop() : IGNORE;
int v4 = (toPop > 3) ? workingState.pop() : IGNORE;
if (size > 1) {
workingState.push(v2);
}
workingState.push(v1);
if (v4 != IGNORE) {
workingState.push(v4);
}
if (v3 != IGNORE) {
workingState.push(v3);
}
if (v2 != IGNORE) {
workingState.push(v2);
}
workingState.push(v1);
}
@Override
public void visitGet(IGetInstruction instruction) {
popN(instruction);
workingState.push(UNANALYZED);
}
protected void popN(IInstruction instruction) {
for (int i = 0; i < instruction.getPoppedCount(); i++) {
workingState.pop();
}
}
@Override
public void visitInstanceof(IInstanceofInstruction instruction) {
workingState.pop();
workingState.push(UNANALYZED);
}
@Override
public void visitInvoke(IInvokeInstruction instruction) {
popN(instruction);
ClassLoaderReference loader =
cfg.getMethod().getDeclaringClass().getClassLoader().getReference();
TypeReference returnType =
ShrikeUtil.makeTypeReference(
loader, Util.getReturnType(instruction.getMethodSignature()));
if (!returnType.equals(TypeReference.Void)) {
workingState.push(UNANALYZED);
}
}
@Override
public void visitMonitor(MonitorInstruction instruction) {
workingState.pop();
}
@Override
public void visitLocalLoad(ILoadInstruction instruction) {
int t = workingState.getLocal(instruction.getVarIndex());
workingState.push(t);
}
@Override
public void visitLocalStore(IStoreInstruction instruction) {
int index = instruction.getVarIndex();
workingState.setLocal(index, workingState.pop());
}
@Override
public void visitNew(NewInstruction instruction) {
popN(instruction);
workingState.push(UNANALYZED);
}
@Override
public void visitPop(PopInstruction instruction) {
if (instruction.getPoppedCount() > 0) {
workingState.pop();
}
}
@Override
public void visitPut(IPutInstruction instruction) {
popN(instruction);
}
@Override
public void visitShift(IShiftInstruction instruction) {
workingState.pop();
}
@Override
public void visitSwap(SwapInstruction instruction) {
workingState.swap();
}
@Override
public void visitSwitch(SwitchInstruction instruction) {
workingState.pop();
}
@Override
public void visitThrow(ThrowInstruction instruction) {
int exceptionType = workingState.pop();
workingState.clearStack();
workingState.push(exceptionType);
}
@Override
public void visitUnaryOp(IUnaryOpInstruction instruction) {
// treated as a no-op in basic scheme
}
}
}
}
| 30,733
| 28.523535
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/ConeType.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.analysis.typeInference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
import java.util.Iterator;
/** Represents a type and its subtypes. */
public class ConeType extends TypeAbstraction {
private final IClass type;
/** @throws IllegalArgumentException if type is null */
public ConeType(IClass type) {
if (type == null) {
throw new IllegalArgumentException("type is null");
}
assert type.getReference().isReferenceType() : type;
this.type = type;
}
@Override
public TypeAbstraction meet(TypeAbstraction rhs) {
if (rhs == TOP) {
return this;
} else if (rhs instanceof ConeType) {
ConeType other = (ConeType) rhs;
if (type.equals(other.type)) {
return this;
} else if (type.isArrayClass() || other.type.isArrayClass()) {
// give up on arrays. We don't care anyway.
return new ConeType(type.getClassHierarchy().getRootClass());
} else {
return new ConeType(
type.getClassHierarchy().getLeastCommonSuperclass(this.type, other.type));
}
} else if (rhs instanceof PointType) {
return rhs.meet(this);
} else if (rhs instanceof PrimitiveType) {
return TOP;
} else {
Assertions.UNREACHABLE("unexpected type " + rhs.getClass());
return null;
}
}
@Override
public String toString() {
return "cone:" + type.toString();
}
@Override
public IClass getType() {
return type;
}
@Override
public TypeReference getTypeReference() {
return type.getReference();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ConeType)) {
return false;
}
ConeType other = (ConeType) obj;
if (other == TOP) {
return false;
}
if (!type.getClassHierarchy().equals(other.type.getClassHierarchy())) {
Assertions.UNREACHABLE("different chas " + this + ' ' + other);
}
return type.equals(other.type);
}
@Override
public int hashCode() {
return 39 * type.hashCode();
}
public boolean isArrayType() {
return getType().isArrayClass();
}
public boolean isInterface() {
return getType().isInterface();
}
/** @return an Iterator of IClass that implement this interface */
public Iterator<IClass> iterateImplementors() {
return type.getClassHierarchy().getImplementors(getType().getReference()).iterator();
}
public IClassHierarchy getClassHierarchy() {
return type.getClassHierarchy();
}
}
| 2,987
| 26.163636
| 89
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/JavaPrimitiveType.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.analysis.typeInference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.HashMap;
/** Abstraction of a primitive type in Java. */
public class JavaPrimitiveType extends PrimitiveType {
public static final PrimitiveType BOOLEAN = makePrimitive(TypeReference.Boolean, 1);
public static final PrimitiveType CHAR = makePrimitive(TypeReference.Char, 16);
public static final PrimitiveType BYTE = makePrimitive(TypeReference.Byte, 8);
public static final PrimitiveType SHORT = makePrimitive(TypeReference.Short, 16);
public static final PrimitiveType INT = makePrimitive(TypeReference.Int, 32);
public static final PrimitiveType LONG = makePrimitive(TypeReference.Long, 64);
public static final PrimitiveType FLOAT = makePrimitive(TypeReference.Float, 32);
public static final PrimitiveType DOUBLE = makePrimitive(TypeReference.Double, 64);
public static final PrimitiveType VOID = makePrimitive(TypeReference.Void, 0);
public static void init() {}
private JavaPrimitiveType(TypeReference reference, int size) {
super(reference, size);
}
private static PrimitiveType makePrimitive(TypeReference reference, int size) {
return new JavaPrimitiveType(reference, size);
}
private static final HashMap<String, String> primitiveNameMap;
static {
primitiveNameMap = HashMapFactory.make(9);
primitiveNameMap.put("I", "int");
primitiveNameMap.put("J", "long");
primitiveNameMap.put("S", "short");
primitiveNameMap.put("B", "byte");
primitiveNameMap.put("C", "char");
primitiveNameMap.put("D", "double");
primitiveNameMap.put("F", "float");
primitiveNameMap.put("Z", "boolean");
primitiveNameMap.put("V", "void");
}
@Override
public String toString() {
String result = primitiveNameMap.get(reference.getName().toString());
return (result != null) ? result : reference.getName().toString();
}
}
| 2,341
| 32.942029
| 86
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/PointType.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.analysis.typeInference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.debug.Assertions;
/** Represents a single concrete type. */
public class PointType extends TypeAbstraction {
private final IClass type;
/** @throws IllegalArgumentException if type is null */
public PointType(IClass type) {
if (type == null) {
throw new IllegalArgumentException("type is null");
}
this.type = type;
assert type.getReference().isReferenceType();
}
@Override
public TypeAbstraction meet(TypeAbstraction rhs) {
if (rhs == TOP) {
return this;
} else {
if (rhs instanceof PointType) {
PointType other = (PointType) rhs;
if (type.equals(other.type)) {
return this;
} else if (type.isArrayClass() || other.type.isArrayClass()) {
// give up on arrays. We don't care anyway.
return new ConeType(type.getClassHierarchy().getRootClass());
} else {
return new ConeType(
type.getClassHierarchy().getLeastCommonSuperclass(this.type, other.type));
}
} else if (rhs instanceof ConeType) {
ConeType other = (ConeType) rhs;
if (type.equals(other.getType())) {
// "this" and the cone type have the same underlying type, return the cone type
return other;
}
TypeReference T = other.getType().getReference();
if (type.isArrayClass() || T.isArrayType()) {
// give up on arrays. We don't care anyway.
return new ConeType(type.getClassHierarchy().getRootClass());
}
IClass typeKlass = type;
if (type.getClassHierarchy().isSubclassOf(typeKlass, other.getType())) {
return other;
} else if (other.isInterface()) {
if (type.getClassHierarchy().implementsInterface(typeKlass, other.getType())) {
return other;
}
}
// if we get here, we need to do cha-based superclass and return a cone.
// TODO: avoid the allocation
return other.meet(new ConeType(this.getType()));
} else {
Assertions.UNREACHABLE("Unexpected type: " + rhs.getClass());
return null;
}
}
}
@Override
public String toString() {
return "point: " + type.toString();
}
@Override
public IClass getType() {
return type;
}
@Override
public TypeReference getTypeReference() {
return type.getReference();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PointType)) {
return false;
}
PointType other = (PointType) obj;
if (!type.getClassHierarchy().equals(other.type.getClassHierarchy())) {
Assertions.UNREACHABLE("different chas " + this + ' ' + other);
}
return type.equals(other.type);
}
@Override
public int hashCode() {
return 37 * type.hashCode();
}
public boolean isArrayType() {
return getType().isArrayClass();
}
public IClass getIClass() {
return type;
}
}
| 3,443
| 28.689655
| 89
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/PrimitiveType.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.analysis.typeInference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.Map;
/**
* Abstraction of a primitive type. Subclasses will define the primitive type abstractions for a
* particular language.
*
* @see JavaPrimitiveType
*/
public abstract class PrimitiveType extends TypeAbstraction {
protected static final Map<TypeReference, PrimitiveType> referenceToType = HashMapFactory.make();
public static PrimitiveType getPrimitive(TypeReference reference) {
return referenceToType.get(reference);
}
protected final TypeReference reference;
protected final int size;
protected PrimitiveType(TypeReference reference, int size) {
this.reference = reference;
this.size = size;
referenceToType.put(reference, this);
}
@Override
public TypeAbstraction meet(TypeAbstraction rhs) {
if (rhs == TOP) {
return this;
} else if (rhs == this) {
return this;
} else if (rhs instanceof PrimitiveType) {
// the meet of two primitives is the smaller of the two types.
// in particular integer meet boolean == boolean
if (size() < ((PrimitiveType) rhs).size()) {
return this;
} else {
return rhs;
}
} else {
return TOP;
}
}
public int size() {
return size;
}
@Override
public int hashCode() {
return reference.hashCode();
}
@Override
public boolean equals(Object other) {
return this == other;
}
@Override
public IClass getType() {
return null;
}
@Override
public TypeReference getTypeReference() {
return reference;
}
@Override
public String toString() {
return reference.getName().toString();
}
}
| 2,176
| 23.188889
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/TypeAbstraction.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.analysis.typeInference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.ContextItem;
import com.ibm.wala.types.TypeReference;
/**
* Abstraction of a Java type. These are immutable.
*
* @see TypeInference
*/
public abstract class TypeAbstraction implements ContextItem {
/** Canonical element representing TOP for a dataflow lattice */
public static final TypeAbstraction TOP =
new TypeAbstraction() {
@Override
public TypeAbstraction meet(TypeAbstraction rhs) {
return rhs;
}
@Override
public String toString() {
return "WalaTypeAbstraction.TOP";
}
@Override
public int hashCode() {
return 17;
}
@Override
public boolean equals(Object other) {
return this == other;
}
@Override
public IClass getType() {
return null;
}
@Override
public TypeReference getTypeReference() {
return null;
}
};
public abstract TypeAbstraction meet(TypeAbstraction rhs);
@Override
public abstract boolean equals(Object obj);
@Override
public abstract int hashCode();
/** A TypeReference representing the types of this abstraction */
public abstract TypeReference getTypeReference();
/**
* This is here for convenience; it makes sense for Point and Cone Dispatch. TODO: probably should
* get rid of it.
*
* @throws UnsupportedOperationException unconditionally
*/
public IClass getType() throws UnsupportedOperationException {
throw new UnsupportedOperationException("getType not implemented for " + getClass());
}
}
| 2,092
| 25.1625
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/TypeInference.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.analysis.typeInference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.util.CancelRuntimeException;
import com.ibm.wala.dataflow.ssa.SSAInference;
import com.ibm.wala.fixedpoint.impl.NullaryOperator;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.FixedPointConstants;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.IVisitorWithAddresses;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAAddressOfInstruction;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadIndirectInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAStoreIndirectInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
import com.ibm.wala.ssa.SymbolTable;
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.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collection;
import java.util.Iterator;
/** This class performs intraprocedural type propagation on an SSA IR. */
public class TypeInference extends SSAInference<TypeVariable> implements FixedPointConstants {
private static final boolean DEBUG = false;
public static TypeInference make(IR ir, boolean doPrimitives) {
return new TypeInference(ir, doPrimitives);
}
/** The governing SSA form */
protected final IR ir;
/** The governing class hierarchy */
protected final IClassHierarchy cha;
protected final Language language;
/** A singleton instance of the phi operator. */
private static final AbstractOperator<TypeVariable> phiOp = new PhiOperator();
private static final AbstractOperator<TypeVariable> primitivePropagateOp =
new PrimitivePropagateOperator();
/** A cone type for java.lang.Object */
protected final TypeAbstraction BOTTOM;
/** A singleton instance of the pi operator. */
private static final PiOperator piOp = new PiOperator();
/** should type inference track primitive types? */
protected final boolean doPrimitives;
private boolean solved = false;
protected TypeInference(IR ir, boolean doPrimitives) {
if (ir == null) {
throw new IllegalArgumentException("ir is null");
}
this.language = ir.getMethod().getDeclaringClass().getClassLoader().getLanguage();
this.cha = ir.getMethod().getDeclaringClass().getClassHierarchy();
this.ir = ir;
this.doPrimitives = doPrimitives;
this.BOTTOM = new ConeType(cha.getRootClass());
initialize();
solve();
}
public boolean solve() {
return solve(null);
}
@Override
public boolean solve(IProgressMonitor monitor) {
try {
if (solved) {
return false;
} else {
boolean result = super.solve(null);
solved = true;
return result;
}
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
}
protected void initialize() {
init(ir, this.new TypeVarFactory(), this.new TypeOperatorFactory());
}
@Override
protected void initializeVariables() {
if (DEBUG) {
System.err.println("initializeVariables " + ir.getMethod());
}
int[] parameterValueNumbers = ir.getParameterValueNumbers();
for (int i = 0; i < parameterValueNumbers.length; i++) {
TypeVariable v = getVariable(parameterValueNumbers[i]);
TypeReference t = ir.getParameterType(i);
if (DEBUG) {
System.err.println("parameter " + parameterValueNumbers[i] + ' ' + t);
}
if (t.isReferenceType()) {
IClass klass = cha.lookupClass(t);
if (DEBUG) {
System.err.println("klass " + klass);
}
if (klass != null) {
v.setType(new ConeType(klass));
} else {
// give up .. default to java.lang.Object (BOTTOM)
v.setType(BOTTOM);
}
} else if (doPrimitives) {
v.setType(language.getPrimitive(t));
}
}
SymbolTable st = ir.getSymbolTable();
if (st != null) {
for (int i = 0; i <= st.getMaxValueNumber(); i++) {
if (st.isConstant(i)) {
TypeVariable v = getVariable(i);
v.setType(getConstantType(i));
}
}
}
for (SSAInstruction s : Iterator2Iterable.make(ir.iterateNormalInstructions())) {
if (s instanceof SSAAbstractInvokeInstruction) {
SSAAbstractInvokeInstruction call = (SSAAbstractInvokeInstruction) s;
TypeVariable v = getVariable(call.getException());
Collection<TypeReference> defaultExceptions = call.getExceptionTypes();
if (defaultExceptions.size() == 0) {
continue;
}
Iterator<TypeReference> types = defaultExceptions.iterator();
TypeReference t = types.next();
IClass klass = cha.lookupClass(t);
if (klass == null) {
v.setType(BOTTOM);
} else {
v.setType(new PointType(klass));
}
while (types.hasNext()) {
t = types.next();
klass = cha.lookupClass(t);
if (klass != null) {
v.setType(v.getType().meet(new PointType(klass)));
}
}
IMethod m = cha.resolveMethod(call.getDeclaredTarget());
if (m != null) {
TypeReference[] x = null;
try {
x = m.getDeclaredExceptions();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
} catch (UnsupportedOperationException e) {
x = new TypeReference[] {language.getThrowableType()};
}
if (x != null) {
for (TypeReference tx : x) {
IClass tc = cha.lookupClass(tx);
if (tc != null) {
v.setType(v.getType().meet(new ConeType(tc)));
}
}
}
}
}
}
}
@Override
protected void initializeWorkList() {
addAllStatementsToWorkList();
}
/** An operator which initializes a type to a declared type. */
protected static final class DeclaredTypeOperator extends NullaryOperator<TypeVariable> {
private final TypeAbstraction type;
public DeclaredTypeOperator(TypeAbstraction type) {
assert type != null;
this.type = type;
}
/** Note that we need evaluate this operator at most once */
@Override
public byte evaluate(TypeVariable lhs) {
if (lhs.type.equals(type)) {
return NOT_CHANGED_AND_FIXED;
} else {
lhs.setType(type);
return CHANGED_AND_FIXED;
}
}
/** @see java.lang.Object#toString() */
@Override
public String toString() {
return "delared type := " + type;
}
public static boolean isNullary() {
return true;
}
@Override
public int hashCode() {
return 9931 * type.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof DeclaredTypeOperator) {
DeclaredTypeOperator d = (DeclaredTypeOperator) o;
return type.equals(d.type);
} else {
return false;
}
}
}
private static final class PhiOperator extends AbstractOperator<TypeVariable> {
private PhiOperator() {}
/** TODO: work on efficiency shortcuts for this. */
@Override
public byte evaluate(TypeVariable lhs, TypeVariable[] rhs) {
if (DEBUG) {
System.err.print("PhiOperator.meet " + lhs + ' ');
for (IVariable<?> v : rhs) {
System.err.print(v + " ");
}
System.err.println();
}
TypeAbstraction lhsType = lhs.getType();
TypeAbstraction meet = TypeAbstraction.TOP;
for (TypeVariable r : rhs) {
if (r != null && r.getType() != null) {
meet = meet.meet(r.getType());
}
}
if (lhsType.equals(meet)) {
return NOT_CHANGED;
} else {
lhs.setType(meet);
return CHANGED;
}
}
@Override
public String toString() {
return "phi meet";
}
@Override
public int hashCode() {
return 9929;
}
@Override
public boolean equals(Object o) {
return (o instanceof PhiOperator);
}
}
private static final class PiOperator extends AbstractOperator<TypeVariable> {
private PiOperator() {}
/** TODO: work on efficiency shortcuts for this. */
@Override
public byte evaluate(TypeVariable lhs, TypeVariable[] rhsOperands) {
TypeAbstraction lhsType = lhs.getType();
TypeVariable rhs = rhsOperands[0];
TypeAbstraction rhsType = rhs.getType();
if (lhsType.equals(rhsType)) {
return NOT_CHANGED;
} else {
lhs.setType(rhsType);
return CHANGED;
}
}
@Override
public String toString() {
return "pi";
}
@Override
public int hashCode() {
return 9929 * 13;
}
@Override
public boolean equals(Object o) {
return (o instanceof PiOperator);
}
}
protected static class PrimitivePropagateOperator extends AbstractOperator<TypeVariable> {
protected PrimitivePropagateOperator() {}
@Override
public byte evaluate(TypeVariable lhs, TypeVariable[] rhs) {
TypeAbstraction lhsType = lhs.getType();
TypeAbstraction meet = TypeAbstraction.TOP;
for (TypeVariable r : rhs) {
if (r != null && r.getType() != null) {
meet = meet.meet(r.getType());
}
}
if (lhsType.equals(meet)) {
return NOT_CHANGED;
} else {
lhs.setType(meet);
return CHANGED;
}
}
@Override
public String toString() {
return "propagate";
}
@Override
public int hashCode() {
return 99292;
}
@Override
public boolean equals(Object o) {
return o != null && o.getClass().equals(getClass());
}
}
/**
* This operator will extract the element type from an arrayref in an array access instruction
*
* <p>TODO: why isn't this a nullary operator?
*/
private final class GetElementType extends AbstractOperator<TypeVariable> {
private final SSAArrayLoadInstruction load;
GetElementType(SSAArrayLoadInstruction load) {
this.load = load;
}
@Override
public byte evaluate(TypeVariable lhs, TypeVariable[] rhs) {
TypeAbstraction arrayType = getType(load.getArrayRef());
if (arrayType == null || arrayType.equals(TypeAbstraction.TOP)) {
return NOT_CHANGED;
}
TypeReference elementType = null;
if (arrayType instanceof PointType) {
elementType = ((PointType) arrayType).getType().getReference().getArrayElementType();
} else if (arrayType instanceof ConeType) {
elementType = ((ConeType) arrayType).getType().getReference().getArrayElementType();
} else {
Assertions.UNREACHABLE("Unexpected type " + arrayType.getClass());
}
if (elementType.isPrimitiveType()) {
if (doPrimitives && lhs.getType() == TypeAbstraction.TOP) {
lhs.setType(PrimitiveType.getPrimitive(elementType));
return CHANGED;
}
return NOT_CHANGED;
}
if (lhs.getType() != TypeAbstraction.TOP) {
TypeReference tType = null;
if (lhs.getType() instanceof PointType) {
tType = ((PointType) lhs.getType()).getType().getReference();
} else if (lhs.getType() instanceof ConeType) {
tType = ((ConeType) lhs.getType()).getType().getReference();
} else {
Assertions.UNREACHABLE("Unexpected type " + lhs.getType().getClass());
}
if (tType.equals(elementType)) {
return NOT_CHANGED;
} else {
IClass klass = cha.lookupClass(elementType);
assert klass != null;
lhs.setType(new ConeType(klass));
return CHANGED;
}
} else {
IClass klass = cha.lookupClass(elementType);
if (klass != null) {
lhs.setType(new ConeType(klass));
} else {
lhs.setType(TypeAbstraction.TOP);
}
return CHANGED;
}
}
@Override
public String toString() {
return "getElementType " + load;
}
@Override
public int hashCode() {
return 9923 * load.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof GetElementType) {
GetElementType other = (GetElementType) o;
return load.equals(other.load);
} else {
return false;
}
}
}
protected class TypeOperatorFactory extends SSAInstruction.Visitor
implements IVisitorWithAddresses, OperatorFactory<TypeVariable> {
protected AbstractOperator<TypeVariable> result = null;
@Override
public AbstractOperator<TypeVariable> get(SSAInstruction instruction) {
instruction.visit(this);
AbstractOperator<TypeVariable> temp = result;
result = null;
return temp;
}
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
result = new GetElementType(instruction);
}
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
if (!doPrimitives) {
result = null;
} else {
result = new DeclaredTypeOperator(language.getPrimitive(language.getConstantType(1)));
}
}
@Override
public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {
IClass jlClassKlass = cha.lookupClass(instruction.getType());
assert jlClassKlass != null;
result = new DeclaredTypeOperator(new ConeType(jlClassKlass));
}
@Override
public void visitGet(SSAGetInstruction instruction) {
TypeReference type = instruction.getDeclaredFieldType();
if (doPrimitives && type.isPrimitiveType()) {
PrimitiveType p = language.getPrimitive(type);
assert p != null : "no type for " + type;
result = new DeclaredTypeOperator(p);
} else {
IClass klass = cha.lookupClass(type);
if (klass == null) {
// get from a field of a type that cannot be loaded.
// be pessimistic
result = new DeclaredTypeOperator(BOTTOM);
} else {
result = new DeclaredTypeOperator(new ConeType(klass));
}
}
}
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
TypeReference type = instruction.getDeclaredResultType();
if (type.isReferenceType()) {
IClass klass = cha.lookupClass(type);
if (klass == null) {
// a type that cannot be loaded.
// be pessimistic
result = new DeclaredTypeOperator(BOTTOM);
} else {
result = new DeclaredTypeOperator(new ConeType(klass));
}
} else if (doPrimitives && type.isPrimitiveType()) {
result = new DeclaredTypeOperator(language.getPrimitive(type));
} else {
result = null;
}
}
@Override
public void visitNew(SSANewInstruction instruction) {
TypeReference type = instruction.getConcreteType();
IClass klass = cha.lookupClass(type);
if (klass == null) {
// a type that cannot be loaded.
// be pessimistic
result = new DeclaredTypeOperator(BOTTOM);
} else {
result = new DeclaredTypeOperator(new PointType(klass));
}
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
TypeAbstraction typeAbs = null;
for (TypeReference type : instruction.getDeclaredResultTypes()) {
IClass klass = cha.lookupClass(type);
if (klass == null) {
// a type that cannot be loaded.
// be pessimistic
typeAbs = BOTTOM;
} else {
TypeAbstraction x = null;
if (doPrimitives && type.isPrimitiveType()) {
x = language.getPrimitive(type);
} else if (type.isReferenceType()) {
x = new ConeType(klass);
}
if (x != null) {
if (typeAbs == null) {
typeAbs = x;
} else {
typeAbs = typeAbs.meet(x);
}
}
}
}
result = new DeclaredTypeOperator(typeAbs);
}
@Override
public void visitConversion(SSAConversionInstruction instruction) {
if (doPrimitives) {
result = new DeclaredTypeOperator(language.getPrimitive(instruction.getToType()));
}
}
@Override
public void visitComparison(SSAComparisonInstruction instruction) {
if (doPrimitives) {
result = new DeclaredTypeOperator(language.getPrimitive(language.getConstantType(0)));
}
}
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {
if (doPrimitives) {
result = primitivePropagateOp;
}
}
@Override
public void visitUnaryOp(SSAUnaryOpInstruction instruction) {
if (doPrimitives) {
result = primitivePropagateOp;
}
}
@Override
public void visitInstanceof(SSAInstanceofInstruction instruction) {
if (doPrimitives) {
result =
new DeclaredTypeOperator(language.getPrimitive(language.getConstantType(Boolean.TRUE)));
}
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
TypeAbstraction type = meetDeclaredExceptionTypes(instruction);
result = new DeclaredTypeOperator(type);
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
result = phiOp;
}
@Override
public void visitPi(SSAPiInstruction instruction) {
result = piOp;
}
private TypeAbstraction meetDeclaredExceptionTypes(SSAGetCaughtExceptionInstruction s) {
ExceptionHandlerBasicBlock bb =
(ExceptionHandlerBasicBlock) ir.getControlFlowGraph().getNode(s.getBasicBlockNumber());
Iterator<TypeReference> it = bb.getCaughtExceptionTypes();
TypeReference t = it.next();
IClass klass = cha.lookupClass(t);
TypeAbstraction result = null;
if (klass == null) {
// a type that cannot be loaded.
// be pessimistic
result = BOTTOM;
} else {
result = new ConeType(klass);
}
while (it.hasNext()) {
t = it.next();
IClass tClass = cha.lookupClass(t);
if (tClass == null) {
result = BOTTOM;
} else {
result = result.meet(new ConeType(tClass));
}
}
return result;
}
private DeclaredTypeOperator getPointerTypeOperator(TypeReference type) {
if (type.isPrimitiveType()) {
return new DeclaredTypeOperator(language.getPrimitive(type));
} else {
IClass klass = cha.lookupClass(type);
if (klass == null) {
// a type that cannot be loaded.
// be pessimistic
return new DeclaredTypeOperator(BOTTOM);
} else {
return new DeclaredTypeOperator(new ConeType(klass));
}
}
}
@Override
public void visitAddressOf(SSAAddressOfInstruction instruction) {
TypeReference type = language.getPointerType(instruction.getType());
result = getPointerTypeOperator(type);
}
@Override
public void visitLoadIndirect(SSALoadIndirectInstruction instruction) {
result = getPointerTypeOperator(instruction.getLoadedType());
}
@Override
public void visitStoreIndirect(SSAStoreIndirectInstruction instruction) {
Assertions.UNREACHABLE();
}
}
public class TypeVarFactory implements VariableFactory<TypeVariable> {
@Override
public TypeVariable makeVariable(int valueNumber) {
if (doPrimitives) {
SymbolTable st = ir.getSymbolTable();
if (st.isConstant(valueNumber)) {
if (st.isBooleanConstant(valueNumber)) {
return new TypeVariable(language.getPrimitive(language.getConstantType(Boolean.TRUE)));
}
}
}
return new TypeVariable(TypeAbstraction.TOP);
}
}
public IR getIR() {
return ir;
}
/** Return the type computed for a particular value number */
public TypeAbstraction getType(int valueNumber) {
if (valueNumber < 0) {
throw new IllegalArgumentException("bad value number " + valueNumber);
}
TypeVariable variable = getVariable(valueNumber);
assert variable != null : "null variable for value number " + valueNumber;
return variable.getType();
}
public TypeAbstraction getConstantType(int valueNumber) {
if (ir.getSymbolTable().isStringConstant(valueNumber)) {
return new PointType(cha.lookupClass(language.getStringType()));
} else {
return getConstantPrimitiveType(valueNumber);
}
}
public TypeAbstraction getConstantPrimitiveType(int valueNumber) {
SymbolTable st = ir.getSymbolTable();
if (!st.isConstant(valueNumber) || st.isNullConstant(valueNumber)) {
return TypeAbstraction.TOP;
} else {
return language.getPrimitive(language.getConstantType(st.getConstantValue(valueNumber)));
}
}
public boolean isUndefined(int valueNumber) {
// TODO: Julian, you seem to be using BOTTOM in the European style.
// Steve's code assumes American style (god forbid), so what you're getting
// here
// is not undefined, but java.lang.Object [NR/EY]
if (getVariable(valueNumber) == null) {
return true;
}
TypeAbstraction ta = getVariable(valueNumber).getType();
return ta == BOTTOM || ta.getType() == null;
}
/**
* Extract all results of the type inference analysis.
*
* @return an array, where the i'th variable holds the type abstraction of the i'th value number.
*/
public TypeAbstraction[] extractAllResults() {
int numberOfVars = ir.getSymbolTable().getMaxValueNumber() + 1;
TypeAbstraction[] ret = new TypeAbstraction[numberOfVars];
for (int i = 0; i < numberOfVars; ++i) {
TypeVariable var = getVariable(i);
ret[i] = var == null ? null : var.getType();
}
return ret;
}
@Override
protected TypeVariable[] makeStmtRHS(int size) {
return new TypeVariable[size];
}
}
| 23,492
| 29.080666
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/analysis/typeInference/TypeVariable.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.analysis.typeInference;
import com.ibm.wala.fixpoint.AbstractVariable;
/**
* A type variable in the dataflow system for type inference.
*
* @see TypeInference
*/
public class TypeVariable extends AbstractVariable<TypeVariable> {
TypeAbstraction type;
public TypeVariable(TypeAbstraction type) {
if (type == null) {
throw new IllegalArgumentException("null type");
}
this.type = type;
}
@Override
public void copyState(TypeVariable other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("v == null");
}
this.type = other.type;
}
public TypeAbstraction getType() {
return type;
}
public void setType(TypeAbstraction type) {
this.type = type;
}
@Override
public String toString() {
return type.toString();
}
}
| 1,231
| 22.692308
| 77
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/AbstractCFG.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.cfg;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.util.collections.CompoundIterator;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.IteratorPlusOne;
import com.ibm.wala.util.collections.IteratorPlusTwo;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.collections.SimpleVector;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.graph.impl.DelegatingNumberedNodeManager;
import com.ibm.wala.util.graph.impl.NumberedNodeIterator;
import com.ibm.wala.util.graph.impl.SparseNumberedEdgeManager;
import com.ibm.wala.util.intset.BasicNaturalRelation;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.FixedSizeBitVector;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.SimpleIntVector;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
/** Common functionality for {@link ControlFlowGraph} implementations. */
public abstract class AbstractCFG<I, T extends IBasicBlock<I>>
implements ControlFlowGraph<I, T>, MinimalCFG<T>, Constants {
/** The method this AbstractCFG represents */
private final IMethod method;
/** An object to track nodes in this cfg */
private final DelegatingNumberedNodeManager<T> nodeManager =
new DelegatingNumberedNodeManager<>();
/** An object to track most normal edges in this cfg */
private final SparseNumberedEdgeManager<T> normalEdgeManager =
new SparseNumberedEdgeManager<>(nodeManager, 2, BasicNaturalRelation.SIMPLE);
/** An object to track not-to-exit exceptional edges in this cfg */
private final SparseNumberedEdgeManager<T> exceptionalEdgeManager =
new SparseNumberedEdgeManager<>(nodeManager, 0, BasicNaturalRelation.SIMPLE);
/**
* An object to track not-to-exit exceptional edges in this cfg, indexed by block number.
* exceptionalEdges[i] is a list of block numbers that are non-exit exceptional successors of
* block i, in order of increasing "catch scope".
*/
private final SimpleVector<SimpleIntVector> exceptionalSuccessors = new SimpleVector<>();
/** Which basic blocks have a normal edge to exit()? */
private FixedSizeBitVector normalToExit;
/** Which basic blocks have an exceptional edge to exit()? */
private FixedSizeBitVector exceptionalToExit;
/** Which basic blocks have a fall-through? */
private FixedSizeBitVector fallThru;
/** Which basic blocks are catch blocks? */
private final BitVector catchBlocks;
/** Cache here for efficiency */
private T exit;
protected AbstractCFG(IMethod method) {
this.method = method;
this.catchBlocks = new BitVector(10);
}
/** subclasses must call this before calling addEdge, but after creating the nodes */
protected void init() {
normalToExit = new FixedSizeBitVector(getMaxNumber() + 1);
exceptionalToExit = new FixedSizeBitVector(getMaxNumber() + 1);
fallThru = new FixedSizeBitVector(getMaxNumber() + 1);
exit = getNode(getMaxNumber());
}
@Override
public abstract boolean equals(Object o);
@Override
public abstract int hashCode();
/** Return the entry basic block for the CFG. */
@Override
public T entry() {
return getNode(0);
}
/** Return the exit basic block for the CFG. */
@Override
public T exit() {
return exit;
}
@Override
public int getPredNodeCount(T N) {
if (N == null) {
throw new IllegalArgumentException("N is null");
}
if (N.equals(exit())) {
// TODO: cache if necessary
FixedSizeBitVector x = FixedSizeBitVector.or(normalToExit, exceptionalToExit);
return x.populationCount();
} else {
boolean normalIn = getNumberOfNormalIn(N) > 0;
boolean exceptionalIn = getNumberOfExceptionalIn(N) > 0;
if (normalIn) {
if (exceptionalIn) {
return Iterator2Collection.toSet(getPredNodes(N)).size();
} else {
return getNumberOfNormalIn(N);
}
} else {
return getNumberOfExceptionalIn(N);
}
}
}
public int getNumberOfNormalIn(T N) {
if (N == null) {
throw new IllegalArgumentException("N is null");
}
assert !N.equals(exit());
int number = getNumber(N);
int xtra = 0;
if (number > 0) {
if (fallThru.get(number - 1)) {
xtra++;
}
}
return normalEdgeManager.getPredNodeCount(N) + xtra;
}
public int getNumberOfExceptionalIn(T N) {
if (N == null) {
throw new IllegalArgumentException("N is null");
}
assert !N.equals(exit());
return exceptionalEdgeManager.getPredNodeCount(N);
}
/** @param number number of a basic block in this cfg */
boolean hasAnyNormalOut(int number) {
return (fallThru.get(number)
|| normalEdgeManager.getSuccNodeCount(number) > 0
|| normalToExit.get(number));
}
/** @param number number of a basic block in this cfg */
private int getNumberOfNormalOut(int number) {
int xtra = 0;
if (fallThru.get(number)) {
xtra++;
}
if (normalToExit.get(number)) {
xtra++;
}
return normalEdgeManager.getSuccNodeCount(number) + xtra;
}
/** @param number number of a basic block in this cfg */
public int getNumberOfExceptionalOut(int number) {
int xtra = 0;
if (exceptionalToExit.get(number)) {
xtra++;
}
return exceptionalEdgeManager.getSuccNodeCount(number) + xtra;
}
public int getNumberOfNormalOut(T N) {
return getNumberOfNormalOut(getNumber(N));
}
public int getNumberOfExceptionalOut(final T N) {
return getNumberOfExceptionalOut(getNumber(N));
}
@Override
public Iterator<T> getPredNodes(T N) {
if (N == null) {
throw new IllegalArgumentException("N is null");
}
if (N.equals(exit())) {
return new FilterIterator<>(
iterator(),
o -> {
int i = getNumber(o);
return normalToExit.get(i) || exceptionalToExit.get(i);
});
} else {
int number = getNumber(N);
boolean normalIn = getNumberOfNormalIn(N) > 0;
boolean exceptionalIn = getNumberOfExceptionalIn(N) > 0;
if (normalIn) {
if (exceptionalIn) {
HashSet<T> result =
HashSetFactory.make(getNumberOfNormalIn(N) + getNumberOfExceptionalIn(N));
result.addAll(Iterator2Collection.toSet(normalEdgeManager.getPredNodes(N)));
result.addAll(Iterator2Collection.toSet(exceptionalEdgeManager.getPredNodes(N)));
if (fallThru.get(number - 1)) {
result.add(getNode(number - 1));
}
return result.iterator();
} else {
if (number > 0 && fallThru.get(number - 1)) {
return IteratorPlusOne.make(normalEdgeManager.getPredNodes(N), getNode(number - 1));
} else {
return normalEdgeManager.getPredNodes(N);
}
}
} else {
// !normalIn
if (exceptionalIn) {
return exceptionalEdgeManager.getPredNodes(N);
} else {
return EmptyIterator.instance();
}
}
}
}
@Override
public int getSuccNodeCount(T N) {
if (N == null) {
throw new IllegalArgumentException("N is null");
}
if (N.equals(exit())) {
return 0;
}
int nNormal = getNumberOfNormalOut(N);
int nExc = getNumberOfExceptionalOut(N);
if (nNormal > 0) {
if (nExc > 0) {
if (nExc == 1) {
int number = getNumber(N);
if (exceptionalToExit.get(number)) {
if (normalToExit.get(number)) {
return nNormal + nExc - 1;
} else {
return nNormal + nExc;
}
} else {
return slowCountSuccNodes(N);
}
} else {
return slowCountSuccNodes(N);
}
} else {
return nNormal;
}
} else {
// nNormal == 0
return nExc;
}
}
private int slowCountSuccNodes(T N) {
return Iterator2Collection.toSet(getSuccNodes(N)).size();
}
@Override
public Iterator<T> getSuccNodes(T N) {
int number = getNumber(N);
if (normalToExit.get(number) && exceptionalToExit.get(number)) {
return new CompoundIterator<>(
iterateNormalSuccessorsWithoutExit(number), iterateExceptionalSuccessors(number));
} else {
return new CompoundIterator<>(
iterateNormalSuccessors(number), iterateExceptionalSuccessors(number));
}
}
/**
* @param number of a basic block
* @return the exceptional successors of the basic block, in order of increasing catch scope.
*/
private Iterator<T> iterateExceptionalSuccessors(int number) {
if (exceptionalEdgeManager.hasAnySuccessor(number)) {
SimpleIntVector v = exceptionalSuccessors.get(number);
List<T> result = new ArrayList<>(v.getMaxIndex() + 1);
for (int i = 0; i <= v.getMaxIndex(); i++) {
result.add(getNode(v.get(i)));
}
if (exceptionalToExit.get(number)) {
result.add(exit);
}
return result.iterator();
} else {
if (exceptionalToExit.get(number)) {
return new NonNullSingletonIterator<>(exit());
} else {
return EmptyIterator.instance();
}
}
}
Iterator<T> iterateExceptionalPredecessors(T N) {
if (N.equals(exit())) {
return new FilterIterator<>(
iterator(),
o -> {
int i = getNumber(o);
return exceptionalToExit.get(i);
});
} else {
return exceptionalEdgeManager.getPredNodes(N);
}
}
Iterator<T> iterateNormalPredecessors(T N) {
if (N.equals(exit())) {
return new FilterIterator<>(
iterator(),
o -> {
int i = getNumber(o);
return normalToExit.get(i);
});
} else {
int number = getNumber(N);
if (number > 0 && fallThru.get(number - 1)) {
return IteratorPlusOne.make(normalEdgeManager.getPredNodes(N), getNode(number - 1));
} else {
return normalEdgeManager.getPredNodes(N);
}
}
}
private Iterator<T> iterateNormalSuccessors(int number) {
if (fallThru.get(number)) {
if (normalToExit.get(number)) {
return new IteratorPlusTwo<>(
normalEdgeManager.getSuccNodes(number), getNode(number + 1), exit());
} else {
return IteratorPlusOne.make(normalEdgeManager.getSuccNodes(number), getNode(number + 1));
}
} else {
if (normalToExit.get(number)) {
return IteratorPlusOne.make(normalEdgeManager.getSuccNodes(number), exit());
} else {
return normalEdgeManager.getSuccNodes(number);
}
}
}
private Iterator<T> iterateNormalSuccessorsWithoutExit(int number) {
if (fallThru.get(number)) {
return IteratorPlusOne.make(normalEdgeManager.getSuccNodes(number), getNode(number + 1));
} else {
return normalEdgeManager.getSuccNodes(number);
}
}
@Override
public void addNode(T n) {
nodeManager.addNode(n);
}
@Override
public int getMaxNumber() {
return nodeManager.getMaxNumber();
}
@Override
public T getNode(int number) {
return nodeManager.getNode(number);
}
@Override
public int getNumber(T N) {
return nodeManager.getNumber(N);
}
@Override
public int getNumberOfNodes() {
return nodeManager.getNumberOfNodes();
}
@Override
public Iterator<T> iterator() {
return nodeManager.iterator();
}
@Override
public Stream<T> stream() {
return nodeManager.stream();
}
@Override
public void addEdge(T src, T dst) throws UnimplementedError {
Assertions.UNREACHABLE("Don't call me .. use addNormalEdge or addExceptionalEdge");
}
@Override
public void removeEdge(T src, T dst) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public boolean hasEdge(T src, T dst) {
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
int x = getNumber(src);
if (dst.equals(exit())) {
return normalToExit.get(x) || exceptionalToExit.get(x);
} else if (getNumber(dst) == (x + 1) && fallThru.get(x)) {
return true;
}
return normalEdgeManager.hasEdge(src, dst) || exceptionalEdgeManager.hasEdge(src, dst);
}
public boolean hasExceptionalEdge(T src, T dst) {
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
int x = getNumber(src);
if (dst.equals(exit())) {
return exceptionalToExit.get(x);
}
return exceptionalEdgeManager.hasEdge(src, dst);
}
public boolean hasNormalEdge(T src, T dst) {
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
int x = getNumber(src);
if (dst.equals(exit())) {
return normalToExit.get(x);
} else if (getNumber(dst) == (x + 1) && fallThru.get(x)) {
return true;
}
return normalEdgeManager.hasEdge(src, dst);
}
/** @throws IllegalArgumentException if src or dst is null */
public void addNormalEdge(T src, T dst) {
if (src == null) {
throw new IllegalArgumentException("src is null");
}
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
if (dst.equals(exit())) {
normalToExit.set(getNumber(src));
} else if (getNumber(dst) == (getNumber(src) + 1)) {
fallThru.set(getNumber(src));
} else {
normalEdgeManager.addEdge(src, dst);
}
}
/** @throws IllegalArgumentException if dst is null */
public void addExceptionalEdge(T src, T dst) {
if (dst == null) {
throw new IllegalArgumentException("dst is null");
}
if (dst.equals(exit())) {
exceptionalToExit.set(getNumber(src));
} else {
exceptionalEdgeManager.addEdge(src, dst);
SimpleIntVector v = exceptionalSuccessors.get(getNumber(src));
if (v == null) {
v = new SimpleIntVector(-1);
exceptionalSuccessors.set(getNumber(src), v);
v.set(0, getNumber(dst));
return;
}
if (v.get(v.getMaxIndex()) != getNumber(dst)) {
v.set(v.getMaxIndex() + 1, getNumber(dst));
}
}
}
/** @see com.ibm.wala.util.graph.Graph#removeNode(Object) */
@Override
public void removeNodeAndEdges(T N) throws UnimplementedError {
Assertions.UNREACHABLE();
}
/** @see com.ibm.wala.util.graph.NodeManager#removeNode(Object) */
@Override
public void removeNode(T n) throws UnimplementedError {
Assertions.UNREACHABLE();
}
/** @see com.ibm.wala.util.graph.NodeManager#containsNode(Object) */
@Override
public boolean containsNode(T N) {
return nodeManager.containsNode(N);
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (T bb : this) {
s.append("BB").append(getNumber(bb)).append('\n');
Iterator<T> succNodes = getSuccNodes(bb);
while (succNodes.hasNext()) {
s.append(" -> BB").append(getNumber(succNodes.next())).append('\n');
}
}
return s.toString();
}
/** record that basic block i is a catch block */
protected void setCatchBlock(int i) {
catchBlocks.set(i);
}
/** @return true iff block i is a catch block */
public boolean isCatchBlock(int i) {
return catchBlocks.get(i);
}
/** Returns the catchBlocks. */
@Override
public BitVector getCatchBlocks() {
return catchBlocks;
}
@Override
public IMethod getMethod() {
return method;
}
/** @see com.ibm.wala.util.graph.EdgeManager#removeAllIncidentEdges(Object) */
@Override
public void removeAllIncidentEdges(T node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public List<T> getExceptionalSuccessors(T b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
List<T> result = new ArrayList<>();
for (T s : Iterator2Iterable.make(iterateExceptionalSuccessors(b.getNumber()))) {
result.add(s);
}
return result;
}
@Override
public Collection<T> getNormalSuccessors(T b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
return Iterator2Collection.toSet(iterateNormalSuccessors(b.getNumber()));
}
/**
* @see com.ibm.wala.util.graph.NumberedNodeManager#iterateNodes(com.ibm.wala.util.intset.IntSet)
*/
@Override
public Iterator<T> iterateNodes(IntSet s) {
return new NumberedNodeIterator<>(s, this);
}
@Override
public void removeIncomingEdges(T node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
@Override
public void removeOutgoingEdges(T node) throws UnimplementedError {
Assertions.UNREACHABLE();
}
public FixedSizeBitVector getExceptionalToExit() {
return exceptionalToExit;
}
public FixedSizeBitVector getNormalToExit() {
return normalToExit;
}
@Override
public Collection<T> getExceptionalPredecessors(T b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
return Iterator2Collection.toSet(iterateExceptionalPredecessors(b));
}
@Override
public Collection<T> getNormalPredecessors(T b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
return Iterator2Collection.toSet(iterateNormalPredecessors(b));
}
@Override
public IntSet getPredNodeNumbers(T node) throws UnimplementedError {
Assertions.UNREACHABLE();
return null;
}
/*
* TODO: optimize this.
*/
@Override
public IntSet getSuccNodeNumbers(T node) {
int number = getNumber(node);
IntSet s = normalEdgeManager.getSuccNodeNumbers(node);
MutableSparseIntSet result =
s == null ? MutableSparseIntSet.makeEmpty() : MutableSparseIntSet.make(s);
s = exceptionalEdgeManager.getSuccNodeNumbers(node);
if (s != null) {
result.addAll(s);
}
if (normalToExit.get(number) || exceptionalToExit.get(number)) {
result.add(exit.getNumber());
}
if (fallThru.get(number)) {
result.add(number + 1);
}
return result;
}
}
| 18,928
| 28.392857
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/BytecodeCFG.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.cfg;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import java.util.Set;
public interface BytecodeCFG {
Set<ExceptionHandler> getExceptionHandlers();
}
| 554
| 26.75
| 72
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/CFGSanitizer.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.cfg;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSACFG.ExceptionHandlerBasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.impl.SlowSparseNumberedGraph;
import java.util.Collection;
/** Utility class to remove exceptional edges to exit() from a CFG */
public class CFGSanitizer {
/**
* Return a view of the {@link ControlFlowGraph} for an {@link IR}, which elides all exceptional
* exits from PEIs in the IR.
*/
public static Graph<ISSABasicBlock> sanitize(IR ir, IClassHierarchy cha)
throws IllegalArgumentException, WalaException {
if (ir == null) {
throw new IllegalArgumentException("ir cannot be null");
}
ControlFlowGraph<SSAInstruction, ISSABasicBlock> cfg = ir.getControlFlowGraph();
Graph<ISSABasicBlock> g = SlowSparseNumberedGraph.make();
// add all nodes to the graph
for (ISSABasicBlock basicBlock : cfg) {
g.addNode(basicBlock);
}
// add all edges to the graph, except those that go to exit
for (ISSABasicBlock b : cfg) {
for (ISSABasicBlock b2 : Iterator2Iterable.make(cfg.getSuccNodes(b))) {
if (!b2.isExitBlock()) {
g.addEdge(b, b2);
}
}
}
// now add edges to exit, ignoring undeclared exceptions
ISSABasicBlock exit = cfg.exit();
for (ISSABasicBlock b : Iterator2Iterable.make(cfg.getPredNodes(exit))) {
// for each predecessor of exit ...
SSAInstruction s = ir.getInstructions()[b.getLastInstructionIndex()];
if (s == null) {
// TODO: this shouldn't happen?
continue;
}
if (s instanceof SSAReturnInstruction
|| s instanceof SSAThrowInstruction
|| cfg.getSuccNodeCount(b) == 1) {
// return or athrow, or some statement which is not an athrow or return whose only successor
// is the exit node (can only
// occur in synthetic methods without a return statement? --MS); add edge to exit
g.addEdge(b, exit);
} else {
// compute types of exceptions the pei may throw
TypeReference[] exceptions = null;
try {
exceptions = computeExceptions(cha, ir, s);
} catch (InvalidClassFileException e1) {
e1.printStackTrace();
Assertions.UNREACHABLE();
}
// remove any exceptions that are caught by catch blocks
for (ISSABasicBlock c : Iterator2Iterable.make(cfg.getSuccNodes(b))) {
if (c.isCatchBlock()) {
SSACFG.ExceptionHandlerBasicBlock cb = (ExceptionHandlerBasicBlock) c;
for (TypeReference ex : Iterator2Iterable.make(cb.getCaughtExceptionTypes())) {
IClass exClass = cha.lookupClass(ex);
if (exClass == null) {
throw new WalaException("failed to find " + ex);
}
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] != null) {
IClass exi = cha.lookupClass(exceptions[i]);
if (exi == null) {
throw new WalaException("failed to find " + exceptions[i]);
}
if (cha.isSubclassOf(exi, exClass)) {
exceptions[i] = null;
}
}
}
}
}
}
// check the remaining uncaught exceptions
TypeReference[] declared = null;
try {
declared = ir.getMethod().getDeclaredExceptions();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
if (declared != null && exceptions != null) {
for (TypeReference exception : exceptions) {
boolean isDeclared = false;
if (exception != null) {
IClass exi = cha.lookupClass(exception);
if (exi == null) {
throw new WalaException("failed to find " + exception);
}
for (TypeReference element : declared) {
IClass dc = cha.lookupClass(element);
if (dc == null) {
throw new WalaException("failed to find " + element);
}
if (cha.isSubclassOf(exi, dc)) {
isDeclared = true;
break;
}
}
if (isDeclared) {
// found a declared exceptional edge
g.addEdge(b, exit);
}
}
}
}
}
}
return g;
}
/** What are the exception types which s may throw? */
private static TypeReference[] computeExceptions(IClassHierarchy cha, IR ir, SSAInstruction s)
throws InvalidClassFileException {
final Collection<TypeReference> c;
Language l = ir.getMethod().getDeclaringClass().getClassLoader().getLanguage();
if (s instanceof SSAInvokeInstruction) {
SSAInvokeInstruction call = (SSAInvokeInstruction) s;
c = l.inferInvokeExceptions(call.getDeclaredTarget(), cha);
} else {
c = s.getExceptionTypes();
}
return c == null ? null : c.toArray(new TypeReference[0]);
}
}
| 6,180
| 36.011976
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/ControlFlowGraph.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.cfg;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.intset.BitVector;
/** An interface that is common to the Shrike and SSA CFG implementations. */
public interface ControlFlowGraph<I, T extends IBasicBlock<I>>
extends NumberedGraph<T>, MinimalCFG<T> {
/** @return the indices of the catch blocks, as a bit vector */
BitVector getCatchBlocks();
/**
* @param index an instruction index
* @return the basic block which contains this instruction.
*/
T getBlockForInstruction(int index);
/** @return the instructions of this CFG, as an array. */
I[] getInstructions();
/**
* TODO: move this into IR?
*
* @param index an instruction index
* @return the program counter (bytecode index) corresponding to that instruction
*/
int getProgramCounter(int index);
/** @return the Method this CFG represents */
IMethod getMethod();
}
| 1,337
| 29.409091
| 83
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/IBasicBlock.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.cfg;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.util.graph.INodeWithNumber;
/** An interface for a basic block in a control flow graph. */
public interface IBasicBlock<InstType> extends INodeWithNumber, Iterable<InstType> {
/**
* Get the index of the first instruction in the basic block. The value is an index into the
* instruction array that contains all the instructions for the method.
*
* <p>If the result is < 0, the block has no instructions
*
* @return the instruction index for the first instruction in the basic block.
*/
int getFirstInstructionIndex();
/**
* Get the index of the last instruction in the basic block. The value is an index into the
* instruction array that contains all the instructions for the method.
*
* <p>If the result is < 0, the block has no instructions
*
* @return the instruction index for the last instruction in the basic block
*/
int getLastInstructionIndex();
/**
* Return true if the basic block represents a catch block.
*
* @return true if the basic block represents a catch block.
*/
boolean isCatchBlock();
/**
* Return true if the basic block represents the unique exit block.
*
* @return true if the basic block represents the unique exit block.
*/
boolean isExitBlock();
/**
* Return true if the basic block represents the unique entry block.
*
* @return true if the basic block represents the unique entry block.
*/
boolean isEntryBlock();
/** @return governing method for this block */
IMethod getMethod();
/**
* Each basic block should have a unique number in its cfg
*
* @return the basic block's number
*/
int getNumber();
}
| 2,128
| 28.985915
| 94
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/InducedCFG.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.cfg;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.util.collections.ArrayIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.GraphIntegrity;
import com.ibm.wala.util.graph.GraphIntegrity.UnsoundGraphException;
import com.ibm.wala.util.graph.impl.NodeWithNumber;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* A {@link ControlFlowGraph} computed from a set of {@link SSAInstruction} instructions.
*
* <p>This is a funny CFG ... we assume that there are always fallthru edges, even from throws and
* returns. It is extremely fragile and unsuited for flow-sensitive analysis. Someday this should be
* nuked.
*/
public class InducedCFG extends AbstractCFG<SSAInstruction, InducedCFG.BasicBlock> {
private static final boolean DEBUG = false;
/** A partial map from Instruction -> BasicBlock */
private final BasicBlock[] i2block;
private final Context context;
private final SSAInstruction[] instructions;
/**
* TODO: we do not yet support induced CFGS with exception handlers.
*
* <p>NOTE: SIDE EFFECT!!! ... nulls out phi instructions and pi instructions in the instruction
* array!
*
* @throws IllegalArgumentException if instructions is null
*/
public InducedCFG(SSAInstruction[] instructions, IMethod method, Context context) {
super(method);
if (instructions == null) {
throw new IllegalArgumentException("instructions is null");
}
if (method == null) {
throw new IllegalArgumentException("method is null");
}
this.context = context;
this.instructions = instructions;
if (DEBUG) {
System.err.println(("compute InducedCFG: " + method));
}
i2block = new BasicBlock[instructions.length];
if (instructions.length == 0) {
makeEmptyBlocks();
} else {
makeBasicBlocks();
}
init();
computeEdges();
if (DEBUG) {
try {
GraphIntegrity.check(this);
} catch (UnsoundGraphException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
}
}
@Override
public int hashCode() {
return context.hashCode() ^ getMethod().hashCode();
}
@Override
public boolean equals(Object o) {
return (o instanceof InducedCFG)
&& getMethod().equals(((InducedCFG) o).getMethod())
&& context.equals(((InducedCFG) o).context);
}
@Override
public SSAInstruction[] getInstructions() {
return instructions;
}
/** Compute outgoing edges in the control flow graph. */
private void computeEdges() {
for (BasicBlock b : this) {
if (b.equals(exit())) continue;
b.computeOutgoingEdges();
}
clearPis(getInstructions());
}
private static void clearPis(SSAInstruction[] instructions) {
for (int i = 0; i < instructions.length; i++) {
if (instructions[i] instanceof SSAPiInstruction) {
instructions[i] = null;
}
}
}
/** Create basic blocks for an empty method */
private void makeEmptyBlocks() {
BasicBlock b = new BasicBlock(-1);
addNode(b);
}
protected BranchVisitor makeBranchVisitor(boolean[] r) {
return new BranchVisitor(r);
}
protected PEIVisitor makePEIVisitor(boolean[] r) {
return new PEIVisitor(r);
}
/** Walk through the instructions and compute basic block boundaries. */
private void makeBasicBlocks() {
SSAInstruction[] instructions = getInstructions();
final boolean[] r = new boolean[instructions.length];
// Compute r so r[i] == true iff instruction i begins a basic block.
// While doing so count the number of blocks.
r[0] = true;
BranchVisitor branchVisitor = makeBranchVisitor(r);
PEIVisitor peiVisitor = makePEIVisitor(r);
for (int i = 0; i < instructions.length; i++) {
if (instructions[i] != null) {
branchVisitor.setIndex(i);
instructions[i].visit(branchVisitor);
// TODO: deal with exception handlers
peiVisitor.setIndex(i);
instructions[i].visit(peiVisitor);
}
}
assert (instructions.length <= r.length);
if (DEBUG) {
System.err.println(
"Searching " + instructions.length + " instructions for basic clocks and Phi/Pi");
}
BasicBlock b = null;
for (int i = 0; i < r.length; i++) {
if (r[i]) {
b = new BasicBlock(i);
addNode(b);
int j = i;
while (instructions[j] instanceof SSAPhiInstruction) {
b.addPhi((SSAPhiInstruction) instructions[j]);
j++;
if (j >= instructions.length) {
break;
}
}
if (DEBUG) {
System.err.println(
("Add basic block "
+ b.getNumber()
+ " (starting from "
+ b.getFirstInstructionIndex()
+ ") with instruction "
+ instructions[i]
+ " at aIndex "
+ i));
}
}
if (instructions[i] instanceof SSAPiInstruction) {
// add it to the current basic block
b.addPi((SSAPiInstruction) instructions[i]);
}
i2block[i] = b;
}
// allocate the exit block
BasicBlock exit = new BasicBlock(-1);
if (DEBUG) {
System.err.println(("Add exit block " + exit));
}
addNode(exit);
clearPhis(instructions);
}
/** set to null any slots in the array with phi instructions */
private static void clearPhis(SSAInstruction[] instructions) {
for (int i = 0; i < instructions.length; i++) {
if (instructions[i] instanceof SSAPhiInstruction) {
instructions[i] = null;
}
}
}
/** This visitor identifies basic block boundaries induced by branch instructions. */
public class BranchVisitor extends SSAInstruction.Visitor {
private final boolean[] r;
protected BranchVisitor(boolean[] r) {
this.r = r;
}
int index = 0;
void setIndex(int i) {
index = i;
}
@Override
public void visitGoto(SSAGotoInstruction instruction) {
if (DEBUG) {
System.err.println(
"Breaking Basic block after instruction " + instruction + " index " + index);
}
breakBasicBlock(index); // Breaks __after__ the GoTo-Instruction
final int jumpTarget = getIndexFromIIndex(instruction.getTarget());
assert (instructions[jumpTarget] != null) : "GoTo cant go to null";
if (DEBUG) {
System.err.println(
"Breaking Basic block before instruction "
+ instructions[jumpTarget]
+ " index "
+ jumpTarget
+ " -1");
}
breakBasicBlock(jumpTarget - 1); // Breaks __before__ the target
}
@Override
public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {
breakBasicBlock(index);
}
@Override
public void visitSwitch(SSASwitchInstruction instruction) {
breakBasicBlock(index);
int[] targets = instruction.getCasesAndLabels();
for (int i = 1; i < targets.length; i += 2) {
r[targets[i]] = true;
}
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
// we can have more than one phi instruction in a row. break the basic block
// only before the first one.
if (!(instructions[index - 1] instanceof SSAPhiInstruction)) {
breakBasicBlock(index - 1);
}
}
@Override
public void visitReturn(SSAReturnInstruction instruction) {
breakBasicBlock(index);
}
@Override
public void visitThrow(SSAThrowInstruction instruction) {
breakBasicBlock(index);
}
/**
* introduce a basic block boundary immediately after instruction number 'index' if it is not
* followed by pi instructions, or after the pi instructions otherwise
*/
protected void breakBasicBlock(int index) {
int j = index + 1;
while (j < instructions.length && instructions[j] instanceof SSAPiInstruction) {
j++;
}
if (j < instructions.length && !r[j]) {
r[j] = true;
}
}
}
// TODO: extend the following to deal with catch blocks. Right now
// it simply breaks basic blocks at PEIs.
public class PEIVisitor extends SSAInstruction.Visitor {
private final boolean[] r;
protected PEIVisitor(boolean[] r) {
this.r = r;
}
int index = 0;
void setIndex(int i) {
index = i;
}
protected void breakBasicBlock() {
int j = index + 1;
while (j < instructions.length && instructions[j] instanceof SSAPiInstruction) {
j++;
}
if (j < instructions.length && !r[j]) {
r[j] = true;
}
}
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitGet(SSAGetInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitMonitor(SSAMonitorInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitNew(SSANewInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitPut(SSAPutInstruction instruction) {
breakBasicBlock();
}
@Override
public void visitThrow(com.ibm.wala.ssa.SSAThrowInstruction instruction) {
breakBasicBlock();
}
}
@Override
public BasicBlock getBlockForInstruction(int index) {
if (i2block[index] == null) {
Assertions.productionAssertion(false, "unexpected null for " + index);
}
return i2block[index];
}
// TODO: share some common parts of this implementation with the ShrikeCFG
// implementation! right now it's clone-and-owned :(
public class BasicBlock extends NodeWithNumber implements IBasicBlock<SSAInstruction> {
private Collection<SSAPhiInstruction> phis;
public Collection<SSAPhiInstruction> getPhis() {
return phis == null
? Collections.<SSAPhiInstruction>emptyList()
: Collections.unmodifiableCollection(phis);
}
public void addPhi(SSAPhiInstruction phiInstruction) {
if (phis == null) {
phis = new ArrayList<>(1);
}
phis.add(phiInstruction);
}
private ArrayList<SSAPiInstruction> pis;
public Collection<SSAPiInstruction> getPis() {
return pis == null
? Collections.<SSAPiInstruction>emptyList()
: Collections.unmodifiableCollection(pis);
}
public void addPi(SSAPiInstruction piInstruction) {
if (pis == null) {
pis = new ArrayList<>(1);
}
pis.add(piInstruction);
}
@Override
public boolean equals(Object arg0) {
if (arg0 != null && getClass().equals(arg0.getClass())) {
BasicBlock other = (BasicBlock) arg0;
return start == other.start && getMethod().equals(other.getMethod());
} else {
return false;
}
}
private final int start;
BasicBlock(int start) {
this.start = start;
}
/**
* Add any exceptional edges generated by the last instruction in a basic block.
*
* @param last the last instruction in a basic block.
*/
private void addExceptionalEdges(SSAInstruction last) {
if (last == null) {
// XXX: Bug here?
// throw new IllegalStateException("Missing last SSA-Instruction in basic block (null).");
// // XXX: When does this happen?
System.err.println("Missing last SSA-Instruction in basic block (null).");
return;
}
if (last.isPEI()) {
// we don't currently model catch blocks here ... instead just link
// to the exit block
addExceptionalEdgeTo(exit());
}
}
private void addNormalEdgeTo(BasicBlock b) {
addNormalEdge(this, b);
}
private void addExceptionalEdgeTo(BasicBlock b) {
addExceptionalEdge(this, b);
}
private void computeOutgoingEdges() {
if (DEBUG) {
System.err.println("Block " + this + ": computeOutgoingEdges()");
}
SSAInstruction last = getInstructions()[getLastInstructionIndex()];
addExceptionalEdges(last);
if (last instanceof SSAGotoInstruction) {
int tgt = ((SSAGotoInstruction) last).getTarget();
if (tgt != -1) {
int tgtNd = getIndexFromIIndex(tgt); // index in instructions-array
BasicBlock target = null;
for (BasicBlock candid : InducedCFG.this) {
if (candid.getFirstInstructionIndex() == tgtNd) {
target = candid;
break;
}
}
if (target == null) {
System.err.println(
"Error retreiving the Node with IIndex " + tgt + " (in array at " + tgtNd + ')');
System.err.println(
"The associated Instruction "
+ instructions[tgtNd]
+ " does not start a basic block");
assert false; // It will fail anyway
}
if (DEBUG) {
System.err.println(
"GOTO: Add additional CF " + last.iIndex() + " to " + tgt + " is node " + target);
}
addNormalEdgeTo(target);
}
}
int normalSuccNodeNumber = getGraphNodeId() + 1;
if (last.isFallThrough()) {
if (DEBUG) {
System.err.println(("Add fallthru to " + getNode(getGraphNodeId() + 1)));
}
addNormalEdgeTo(getNode(normalSuccNodeNumber));
}
if (last instanceof SSAGotoInstruction) {
addNormalEdgeTo(getBlockForInstruction(((SSAGotoInstruction) last).getTarget()));
} else if (last instanceof SSAConditionalBranchInstruction) {
addNormalEdgeTo(
getBlockForInstruction(((SSAConditionalBranchInstruction) last).getTarget()));
} else if (last instanceof SSASwitchInstruction) {
int[] targets = ((SSASwitchInstruction) last).getCasesAndLabels();
for (int i = 1; i < targets.length; i += 2) {
addNormalEdgeTo(getBlockForInstruction(targets[i]));
}
}
if (pis != null) {
updatePiInstrs(normalSuccNodeNumber);
}
if (last instanceof SSAReturnInstruction) {
// link each return instrution to the exit block.
BasicBlock exit = exit();
addNormalEdgeTo(exit);
}
}
/**
* correct pi instructions with appropriate basic block numbers. we assume for now that pi
* instructions are always associated with the normal "fall-thru" exit edge.
*/
private void updatePiInstrs(int normalSuccNodeNumber) {
for (int i = 0; i < pis.size(); i++) {
SSAPiInstruction pi = pis.get(i);
SSAInstructionFactory insts =
getMethod().getDeclaringClass().getClassLoader().getInstructionFactory();
pis.set(
i,
insts.PiInstruction(
SSAInstruction.NO_INDEX,
pi.getDef(),
pi.getVal(),
getGraphNodeId(),
normalSuccNodeNumber,
pi.getCause()));
}
}
@Override
public int getFirstInstructionIndex() {
return start;
}
@Override
public int getLastInstructionIndex() {
int exitNumber = InducedCFG.this.getNumber(exit());
if (getGraphNodeId() == exitNumber) {
// this is the exit block
return -2;
}
if (getGraphNodeId() == (exitNumber - 1)) {
// this is the last non-exit block
return getInstructions().length - 1;
} else {
BasicBlock next = getNode(getGraphNodeId() + 1);
return next.getFirstInstructionIndex() - 1;
}
}
@Override
public boolean isCatchBlock() {
// TODO: support induced CFG with catch blocks.
return false;
}
@Override
public int hashCode() {
return 1153 * getGraphNodeId() + getMethod().hashCode();
}
/** @see java.lang.Object#toString() */
@Override
public String toString() {
return "BB[Induced]" + getNumber() + " - " + getMethod().getSignature();
}
@Override
public boolean isExitBlock() {
return getLastInstructionIndex() == -2;
}
@Override
public boolean isEntryBlock() {
return getNumber() == 0;
}
@Override
public IMethod getMethod() {
return InducedCFG.this.getMethod();
}
public boolean endsInPEI() {
return getInstructions()[getLastInstructionIndex()].isPEI();
}
public boolean endsInReturn() {
return getInstructions()[getLastInstructionIndex()] instanceof SSAReturnInstruction;
}
@Override
public int getNumber() {
return InducedCFG.this.getNumber(this);
}
@Override
public Iterator<SSAInstruction> iterator() {
return new ArrayIterator<>(
getInstructions(), getFirstInstructionIndex(), getLastInstructionIndex());
}
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (BasicBlock bb : this) {
s.append("BB").append(getNumber(bb)).append('\n');
for (int j = bb.getFirstInstructionIndex(); j <= bb.getLastInstructionIndex(); j++) {
s.append(" ").append(j).append(" ").append(getInstructions()[j]).append('\n');
}
Iterator<BasicBlock> succNodes = getSuccNodes(bb);
while (succNodes.hasNext()) {
s.append(" -> BB").append(getNumber(succNodes.next())).append('\n');
}
}
return s.toString();
}
/**
* Since this CFG is synthetic, for now we assume the instruction index is the same as the program
* counter
*
* @see com.ibm.wala.cfg.ControlFlowGraph#getProgramCounter(int)
*/
@Override
public int getProgramCounter(int index) {
if (getInstructions().length <= index) {
throw new IllegalArgumentException("invalid index " + index + ' ' + getInstructions().length);
}
if (getInstructions()[index] instanceof SSAInvokeInstruction) {
return ((SSAInvokeInstruction) getInstructions()[index]).getCallSite().getProgramCounter();
} else {
return index;
}
}
/**
* Get the position of a instruction with a given iindex in the internal list.
*
* @param iindex The iindex used when generating the SSAInstruction
* @return index into the internal list of instructions
* @throws IllegalStateException if no instruction exists with iindex or it's not in the internal
* array (Phi)
*/
public int getIndexFromIIndex(int iindex) {
if (iindex <= 0) {
throw new IllegalArgumentException(
"The iindex may not be negative (is "
+ iindex
+ ". Method: "
+ getMethod()
+ ", Contenxt: "
+ this.context);
}
final SSAInstruction[] instructions = getInstructions();
if (instructions == null) {
throw new IllegalStateException(
"This CFG contains no Instructions? " + getMethod() + ", Contenxt: " + this.context);
}
for (int i = 0; i < instructions.length; ++i) {
if (instructions[i] == null) {
// There are holes in the instructions array ?!
// Perhaps from Phi-functions?
if (DEBUG) {
System.err.println("The " + i + "th instrction is null! Mathod: " + getMethod());
if (i > 0) {
System.err.println(" Instuction before is: " + instructions[i - 1]);
}
if (i < instructions.length - 1) {
System.err.println(" Instuction after is: " + instructions[i + 1]);
}
}
continue;
}
if (instructions[i].iIndex() == iindex) {
return i;
}
}
throw new IllegalStateException(
"The searched iindex ("
+ iindex
+ ") does not exist! In "
+ getMethod()
+ ", Contenxt: "
+ this.context);
}
public Collection<SSAPhiInstruction> getAllPhiInstructions() {
Collection<SSAPhiInstruction> result = HashSetFactory.make();
for (BasicBlock b : this) {
result.addAll(b.getPhis());
}
return result;
}
}
| 21,950
| 29.028728
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/MinimalCFG.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.cfg;
import com.ibm.wala.util.graph.NumberedGraph;
import java.util.Collection;
import java.util.List;
public interface MinimalCFG<T> extends NumberedGraph<T> {
/** Return the entry basic block in the CFG */
T entry();
/** @return the synthetic exit block for the cfg */
T exit();
/**
* The order of blocks returned must indicate the exception-handling scope. So the first block is
* the first candidate catch block, and so on. With this invariant one can compute the exceptional
* control flow for a given exception type.
*
* @return the basic blocks which may be reached from b via exceptional control flow
*/
List<T> getExceptionalSuccessors(T b);
/**
* The order of blocks returned should be arbitrary but deterministic.
*
* @return the basic blocks which may be reached from b via normal control flow
*/
Collection<T> getNormalSuccessors(T b);
/**
* The order of blocks returned should be arbitrary but deterministic.
*
* @return the basic blocks from which b may be reached via exceptional control flow
*/
Collection<T> getExceptionalPredecessors(T b);
/**
* The order of blocks returned should be arbitrary but deterministic.
*
* @return the basic blocks from which b may be reached via normal control flow
*/
Collection<T> getNormalPredecessors(T b);
}
| 1,736
| 30.581818
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/ShrikeCFG.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.cfg;
import com.ibm.wala.classLoader.BytecodeLanguage;
import com.ibm.wala.classLoader.IBytecodeMethod;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.shrike.ShrikeUtil;
import com.ibm.wala.core.util.warnings.Warning;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.ArrayIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.impl.NodeWithNumber;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/** A graph of basic blocks. */
public class ShrikeCFG extends AbstractCFG<IInstruction, ShrikeCFG.BasicBlock>
implements BytecodeCFG {
private static final boolean DEBUG = false;
private int[] instruction2Block;
private final IBytecodeMethod<IInstruction> method;
/** Cache this here for efficiency */
private final int hashBase;
/** Set of Shrike {@link ExceptionHandler} objects that cover this method. */
private final Set<ExceptionHandler> exceptionHandlers = HashSetFactory.make(10);
public static ShrikeCFG make(IBytecodeMethod<IInstruction> m) {
return new ShrikeCFG(m);
}
private ShrikeCFG(IBytecodeMethod<IInstruction> method) throws IllegalArgumentException {
super(method);
if (method == null) {
throw new IllegalArgumentException("method cannot be null");
}
this.method = method;
this.hashBase = method.hashCode() * 9967;
makeBasicBlocks();
init();
computeI2BMapping();
computeEdges();
if (DEBUG) {
System.err.println(this);
}
}
@Override
public IBytecodeMethod<IInstruction> getMethod() {
return method;
}
@Override
public int hashCode() {
return 9511 * getMethod().hashCode();
}
@Override
public boolean equals(Object o) {
return (o instanceof ShrikeCFG) && getMethod().equals(((ShrikeCFG) o).getMethod());
}
@Override
public IInstruction[] getInstructions() {
try {
return method.getInstructions();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return null;
}
}
/**
* Compute a mapping from instruction to basic block. Also, compute the blocks that end with a
* 'normal' return.
*/
private void computeI2BMapping() {
instruction2Block = new int[getInstructions().length];
for (BasicBlock b : this) {
for (int j = b.getFirstInstructionIndex(); j <= b.getLastInstructionIndex(); j++) {
instruction2Block[j] = getNumber(b);
}
}
}
/** Compute outgoing edges in the control flow graph. */
private void computeEdges() {
for (BasicBlock b : this) {
if (b.equals(exit())) {
continue;
} else if (b.equals(entry())) {
BasicBlock bb0 = getBlockForInstruction(0);
assert bb0 != null;
addNormalEdge(b, bb0);
} else {
b.computeOutgoingEdges();
}
}
}
private void makeBasicBlocks() {
ExceptionHandler[][] handlers;
try {
handlers = method.getHandlers();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
handlers = null;
}
// Compute r so r[i] == true iff instruction i begins a basic block.
boolean[] r = new boolean[getInstructions().length];
boolean[] catchers = new boolean[getInstructions().length];
r[0] = true;
IInstruction[] instructions = getInstructions();
for (int i = 0; i < instructions.length; i++) {
int[] targets = instructions[i].getBranchTargets();
// if there are any targets, then break the basic block here.
// also break the basic block after a return
if (targets.length > 0 || !instructions[i].isFallThrough()) {
if (i + 1 < instructions.length && !r[i + 1]) {
r[i + 1] = true;
}
}
for (int target : targets) {
if (!r[target]) {
r[target] = true;
}
}
if (instructions[i].isPEI()) {
ExceptionHandler[] hs = handlers[i];
// break the basic block here.
if (i + 1 < instructions.length && !r[i + 1]) {
r[i + 1] = true;
}
if (hs != null) {
for (ExceptionHandler h : hs) {
exceptionHandlers.add(h);
if (!r[h.getHandler()]) {
// we have not discovered the catch block yet.
// form a new basic block
r[h.getHandler()] = true;
}
catchers[h.getHandler()] = true;
}
}
}
}
BasicBlock entry = new BasicBlock(-1);
addNode(entry);
int j = 1;
for (int i = 0; i < r.length; i++) {
if (r[i]) {
BasicBlock b = new BasicBlock(i);
addNode(b);
if (catchers[i]) {
setCatchBlock(j);
}
j++;
}
}
BasicBlock exit = new BasicBlock(-1);
addNode(exit);
}
/**
* Return an instruction's basic block in the CFG given the index of the instruction in the CFG's
* instruction array.
*/
@Override
public BasicBlock getBlockForInstruction(int index) {
return getNode(instruction2Block[index]);
}
public final class BasicBlock extends NodeWithNumber implements IBasicBlock<IInstruction> {
/** The number of the ShrikeBT instruction that begins this block. */
private final int startIndex;
public BasicBlock(int startIndex) {
this.startIndex = startIndex;
}
@Override
public boolean isCatchBlock() {
return ShrikeCFG.this.isCatchBlock(getNumber());
}
private void computeOutgoingEdges() {
if (DEBUG) {
System.err.println("Block " + this + ": computeOutgoingEdges()");
}
IInstruction last = getInstructions()[getLastInstructionIndex()];
int[] targets = last.getBranchTargets();
for (int target : targets) {
BasicBlock b = getBlockForInstruction(target);
addNormalEdgeTo(b);
}
addExceptionalEdges(last);
if (last.isFallThrough()) {
BasicBlock next = getNode(getNumber() + 1);
addNormalEdgeTo(next);
}
if (last instanceof ReturnInstruction) {
// link each return instruction to the exit block.
BasicBlock exit = exit();
addNormalEdgeTo(exit);
}
}
/**
* Add any exceptional edges generated by the last instruction in a basic block.
*
* @param last the last instruction in a basic block.
*/
private void addExceptionalEdges(IInstruction last) {
IClassHierarchy cha = getMethod().getClassHierarchy();
if (last.isPEI()) {
Collection<TypeReference> exceptionTypes = null;
boolean goToAllHandlers = false;
ExceptionHandler[] hs = getExceptionHandlers();
if (last instanceof ThrowInstruction) {
// this class does not have the type information needed
// to determine what the athrow throws. So, add an
// edge to all reachable handlers. Better information can
// be obtained later with SSA type propagation.
// TODO: consider pruning to only the exception types that
// this method either catches or allocates, since these are
// the only types that can flow to an athrow.
goToAllHandlers = true;
} else {
if (hs != null && hs.length > 0) {
IClassLoader loader = getMethod().getDeclaringClass().getClassLoader();
BytecodeLanguage l = (BytecodeLanguage) loader.getLanguage();
exceptionTypes = l.getImplicitExceptionTypes(last);
if (last instanceof IInvokeInstruction) {
IInvokeInstruction call = (IInvokeInstruction) last;
exceptionTypes = HashSetFactory.make(exceptionTypes);
MethodReference target =
MethodReference.findOrCreate(
l,
loader.getReference(),
call.getClassType(),
call.getMethodName(),
call.getMethodSignature());
try {
exceptionTypes.addAll(l.inferInvokeExceptions(target, cha));
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
IMethod mTarget = cha.resolveMethod(target);
if (mTarget == null) {
goToAllHandlers = true;
}
}
}
}
if (hs != null && hs.length > 0) {
// found a handler for this PEI
// create a mutable copy
if (!goToAllHandlers) {
exceptionTypes = HashSetFactory.make(exceptionTypes);
}
// this var gets set to false if goToAllHandlers is true but some enclosing exception
// handler catches all
// exceptions. in such a case, we need not add an exceptional edge to the method exit
boolean needEdgeToExitForAllHandlers = true;
for (ExceptionHandler element : hs) {
if (DEBUG) {
System.err.println(" handler " + element);
}
BasicBlock b = getBlockForInstruction(element.getHandler());
if (DEBUG) {
System.err.println(" target " + b);
}
if (goToAllHandlers) {
// add an edge to the catch block.
if (DEBUG) {
System.err.println(" gotoAllHandlers " + b);
}
addExceptionalEdgeTo(b);
// if the handler catches all exceptions, we don't need to add an edge to the exit or
// any other handlers
if (element.getCatchClass() == null) {
needEdgeToExitForAllHandlers = false;
break;
}
} else {
TypeReference caughtException = null;
if (element.getCatchClass() != null) {
ClassLoaderReference loader =
element.getCatchClassLoader() == null
? ShrikeCFG.this
.getMethod()
.getDeclaringClass()
.getReference()
.getClassLoader()
: (ClassLoaderReference) element.getCatchClassLoader();
caughtException = ShrikeUtil.makeTypeReference(loader, element.getCatchClass());
if (DEBUG) {
System.err.println(" caughtException " + caughtException);
}
IClass caughtClass = cha.lookupClass(caughtException);
if (DEBUG) {
System.err.println(" caughtException class " + caughtClass);
}
if (caughtClass == null) {
// conservatively add the edge, and raise a warning
addExceptionalEdgeTo(b);
Warnings.add(FailedExceptionResolutionWarning.create(caughtException));
// null out caughtException, to avoid attempting to process it
caughtException = null;
}
} else {
if (DEBUG) {
System.err.println(" catchClass() == null");
}
// hs[j].getCatchClass() == null.
// this means that the handler catches all exceptions.
// add the edge and null out all types
if (!exceptionTypes.isEmpty()) {
addExceptionalEdgeTo(b);
exceptionTypes.clear();
assert caughtException == null;
}
}
if (caughtException != null) {
IClass caughtClass = cha.lookupClass(caughtException);
// the set "caught" should be the set of exceptions that MUST
// have been caught by the handlers in scope
ArrayList<TypeReference> caught = new ArrayList<>(exceptionTypes.size());
// check if we should add an edge to the catch block.
for (TypeReference t : exceptionTypes) {
if (t != null) {
IClass klass = cha.lookupClass(t);
if (klass == null) {
Warnings.add(FailedExceptionResolutionWarning.create(caughtException));
// conservatively add an edge
addExceptionalEdgeTo(b);
} else {
boolean subtype1 = cha.isSubclassOf(klass, caughtClass);
if (subtype1 || cha.isSubclassOf(caughtClass, klass)) {
// add the edge and null out the type from the array
addExceptionalEdgeTo(b);
if (subtype1) {
caught.add(t);
}
}
}
}
}
exceptionTypes.removeAll(caught);
}
}
}
// if needed, add an edge to the exit block.
if ((exceptionTypes == null && needEdgeToExitForAllHandlers)
|| (exceptionTypes != null && !exceptionTypes.isEmpty())) {
BasicBlock exit = exit();
addExceptionalEdgeTo(exit);
}
} else {
// found no handler for this PEI ... link to the exit block.
BasicBlock exit = exit();
addExceptionalEdgeTo(exit);
}
}
}
private ExceptionHandler[] getExceptionHandlers() {
ExceptionHandler[][] handlers;
try {
handlers = method.getHandlers();
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
handlers = null;
}
ExceptionHandler[] hs = handlers[getLastInstructionIndex()];
return hs;
}
private void addNormalEdgeTo(BasicBlock b) {
addNormalEdge(this, b);
}
private void addExceptionalEdgeTo(BasicBlock b) {
addExceptionalEdge(this, b);
}
@Override
public int getLastInstructionIndex() {
if (this == entry() || this == exit()) {
// these are the special end blocks
return -2;
}
if (getNumber() == (getMaxNumber() - 1)) {
// this is the last non-exit block
return getInstructions().length - 1;
} else {
int i = 1;
BasicBlock next;
do {
next = getNode(getNumber() + i);
} while (next == null);
return next.getFirstInstructionIndex() - 1;
}
}
@Override
public int getFirstInstructionIndex() {
return startIndex;
}
@Override
public String toString() {
return "BB[Shrike]"
+ getNumber()
+ " - "
+ method.getDeclaringClass().getReference().getName()
+ '.'
+ method.getName();
}
@Override
public boolean isExitBlock() {
return this == ShrikeCFG.this.exit();
}
@Override
public boolean isEntryBlock() {
return this == ShrikeCFG.this.entry();
}
@Override
public IMethod getMethod() {
return ShrikeCFG.this.getMethod();
}
@Override
public int hashCode() {
return hashBase + getNumber();
}
@Override
public boolean equals(Object o) {
return (o instanceof BasicBlock)
&& ((BasicBlock) o).getMethod().equals(getMethod())
&& ((BasicBlock) o).getNumber() == getNumber();
}
@Override
public int getNumber() {
return getGraphNodeId();
}
@Override
public Iterator<IInstruction> iterator() {
return new ArrayIterator<>(
getInstructions(), getFirstInstructionIndex(), getLastInstructionIndex());
}
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (BasicBlock bb : this) {
s.append("BB").append(getNumber(bb)).append('\n');
for (int j = bb.getFirstInstructionIndex(); j <= bb.getLastInstructionIndex(); j++) {
s.append(" ").append(j).append(" ").append(getInstructions()[j]).append('\n');
}
Iterator<BasicBlock> succNodes = getSuccNodes(bb);
while (succNodes.hasNext()) {
s.append(" -> BB").append(getNumber(succNodes.next())).append('\n');
}
}
return s.toString();
}
@Override
public Set<ExceptionHandler> getExceptionHandlers() {
return exceptionHandlers;
}
/** @see com.ibm.wala.cfg.ControlFlowGraph#getProgramCounter(int) */
@Override
public int getProgramCounter(int index) {
try {
return method.getBytecodeIndex(index);
} catch (InvalidClassFileException e) {
e.printStackTrace();
Assertions.UNREACHABLE();
return -1;
}
}
/** A warning when we fail to resolve the type of an exception */
private static class FailedExceptionResolutionWarning extends Warning {
final TypeReference T;
FailedExceptionResolutionWarning(TypeReference T) {
super(Warning.MODERATE);
this.T = T;
}
@Override
public String getMsg() {
return getClass().toString() + " : " + T;
}
public static FailedExceptionResolutionWarning create(TypeReference T) {
return new FailedExceptionResolutionWarning(T);
}
}
}
| 18,405
| 31.926655
| 99
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/Util.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.cfg;
import com.ibm.wala.shrike.shrikeBT.ConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
/** Convenience methods for navigating a {@link ControlFlowGraph}. */
public class Util {
/** @return the last instruction in basic block b, as stored in the instruction array for cfg */
public static SSAInstruction getLastInstruction(
ControlFlowGraph<? extends SSAInstruction, ?> cfg, IBasicBlock<?> b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
if (cfg == null) {
throw new IllegalArgumentException("G is null");
}
return cfg.getInstructions()[b.getLastInstructionIndex()];
}
/** Does basic block b end with a conditional branch instruction? */
public static boolean endsWithConditionalBranch(
ControlFlowGraph<? extends SSAInstruction, ?> G, IBasicBlock<?> b) {
return getLastInstruction(G, b) instanceof SSAConditionalBranchInstruction;
}
/** Does basic block b end with a switch instruction? */
public static boolean endsWithSwitch(
ControlFlowGraph<? extends SSAInstruction, ?> G, IBasicBlock<?> b) {
return getLastInstruction(G, b) instanceof SSASwitchInstruction;
}
/**
* Given that b falls through to the next basic block, what basic block does it fall through to?
*/
public static <I, T extends IBasicBlock<I>> T getFallThruBlock(ControlFlowGraph<I, T> G, T b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
if (G == null) {
throw new IllegalArgumentException("G is null");
}
return G.getBlockForInstruction(b.getLastInstructionIndex() + 1);
}
/**
* Given that b ends with a conditional branch, return the basic block to which control transfers
* if the branch is not taken.
*/
public static <I extends SSAInstruction, T extends IBasicBlock<I>> T getNotTakenSuccessor(
ControlFlowGraph<I, T> G, T b) {
if (G == null) {
throw new IllegalArgumentException("G is null");
}
if (!endsWithConditionalBranch(G, b)) {
throw new IllegalArgumentException(b.toString() + " does not end with a conditional branch");
}
return getFallThruBlock(G, b);
}
/**
* Given that b ends with a conditional branch, return the basic block to which control transfers
* if the branch is taken.
*/
public static <I extends SSAInstruction, T extends IBasicBlock<I>> T getTakenSuccessor(
ControlFlowGraph<I, T> G, T b) {
if (G == null) {
throw new IllegalArgumentException("G is null");
}
if (!endsWithConditionalBranch(G, b)) {
throw new IllegalArgumentException(b.toString() + " does not end with a conditional branch");
}
T fs = getNotTakenSuccessor(G, b);
for (T s : Iterator2Iterable.make(G.getSuccNodes(b))) {
if (s != fs) return s;
}
// under pathological conditions, b may have exactly one successor (in other
// words, the
// branch is irrelevant
return fs;
}
/**
* When the tested value of the switch statement in b has value c, which basic block does control
* transfer to.
*/
public static <I extends SSAInstruction, T extends IBasicBlock<I>> T resolveSwitch(
ControlFlowGraph<I, T> G, T b, int c) {
assert endsWithSwitch(G, b);
SSASwitchInstruction s = (SSASwitchInstruction) getLastInstruction(G, b);
int[] casesAndLabels = s.getCasesAndLabels();
for (int i = 0; i < casesAndLabels.length; i += 2)
if (casesAndLabels[i] == c) return G.getBlockForInstruction(casesAndLabels[i + 1]);
return G.getBlockForInstruction(s.getDefault());
}
/**
* Is block s the default case for the switch instruction which is the last instruction of block
* b?
*/
public static <I extends SSAInstruction, T extends IBasicBlock<I>> boolean isSwitchDefault(
ControlFlowGraph<I, T> G, T b, T s) {
if (G == null) {
throw new IllegalArgumentException("G is null");
}
assert endsWithSwitch(G, b);
SSASwitchInstruction sw = (SSASwitchInstruction) getLastInstruction(G, b);
assert G.getBlockForInstruction(sw.getDefault()) != null;
return G.getBlockForInstruction(sw.getDefault()).equals(s);
}
/**
* When a switch statement at the end of block b transfers control to block s, which case was
* taken? TODO: Is this correct? Can't we have multiple cases that apply? Check on this.
*/
public static <I extends SSAInstruction, T extends IBasicBlock<I>> int getSwitchLabel(
ControlFlowGraph<I, T> G, T b, T s) {
assert endsWithSwitch(G, b);
SSASwitchInstruction sw = (SSASwitchInstruction) getLastInstruction(G, b);
int[] casesAndLabels = sw.getCasesAndLabels();
for (int i = 0; i < casesAndLabels.length; i += 2) {
if (G.getBlockForInstruction(casesAndLabels[i + 1]).equals(s)) {
return casesAndLabels[i];
}
}
Assertions.UNREACHABLE();
return -1;
}
/**
* To which {@link IBasicBlock} does control flow from basic block bb, which ends in a conditional
* branch, when the conditional branch operands evaluate to the constants c1 and c2, respectively.
*
* <p>Callers must resolve the constant values from the {@link SymbolTable} before calling this
* method. These integers are <b>not</b> value numbers;
*/
public static <I extends SSAInstruction, T extends IBasicBlock<I>> T resolveBranch(
ControlFlowGraph<I, T> G, T bb, int c1, int c2) {
SSAConditionalBranchInstruction c = (SSAConditionalBranchInstruction) getLastInstruction(G, bb);
final ConditionalBranchInstruction.Operator operator =
(ConditionalBranchInstruction.Operator) c.getOperator();
switch (operator) {
case EQ:
if (c1 == c2) return getTakenSuccessor(G, bb);
else return getNotTakenSuccessor(G, bb);
case NE:
if (c1 != c2) return getTakenSuccessor(G, bb);
else return getNotTakenSuccessor(G, bb);
case LT:
if (c1 < c2) return getTakenSuccessor(G, bb);
else return getNotTakenSuccessor(G, bb);
case GE:
if (c1 >= c2) return getTakenSuccessor(G, bb);
else return getNotTakenSuccessor(G, bb);
case GT:
if (c1 > c2) return getTakenSuccessor(G, bb);
else return getNotTakenSuccessor(G, bb);
case LE:
if (c1 <= c2) return getTakenSuccessor(G, bb);
else return getNotTakenSuccessor(G, bb);
default:
throw new UnsupportedOperationException(String.format("unexpected operator %s", operator));
}
}
/**
* Given that a is a predecessor of b in the cfg ..
*
* <p>When we enumerate the predecessors of b in order, which is the first index in this order in
* which a appears? Note that this order corresponds to the order of operands in a phi
* instruction.
*/
public static <I, T extends IBasicBlock<I>> int whichPred(ControlFlowGraph<I, T> cfg, T a, T b) {
if (cfg == null) {
throw new IllegalArgumentException("cfg is null");
}
if (a == null) {
throw new IllegalArgumentException("a is null");
}
if (b == null) {
throw new IllegalArgumentException("b is null");
}
int i = 0;
for (T p : Iterator2Iterable.make(cfg.getPredNodes(b))) {
if (p.equals(a)) {
return i;
}
i++;
}
Assertions.UNREACHABLE("Invalid: a must be a predecessor of b! " + a + ' ' + b);
return -1;
}
}
| 8,025
| 36.858491
| 100
|
java
|
WALA
|
WALA-master/core/src/main/java/com/ibm/wala/cfg/cdg/ControlDependenceGraph.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.cfg.cdg;
import com.ibm.wala.cfg.MinimalCFG;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.graph.AbstractNumberedGraph;
import com.ibm.wala.util.graph.NumberedEdgeManager;
import com.ibm.wala.util.graph.NumberedNodeManager;
import com.ibm.wala.util.graph.dominators.DominanceFrontiers;
import com.ibm.wala.util.graph.impl.GraphInverter;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/** Control Dependence Graph */
public class ControlDependenceGraph<T> extends AbstractNumberedGraph<T> {
/** Governing control flow-graph. The control dependence graph is computed from this cfg. */
private final MinimalCFG<T> cfg;
/**
* the EdgeManager for the CDG. It implements the edge part of the standard Graph abstraction,
* using the control-dependence edges of the cdg.
*/
private final NumberedEdgeManager<T> edgeManager;
/**
* If requested, this is a map from parentXchild Pairs representing edges in the CDG to the labels
* of the control flow edges that edge corresponds to. The labels are Boolean.True or
* Boolean.False for conditionals and an Integer for a switch label.
*/
private Map<Pair<T, T>, Set<? extends Object>> edgeLabels;
/**
* This is the heart of the CDG computation. Based on Cytron et al., this is the reverse dominance
* frontier based algorithm for computing control dependence edges.
*
* @return Map: node n -> {x : n is control-dependent on x}
*/
private Map<T, Set<T>> buildControlDependence(boolean wantEdgeLabels) {
Map<T, Set<T>> controlDependence = HashMapFactory.make(cfg.getNumberOfNodes());
DominanceFrontiers<T> RDF = new DominanceFrontiers<>(GraphInverter.invert(cfg), cfg.exit());
if (wantEdgeLabels) {
edgeLabels = HashMapFactory.make();
}
for (T name : cfg) {
HashSet<T> s = HashSetFactory.make(2);
controlDependence.put(name, s);
}
for (T y : cfg) {
for (T x : Iterator2Iterable.make(RDF.getDominanceFrontier(y))) {
controlDependence.get(x).add(y);
if (wantEdgeLabels) {
HashSet<Object> labels = HashSetFactory.make();
edgeLabels.put(Pair.make(x, y), labels);
for (T s : Iterator2Iterable.make(cfg.getSuccNodes(x))) {
if (RDF.isDominatedBy(s, y)) {
labels.add(makeEdgeLabel(x, y, s));
}
}
}
}
}
return controlDependence;
}
protected Object makeEdgeLabel(
@SuppressWarnings("unused") T from, @SuppressWarnings("unused") T to, T s) {
return s;
}
/**
* Given the control-dependence edges in a forward direction (i.e. edges from control parents to
* control children), this method creates an EdgeManager that provides the edge half of the Graph
* abstraction.
*/
private NumberedEdgeManager<T> constructGraphEdges(final Map<T, Set<T>> forwardEdges) {
return new NumberedEdgeManager<>() {
final Map<T, Set<T>> backwardEdges = HashMapFactory.make(forwardEdges.size());
{
for (T name : cfg) {
Set<T> s = HashSetFactory.make();
backwardEdges.put(name, s);
}
for (Map.Entry<T, Set<T>> entry : forwardEdges.entrySet()) {
for (T t : entry.getValue()) {
Object n = t;
backwardEdges.get(n).add(entry.getKey());
}
}
}
@Override
public Iterator<T> getPredNodes(T N) {
if (backwardEdges.containsKey(N)) return backwardEdges.get(N).iterator();
else return EmptyIterator.instance();
}
@Override
public IntSet getPredNodeNumbers(T node) {
MutableIntSet x = IntSetUtil.make();
if (backwardEdges.containsKey(node)) {
for (T pred : backwardEdges.get(node)) {
x.add(cfg.getNumber(pred));
}
}
return x;
}
@Override
public int getPredNodeCount(T N) {
if (backwardEdges.containsKey(N)) return backwardEdges.get(N).size();
else return 0;
}
@Override
public Iterator<T> getSuccNodes(T N) {
if (forwardEdges.containsKey(N)) return forwardEdges.get(N).iterator();
else return EmptyIterator.instance();
}
@Override
public IntSet getSuccNodeNumbers(T node) {
MutableIntSet x = IntSetUtil.make();
if (forwardEdges.containsKey(node)) {
for (T succ : forwardEdges.get(node)) {
x.add(cfg.getNumber(succ));
}
}
return x;
}
@Override
public int getSuccNodeCount(T N) {
if (forwardEdges.containsKey(N)) return forwardEdges.get(N).size();
else return 0;
}
@Override
public boolean hasEdge(T src, T dst) {
return forwardEdges.containsKey(src) && forwardEdges.get(src).contains(dst);
}
@Override
public void addEdge(T src, T dst) {
throw new UnsupportedOperationException();
}
@Override
public void removeEdge(T src, T dst) {
throw new UnsupportedOperationException();
}
@Override
public void removeAllIncidentEdges(T node) {
throw new UnsupportedOperationException();
}
@Override
public void removeIncomingEdges(T node) {
throw new UnsupportedOperationException();
}
@Override
public void removeOutgoingEdges(T node) {
throw new UnsupportedOperationException();
}
};
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (T n : this) {
sb.append(n.toString()).append('\n');
for (T s : Iterator2Iterable.make(getSuccNodes(n))) {
sb.append(" --> ").append(s);
if (edgeLabels != null)
for (Object name : edgeLabels.get(Pair.make(n, s)))
sb.append("\n label: ").append(name);
sb.append('\n');
}
}
return sb.toString();
}
/**
* @param cfg governing control flow graph
* @param wantEdgeLabels whether to compute edge labels for CDG edges
*/
public ControlDependenceGraph(MinimalCFG<T> cfg, boolean wantEdgeLabels) {
if (cfg == null) {
throw new IllegalArgumentException("null cfg");
}
this.cfg = cfg;
this.edgeManager = constructGraphEdges(buildControlDependence(wantEdgeLabels));
}
/** @param cfg governing control flow graph */
public ControlDependenceGraph(MinimalCFG<T> cfg) {
this(cfg, false);
}
public MinimalCFG<T> getControlFlowGraph() {
return cfg;
}
/**
* Return the set of edge labels for the control flow edges that cause the given edge in the CDG.
* Requires that the CDG be constructed with wantEdgeLabels being true.
*/
public Set<? extends Object> getEdgeLabels(T from, T to) {
return edgeLabels.get(Pair.make(from, to));
}
@Override
public NumberedNodeManager<T> getNodeManager() {
return cfg;
}
@Override
public NumberedEdgeManager<T> getEdgeManager() {
return edgeManager;
}
public boolean controlEquivalent(T bb1, T bb2) {
if (getPredNodeCount(bb1) != getPredNodeCount(bb2)) {
return false;
}
for (T pb : Iterator2Iterable.make(getPredNodes(bb1))) {
if (!hasEdge(pb, bb2)) {
return false;
}
}
return true;
}
}
| 8,063
| 29.545455
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.