proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
soot-oss_soot
soot/src/main/java/soot/jimple/spark/pag/FieldRefNode.java
FieldRefNode
getReplacement
class FieldRefNode extends ValNode { /** Returns the base of this field reference. */ public VarNode getBase() { return base; } public Node getReplacement() {<FILL_FUNCTION_BODY>} /** Returns the field of this field reference. */ public SparkField getField() { return field; } public String toString() { return "FieldRefNode " + getNumber() + " " + base + "." + field; } /* End of public methods. */ FieldRefNode(PAG pag, VarNode base, SparkField field) { super(pag, null); if (field == null) { throw new RuntimeException("null field"); } this.base = base; this.field = field; base.addField(this, field); pag.getFieldRefNodeNumberer().add(this); } /* End of package methods. */ protected VarNode base; protected SparkField field; }
if (replacement == this) { if (base.replacement == base) { return this; } Node baseRep = base.getReplacement(); FieldRefNode newRep = pag.makeFieldRefNode((VarNode) baseRep, field); newRep.mergeWith(this); return replacement = newRep.getReplacement(); } else { return replacement = replacement.getReplacement(); }
261
109
370
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/pag/LocalVarNode.java
LocalVarNode
toString
class LocalVarNode extends VarNode { public ContextVarNode context(Object context) { return cvns == null ? null : cvns.get(context); } public SootMethod getMethod() { return method; } public String toString() {<FILL_FUNCTION_BODY>} /* End of public methods. */ LocalVarNode(PAG pag, Object variable, Type t, SootMethod m) { super(pag, variable, t); this.method = m; // if( m == null ) throw new RuntimeException( "method shouldn't be null" ); } /** Registers a cvn as having this node as its base. */ void addContext(ContextVarNode cvn, Object context) { if (cvns == null) { cvns = new HashMap<Object, ContextVarNode>(); } cvns.put(context, cvn); } /* End of package methods. */ protected Map<Object, ContextVarNode> cvns; protected SootMethod method; }
return "LocalVarNode " + getNumber() + " " + variable + " " + method;
278
26
304
<methods>public int compareTo(java.lang.Object) ,public soot.Context context() ,public soot.jimple.spark.pag.FieldRefNode dot(soot.jimple.spark.pag.SparkField) ,public Collection<soot.jimple.spark.pag.FieldRefNode> getAllFieldRefs() ,public java.lang.Object getVariable() ,public boolean isInterProcSource() ,public boolean isInterProcTarget() ,public boolean isThisPtr() ,public void setFinishingNumber(int) ,public void setInterProcSource() ,public void setInterProcTarget() <variables>protected Map<soot.jimple.spark.pag.SparkField,soot.jimple.spark.pag.FieldRefNode> fields,protected int finishingNumber,protected boolean interProcSource,protected boolean interProcTarget,private static final org.slf4j.Logger logger,protected int numDerefs,protected java.lang.Object variable
soot-oss_soot
soot/src/main/java/soot/jimple/spark/pag/Node.java
Node
mergeWith
class Node implements ReferenceVariable, Numberable { public final int hashCode() { return number; } public final boolean equals(Object other) { return this == other; } /** Returns the declared type of this node, null for unknown. */ public Type getType() { return type; } /** Sets the declared type of this node, null for unknown. */ public void setType(Type type) { if (TypeManager.isUnresolved(type) && !Options.v().ignore_resolution_errors()) { throw new RuntimeException("Unresolved type " + type); } this.type = type; } /** * If this node has been merged with another, returns the new node to be used as the representative of this node; returns * this if the node has not been merged. */ public Node getReplacement() { if (replacement != replacement.replacement) { replacement = replacement.getReplacement(); } return replacement; } /** Merge with the node other. */ public void mergeWith(Node other) {<FILL_FUNCTION_BODY>} /** Returns the points-to set for this node. */ public PointsToSetInternal getP2Set() { if (p2set != null) { if (replacement != this) { throw new RuntimeException("Node " + this + " has replacement " + replacement + " but has p2set"); } return p2set; } Node rep = getReplacement(); if (rep == this) { return EmptyPointsToSet.v(); } return rep.getP2Set(); } /** Returns the points-to set for this node, makes it if necessary. */ public PointsToSetInternal makeP2Set() { if (p2set != null) { if (replacement != this) { throw new RuntimeException("Node " + this + " has replacement " + replacement + " but has p2set"); } return p2set; } Node rep = getReplacement(); if (rep == this) { p2set = pag.getSetFactory().newSet(type, pag); } return rep.makeP2Set(); } /** Returns the pointer assignment graph that this node is a part of. */ public PAG getPag() { return pag; } /** Delete current points-to set and make a new one */ public void discardP2Set() { p2set = null; } /** Use the specified points-to set to replace current one */ public void setP2Set(PointsToSetInternal ptsInternal) { p2set = ptsInternal; } /* End of public methods. */ /** Creates a new node of pointer assignment graph pag, with type type. */ Node(PAG pag, Type type) { if (TypeManager.isUnresolved(type) && !Options.v().ignore_resolution_errors()) { throw new RuntimeException("Unresolved type " + type); } this.type = type; this.pag = pag; replacement = this; } /* End of package methods. */ public final int getNumber() { return number; } public final void setNumber(int number) { this.number = number; } private int number = 0; protected Type type; protected Node replacement; protected PAG pag; protected PointsToSetInternal p2set; }
if (other.replacement != other) { throw new RuntimeException("Shouldn't happen"); } Node myRep = getReplacement(); if (other == myRep) { return; } other.replacement = myRep; if (other.p2set != p2set && other.p2set != null && !other.p2set.isEmpty()) { if (myRep.p2set == null || myRep.p2set.isEmpty()) { myRep.p2set = other.p2set; } else { myRep.p2set.mergeWith(other.p2set); } } other.p2set = null; pag.mergedWith(myRep, other); if ((other instanceof VarNode) && (myRep instanceof VarNode) && ((VarNode) other).isInterProcTarget()) { ((VarNode) myRep).setInterProcTarget(); }
900
242
1,142
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/pag/PAG2HTML.java
PAG2HTML
addSymLinks
class PAG2HTML { public PAG2HTML(PAG pag, String output_dir) { this.pag = pag; this.output_dir = output_dir; } public void dump() { for (Iterator vIt = pag.getVarNodeNumberer().iterator(); vIt.hasNext();) { final VarNode v = (VarNode) vIt.next(); mergedNodes.put(v.getReplacement(), v); if (v instanceof LocalVarNode) { SootMethod m = ((LocalVarNode) v).getMethod(); if (m != null) { methodToNodes.put(m, v); } } } try { JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(new File(output_dir, "pag.jar"))); for (Iterator vIt = mergedNodes.keySet().iterator(); vIt.hasNext();) { final VarNode v = (VarNode) vIt.next(); dumpVarNode(v, jarOut); } for (Iterator mIt = methodToNodes.keySet().iterator(); mIt.hasNext();) { final SootMethod m = (SootMethod) mIt.next(); dumpMethod(m, jarOut); } addSymLinks(pag.getVarNodeNumberer().iterator(), jarOut); jarOut.close(); } catch (IOException e) { throw new RuntimeException("Couldn't dump html" + e); } } /* End of public methods. */ /* End of package methods. */ protected PAG pag; protected String output_dir; protected MultiMap mergedNodes = new HashMultiMap(); protected MultiMap methodToNodes = new HashMultiMap(); protected void dumpVarNode(VarNode v, JarOutputStream jarOut) throws IOException { jarOut.putNextEntry(new ZipEntry("nodes/n" + v.getNumber() + ".html")); final PrintWriter out = new PrintWriter(jarOut); out.println("<html>"); out.println("Green node for:"); out.println(varNodeReps(v)); out.println("Declared type: " + v.getType()); out.println("<hr>Reaching blue nodes:"); out.println("<ul>"); v.getP2Set().forall(new P2SetVisitor() { public final void visit(Node n) { out.println("<li>" + htmlify(n.toString())); } }); out.println("</ul>"); out.println("<hr>Outgoing edges:"); Node[] succs = pag.simpleLookup(v); for (Node element : succs) { VarNode succ = (VarNode) element; out.println(varNodeReps(succ)); } out.println("<hr>Incoming edges: "); succs = pag.simpleInvLookup(v); for (Node element : succs) { VarNode succ = (VarNode) element; out.println(varNodeReps(succ)); } out.println("</html>"); out.flush(); } protected String varNodeReps(VarNode v) { StringBuffer ret = new StringBuffer(); ret.append("<ul>\n"); for (Iterator vvIt = mergedNodes.get(v).iterator(); vvIt.hasNext();) { final VarNode vv = (VarNode) vvIt.next(); ret.append(varNode("", vv)); } ret.append("</ul>\n"); return ret.toString(); } protected String varNode(String dirPrefix, VarNode vv) { StringBuffer ret = new StringBuffer(); ret.append("<li><a href=\"" + dirPrefix + "n" + vv.getNumber() + ".html\">"); if (vv.getVariable() != null) { ret.append("" + htmlify(vv.getVariable().toString())); } ret.append("GlobalVarNode"); ret.append("</a><br>"); ret.append("<li>Context: "); ret.append("" + (vv.context() == null ? "null" : htmlify(vv.context().toString()))); ret.append("</a><br>"); if (vv instanceof LocalVarNode) { LocalVarNode lvn = (LocalVarNode) vv; SootMethod m = lvn.getMethod(); if (m != null) { ret.append("<a href=\"../" + toFileName(m.toString()) + ".html\">"); ret.append(htmlify(m.toString()) + "</a><br>"); } } ret.append(htmlify(vv.getType().toString()) + "\n"); return ret.toString(); } protected static String htmlify(String s) { StringBuffer b = new StringBuffer(s); for (int i = 0; i < b.length(); i++) { if (b.charAt(i) == '<') { b.replace(i, i + 1, "&lt;"); } if (b.charAt(i) == '>') { b.replace(i, i + 1, "&gt;"); } } return b.toString(); } protected void dumpMethod(SootMethod m, JarOutputStream jarOut) throws IOException { jarOut.putNextEntry(new ZipEntry("" + toFileName(m.toString()) + ".html")); final PrintWriter out = new PrintWriter(jarOut); out.println("<html>"); out.println("This is method " + htmlify(m.toString()) + "<hr>"); for (Iterator it = methodToNodes.get(m).iterator(); it.hasNext();) { out.println(varNode("nodes/", (VarNode) it.next())); } out.println("</html>"); out.flush(); } protected void addSymLinks(Iterator nodes, JarOutputStream jarOut) throws IOException {<FILL_FUNCTION_BODY>} protected String toFileName(String s) { StringBuffer ret = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '<') { ret.append('{'); } else if (c == '>') { ret.append('}'); } else { ret.append(c); } } return ret.toString(); } }
jarOut.putNextEntry(new ZipEntry("symlinks.sh")); final PrintWriter out = new PrintWriter(jarOut); out.println("#!/bin/sh"); while (nodes.hasNext()) { VarNode v = (VarNode) nodes.next(); VarNode rep = (VarNode) v.getReplacement(); if (v != rep) { out.println("ln -s n" + rep.getNumber() + ".html n" + v.getNumber() + ".html"); } } out.flush();
1,685
141
1,826
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/pag/Parm.java
Parm
v
class Parm implements SparkField { private final int index; private final SootMethod method; private Parm(SootMethod m, int i) { index = i; method = m; } public static Parm v(SootMethod m, int index) {<FILL_FUNCTION_BODY>} public static final void delete() { G.v().Parm_pairToElement = null; } public String toString() { return "Parm " + index + " to " + method; } public final int getNumber() { return number; } public final void setNumber(int number) { this.number = number; } public int getIndex() { return index; } public Type getType() { if (index == PointsToAnalysis.RETURN_NODE) { return method.getReturnType(); } return method.getParameterType(index); } private int number = 0; }
Pair<SootMethod, Integer> p = new Pair<SootMethod, Integer>(m, new Integer(index)); Parm ret = (Parm) G.v().Parm_pairToElement.get(p); if (ret == null) { G.v().Parm_pairToElement.put(p, ret = new Parm(m, index)); } return ret;
265
103
368
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/pag/VarNode.java
VarNode
isThisPtr
class VarNode extends ValNode implements Comparable { private static final Logger logger = LoggerFactory.getLogger(VarNode.class); public Context context() { return null; } /** Returns all field ref nodes having this node as their base. */ public Collection<FieldRefNode> getAllFieldRefs() { if (fields == null) { return Collections.emptyList(); } return fields.values(); } /** * Returns the field ref node having this node as its base, and field as its field; null if nonexistent. */ public FieldRefNode dot(SparkField field) { return fields == null ? null : fields.get(field); } public int compareTo(Object o) { VarNode other = (VarNode) o; if (other.finishingNumber == finishingNumber && other != this) { logger.debug("" + "This is: " + this + " with id " + getNumber() + " and number " + finishingNumber); logger.debug("" + "Other is: " + other + " with id " + other.getNumber() + " and number " + other.finishingNumber); throw new RuntimeException("Comparison error"); } return other.finishingNumber - finishingNumber; } public void setFinishingNumber(int i) { finishingNumber = i; if (i > pag.maxFinishNumber) { pag.maxFinishNumber = i; } } /** Returns the underlying variable that this node represents. */ public Object getVariable() { return variable; } /** * Designates this node as the potential target of a interprocedural assignment edge which may be added during on-the-fly * call graph updating. */ public void setInterProcTarget() { interProcTarget = true; } /** * Returns true if this node is the potential target of a interprocedural assignment edge which may be added during * on-the-fly call graph updating. */ public boolean isInterProcTarget() { return interProcTarget; } /** * Designates this node as the potential source of a interprocedural assignment edge which may be added during on-the-fly * call graph updating. */ public void setInterProcSource() { interProcSource = true; } /** * Returns true if this node is the potential source of a interprocedural assignment edge which may be added during * on-the-fly call graph updating. */ public boolean isInterProcSource() { return interProcSource; } /** Returns true if this VarNode represents the THIS pointer */ public boolean isThisPtr() {<FILL_FUNCTION_BODY>} /* End of public methods. */ VarNode(PAG pag, Object variable, Type t) { super(pag, t); if (!(t instanceof RefLikeType) || t instanceof AnySubType) { throw new RuntimeException("Attempt to create VarNode of type " + t); } this.variable = variable; pag.getVarNodeNumberer().add(this); setFinishingNumber(++pag.maxFinishNumber); } /** Registers a frn as having this node as its base. */ void addField(FieldRefNode frn, SparkField field) { if (fields == null) { fields = new HashMap<SparkField, FieldRefNode>(); } fields.put(field, frn); } /* End of package methods. */ protected Object variable; protected Map<SparkField, FieldRefNode> fields; protected int finishingNumber = 0; protected boolean interProcTarget = false; protected boolean interProcSource = false; protected int numDerefs = 0; }
if (variable instanceof Pair) { Pair o = (Pair) variable; return o.isThisParameter(); } return false;
975
42
1,017
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/sets/DoublePointsToSet.java
DoublePointsToSet
mergeWith
class DoublePointsToSet extends PointsToSetInternal { public DoublePointsToSet(Type type, PAG pag) { super(type); newSet = G.v().newSetFactory.newSet(type, pag); oldSet = G.v().oldSetFactory.newSet(type, pag); this.pag = pag; } /** Returns true if this set contains no run-time objects. */ public boolean isEmpty() { return oldSet.isEmpty() && newSet.isEmpty(); } /** Returns true if this set shares some objects with other. */ public boolean hasNonEmptyIntersection(PointsToSet other) { return oldSet.hasNonEmptyIntersection(other) || newSet.hasNonEmptyIntersection(other); } /** Set of all possible run-time types of objects in the set. */ public Set<Type> possibleTypes() { Set<Type> ret = new HashSet<Type>(); ret.addAll(oldSet.possibleTypes()); ret.addAll(newSet.possibleTypes()); return ret; } /** * Adds contents of other into this set, returns true if this set changed. */ public boolean addAll(PointsToSetInternal other, PointsToSetInternal exclude) { if (exclude != null) { throw new RuntimeException("NYI"); } return newSet.addAll(other, oldSet); } /** Calls v's visit method on all nodes in this set. */ public boolean forall(P2SetVisitor v) { oldSet.forall(v); newSet.forall(v); return v.getReturnValue(); } /** Adds n to this set, returns true if n was not already in this set. */ public boolean add(Node n) { if (oldSet.contains(n)) { return false; } return newSet.add(n); } /** Returns set of nodes already present before last call to flushNew. */ public PointsToSetInternal getOldSet() { return oldSet; } /** Returns set of newly-added nodes since last call to flushNew. */ public PointsToSetInternal getNewSet() { return newSet; } /** Sets all newly-added nodes to old nodes. */ public void flushNew() { oldSet.addAll(newSet, null); newSet = G.v().newSetFactory.newSet(type, pag); } /** Sets all nodes to newly-added nodes. */ public void unFlushNew() { newSet.addAll(oldSet, null); oldSet = G.v().oldSetFactory.newSet(type, pag); } /** Merges other into this set. */ public void mergeWith(PointsToSetInternal other) {<FILL_FUNCTION_BODY>} /** Returns true iff the set contains n. */ public boolean contains(Node n) { return oldSet.contains(n) || newSet.contains(n); } private static P2SetFactory defaultP2SetFactory = new P2SetFactory() { public PointsToSetInternal newSet(Type type, PAG pag) { return new DoublePointsToSet(type, pag); } }; public static P2SetFactory getFactory(P2SetFactory newFactory, P2SetFactory oldFactory) { G.v().newSetFactory = newFactory; G.v().oldSetFactory = oldFactory; return defaultP2SetFactory; } /* End of public methods. */ /* End of package methods. */ private PAG pag; protected PointsToSetInternal newSet; protected PointsToSetInternal oldSet; }
if (!(other instanceof DoublePointsToSet)) { throw new RuntimeException("NYI"); } final DoublePointsToSet o = (DoublePointsToSet) other; if ((other.type != null && !(other.type.equals(type))) || (other.type == null && type != null)) { throw new RuntimeException("different types " + type + " and " + other.type); } final PointsToSetInternal newNewSet = G.v().newSetFactory.newSet(type, pag); final PointsToSetInternal newOldSet = G.v().oldSetFactory.newSet(type, pag); oldSet.forall(new P2SetVisitor() { public final void visit(Node n) { if (o.oldSet.contains(n)) { newOldSet.add(n); } } }); newNewSet.addAll(this, newOldSet); newNewSet.addAll(o, newOldSet); newSet = newNewSet; oldSet = newOldSet;
946
266
1,212
<methods>public void <init>(soot.Type) ,public abstract boolean add(soot.jimple.spark.pag.Node) ,public boolean addAll(soot.jimple.spark.sets.PointsToSetInternal, soot.jimple.spark.sets.PointsToSetInternal) ,public abstract boolean contains(soot.jimple.spark.pag.Node) ,public void flushNew() ,public abstract boolean forall(soot.jimple.spark.sets.P2SetVisitor) ,public soot.jimple.spark.sets.PointsToSetInternal getNewSet() ,public soot.jimple.spark.sets.PointsToSetInternal getOldSet() ,public soot.Type getType() ,public boolean hasNonEmptyIntersection(soot.PointsToSet) ,public void mergeWith(soot.jimple.spark.sets.PointsToSetInternal) ,public boolean pointsToSetEquals(java.lang.Object) ,public int pointsToSetHashCode() ,public Set<soot.jimple.ClassConstant> possibleClassConstants() ,public Set<java.lang.String> possibleStringConstants() ,public Set<soot.Type> possibleTypes() ,public void setType(soot.Type) ,public int size() ,public java.lang.String toString() ,public void unFlushNew() <variables>private static final org.slf4j.Logger logger,protected soot.Type type
soot-oss_soot
soot/src/main/java/soot/jimple/spark/sets/HashPointsToSet.java
HashPointsToSet
add
class HashPointsToSet extends PointsToSetInternal { public HashPointsToSet(Type type, PAG pag) { super(type); this.pag = pag; } /** Returns true if this set contains no run-time objects. */ public final boolean isEmpty() { return s.isEmpty(); } /** * Adds contents of other into this set, returns true if this set changed. */ public final boolean addAll(final PointsToSetInternal other, final PointsToSetInternal exclude) { if (other instanceof HashPointsToSet && exclude == null && (pag.getTypeManager().getFastHierarchy() == null || type == null || type.equals(other.type))) { return s.addAll(((HashPointsToSet) other).s); } else { return super.addAll(other, exclude); } } /** Calls v's visit method on all nodes in this set. */ public final boolean forall(P2SetVisitor v) { for (Iterator<Node> it = new ArrayList<Node>(s).iterator(); it.hasNext();) { v.visit(it.next()); } return v.getReturnValue(); } /** Adds n to this set, returns true if n was not already in this set. */ public final boolean add(Node n) {<FILL_FUNCTION_BODY>} /** Returns true iff the set contains n. */ public final boolean contains(Node n) { return s.contains(n); } public static P2SetFactory getFactory() { return new P2SetFactory() { public PointsToSetInternal newSet(Type type, PAG pag) { return new HashPointsToSet(type, pag); } }; } /* End of public methods. */ /* End of package methods. */ private final HashSet<Node> s = new HashSet<Node>(4); private PAG pag = null; }
if (pag.getTypeManager().castNeverFails(n.getType(), type)) { return s.add(n); } return false;
506
44
550
<methods>public void <init>(soot.Type) ,public abstract boolean add(soot.jimple.spark.pag.Node) ,public boolean addAll(soot.jimple.spark.sets.PointsToSetInternal, soot.jimple.spark.sets.PointsToSetInternal) ,public abstract boolean contains(soot.jimple.spark.pag.Node) ,public void flushNew() ,public abstract boolean forall(soot.jimple.spark.sets.P2SetVisitor) ,public soot.jimple.spark.sets.PointsToSetInternal getNewSet() ,public soot.jimple.spark.sets.PointsToSetInternal getOldSet() ,public soot.Type getType() ,public boolean hasNonEmptyIntersection(soot.PointsToSet) ,public void mergeWith(soot.jimple.spark.sets.PointsToSetInternal) ,public boolean pointsToSetEquals(java.lang.Object) ,public int pointsToSetHashCode() ,public Set<soot.jimple.ClassConstant> possibleClassConstants() ,public Set<java.lang.String> possibleStringConstants() ,public Set<soot.Type> possibleTypes() ,public void setType(soot.Type) ,public int size() ,public java.lang.String toString() ,public void unFlushNew() <variables>private static final org.slf4j.Logger logger,protected soot.Type type
soot-oss_soot
soot/src/main/java/soot/jimple/spark/sets/PointsToBitVector.java
PointsToBitVector
add
class PointsToBitVector extends BitVector { public PointsToBitVector(int size) { super(size); } /** * Adds n to this * * @return Whether this actually changed */ public boolean add(Node n) {<FILL_FUNCTION_BODY>} public boolean contains(Node n) { // Ripped from the HybridPointsToSet implementation // I'm assuming `number' in Node is the location of the node out of all // possible nodes. return get(n.getNumber()); } /** * Adds the Nodes in arr to this bitvector, adding at most size Nodes. * * @return The number of new nodes actually added. */ /* * public int add(Node[] arr, int size) { //assert size <= arr.length; int retVal = 0; for (int i = 0; i < size; ++i) { int * num = arr[i].getNumber(); if (!get(num)) { set(num); ++retVal; } } return retVal; } */ /** Returns true iff other is a subset of this bitvector */ public boolean isSubsetOf(PointsToBitVector other) { // B is a subset of A iff the "and" of A and B gives A. BitVector andResult = BitVector.and(this, other); // Don't want to modify either one return andResult.equals(this); } /** * @return number of 1 bits in the bitset. Call this sparingly because it's probably expensive. */ /* * Old algorithm: public int cardinality() { int retVal = 0; BitSetIterator it = iterator(); while (it.hasNext()) { * it.next(); ++retVal; } return retVal; } */ public PointsToBitVector(PointsToBitVector other) { super(other); /* * PointsToBitVector retVal = (PointsToBitVector)(other.clone()); return retVal; */ } // Reference counting: private int refCount = 0; public void incRefCount() { ++refCount; // An estimate of how much sharing is going on (but it should be 1 less // than the printed value in some cases, because incRefCount is called // for an intermediate result in nativeAddAll. // System.out.println("Reference count = " + refCount); } public void decRefCount() { --refCount; } public boolean unused() { return refCount == 0; } }
int num = n.getNumber(); if (!get(num)) // if it's not already in this { set(num); return true; } else { return false; }
660
59
719
<methods>public void <init>() ,public void <init>(soot.util.BitVector) ,public void <init>(int) ,public void and(soot.util.BitVector) ,public static soot.util.BitVector and(soot.util.BitVector, soot.util.BitVector) ,public void andNot(soot.util.BitVector) ,public int cardinality() ,public void clear(int) ,public java.lang.Object clone() ,public void copyFrom(soot.util.BitVector) ,public boolean equals(java.lang.Object) ,public boolean get(int) ,public int hashCode() ,public boolean intersects(soot.util.BitVector) ,public soot.util.BitSetIterator iterator() ,public int length() ,public void or(soot.util.BitVector) ,public static soot.util.BitVector or(soot.util.BitVector, soot.util.BitVector) ,public boolean orAndAndNot(soot.util.BitVector, soot.util.BitVector, soot.util.BitVector) ,public boolean set(int) ,public int size() ,public java.lang.String toString() ,public void xor(soot.util.BitVector) <variables>private long[] bits
soot-oss_soot
soot/src/main/java/soot/jimple/spark/sets/PointsToSetEqualsWrapper.java
PointsToSetEqualsWrapper
hasNonEmptyIntersection
class PointsToSetEqualsWrapper implements PointsToSet { protected EqualsSupportingPointsToSet pts; public PointsToSetEqualsWrapper(EqualsSupportingPointsToSet pts) { this.pts = pts; } public EqualsSupportingPointsToSet unwarp() { return this.pts; } /** * {@inheritDoc} */ @Override public int hashCode() { // delegate return pts.pointsToSetHashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj || this.pts == obj) { return true; } // unwrap other obj = unwrapIfNecessary(obj); // delegate return pts.pointsToSetEquals(obj); } /** * @param other * @return * @see soot.PointsToSet#hasNonEmptyIntersection(soot.PointsToSet) */ public boolean hasNonEmptyIntersection(PointsToSet other) {<FILL_FUNCTION_BODY>} /** * @return * @see soot.PointsToSet#isEmpty() */ public boolean isEmpty() { return pts.isEmpty(); } /** * @return * @see soot.PointsToSet#possibleClassConstants() */ public Set<ClassConstant> possibleClassConstants() { return pts.possibleClassConstants(); } /** * @return * @see soot.PointsToSet#possibleStringConstants() */ public Set<String> possibleStringConstants() { return pts.possibleStringConstants(); } /** * @return * @see soot.PointsToSet#possibleTypes() */ public Set<Type> possibleTypes() { return pts.possibleTypes(); } protected Object unwrapIfNecessary(Object obj) { if (obj instanceof PointsToSetEqualsWrapper) { PointsToSetEqualsWrapper wrapper = (PointsToSetEqualsWrapper) obj; obj = wrapper.pts; } return obj; } /** * {@inheritDoc} */ @Override public String toString() { return pts.toString(); } }
// unwrap other other = (PointsToSet) unwrapIfNecessary(other); return pts.hasNonEmptyIntersection(other);
606
41
647
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/sets/SortedArraySet.java
SortedArraySet
add
class SortedArraySet extends PointsToSetInternal { public SortedArraySet(Type type, PAG pag) { super(type); this.pag = pag; } /** Returns true if this set contains no run-time objects. */ public final boolean isEmpty() { return size == 0; } /** * Adds contents of other into this set, returns true if this set changed. */ public final boolean addAll(final PointsToSetInternal other, final PointsToSetInternal exclude) { boolean ret = false; BitVector typeMask = (pag.getTypeManager()).get(type); if (other instanceof SortedArraySet) { SortedArraySet o = (SortedArraySet) other; Node[] mya = nodes; Node[] oa = o.nodes; int osize = o.size; Node[] newa = new Node[size + osize]; int myi = 0; int oi = 0; int newi = 0; for (;;) { if (myi < size) { if (oi < osize) { int myhc = mya[myi].getNumber(); int ohc = oa[oi].getNumber(); if (myhc < ohc) { newa[newi++] = mya[myi++]; } else if (myhc > ohc) { if ((type == null || typeMask == null || typeMask.get(ohc)) && (exclude == null || !exclude.contains(oa[oi]))) { newa[newi++] = oa[oi]; ret = true; } oi++; } else { newa[newi++] = mya[myi++]; oi++; } } else { // oi >= osize newa[newi++] = mya[myi++]; } } else { // myi >= size if (oi < osize) { int ohc = oa[oi].getNumber(); if ((type == null || typeMask == null || typeMask.get(ohc)) && (exclude == null || !exclude.contains(oa[oi]))) { newa[newi++] = oa[oi]; ret = true; } oi++; } else { break; } } } nodes = newa; size = newi; return ret; } return super.addAll(other, exclude); } /** Calls v's visit method on all nodes in this set. */ public final boolean forall(P2SetVisitor v) { for (int i = 0; i < size; i++) { v.visit(nodes[i]); } return v.getReturnValue(); } /** Adds n to this set, returns true if n was not already in this set. */ public final boolean add(Node n) {<FILL_FUNCTION_BODY>} /** Returns true iff the set contains n. */ public final boolean contains(Node n) { int left = 0; int right = size; int hc = n.getNumber(); while (left < right) { int mid = (left + right) / 2; int midhc = nodes[mid].getNumber(); if (midhc < hc) { left = mid + 1; } else if (midhc > hc) { right = mid; } else { return true; } } return false; } public final static P2SetFactory getFactory() { return new P2SetFactory() { public final PointsToSetInternal newSet(Type type, PAG pag) { return new SortedArraySet(type, pag); } }; } /* End of public methods. */ /* End of package methods. */ private Node[] nodes = null; private int size = 0; private PAG pag = null; }
if (pag.getTypeManager().castNeverFails(n.getType(), type)) { if (contains(n)) { return false; } int left = 0; int right = size; int mid; int hc = n.getNumber(); while (left < right) { mid = (left + right) / 2; int midhc = nodes[mid].getNumber(); if (midhc < hc) { left = mid + 1; } else if (midhc > hc) { right = mid; } else { break; } } if (nodes == null) { nodes = new Node[size + 4]; } else if (size == nodes.length) { Node[] newNodes = new Node[size + 4]; System.arraycopy(nodes, 0, newNodes, 0, nodes.length); nodes = newNodes; } System.arraycopy(nodes, left, nodes, left + 1, size - left); nodes[left] = n; size++; return true; } return false;
1,036
291
1,327
<methods>public void <init>(soot.Type) ,public abstract boolean add(soot.jimple.spark.pag.Node) ,public boolean addAll(soot.jimple.spark.sets.PointsToSetInternal, soot.jimple.spark.sets.PointsToSetInternal) ,public abstract boolean contains(soot.jimple.spark.pag.Node) ,public void flushNew() ,public abstract boolean forall(soot.jimple.spark.sets.P2SetVisitor) ,public soot.jimple.spark.sets.PointsToSetInternal getNewSet() ,public soot.jimple.spark.sets.PointsToSetInternal getOldSet() ,public soot.Type getType() ,public boolean hasNonEmptyIntersection(soot.PointsToSet) ,public void mergeWith(soot.jimple.spark.sets.PointsToSetInternal) ,public boolean pointsToSetEquals(java.lang.Object) ,public int pointsToSetHashCode() ,public Set<soot.jimple.ClassConstant> possibleClassConstants() ,public Set<java.lang.String> possibleStringConstants() ,public Set<soot.Type> possibleTypes() ,public void setType(soot.Type) ,public int size() ,public java.lang.String toString() ,public void unFlushNew() <variables>private static final org.slf4j.Logger logger,protected soot.Type type
soot-oss_soot
soot/src/main/java/soot/jimple/spark/solver/OnFlyCallGraph.java
OnFlyCallGraph
updatedNode
class OnFlyCallGraph { protected final OnFlyCallGraphBuilder ofcgb; protected final ReachableMethods reachableMethods; protected final QueueReader<MethodOrMethodContext> reachablesReader; protected final QueueReader<Edge> callEdges; protected final CallGraph callGraph; private static final Logger logger = LoggerFactory.getLogger(OnFlyCallGraph.class); public ReachableMethods reachableMethods() { return reachableMethods; } public CallGraph callGraph() { return callGraph; } public OnFlyCallGraph(PAG pag, boolean appOnly) { this.pag = pag; callGraph = Scene.v().internalMakeCallGraph(); Scene.v().setCallGraph(callGraph); ContextManager cm = CallGraphBuilder.makeContextManager(callGraph); reachableMethods = Scene.v().getReachableMethods(); ofcgb = createOnFlyCallGraphBuilder(cm, reachableMethods, appOnly); reachablesReader = reachableMethods.listener(); callEdges = cm.callGraph().listener(); } /** * Factory method for creating a new on-fly callgraph builder. Custom implementations can override this method for * injecting own callgraph builders without having to modify Soot. * * @param cm * The context manager * @param reachableMethods * The reachable method set * @param appOnly * True to only consider application code * @return The new on-fly callgraph builder */ protected OnFlyCallGraphBuilder createOnFlyCallGraphBuilder(ContextManager cm, ReachableMethods reachableMethods, boolean appOnly) { return new OnFlyCallGraphBuilder(cm, reachableMethods, appOnly); } public void build() { ofcgb.processReachables(); processReachables(); processCallEdges(); } private void processReachables() { reachableMethods.update(); while (reachablesReader.hasNext()) { MethodOrMethodContext m = reachablesReader.next(); if (m == null) { continue; } MethodPAG mpag = MethodPAG.v(pag, m.method()); try { mpag.build(); } catch (Exception e) { String msg = String.format("An error occurred while processing %s in callgraph", mpag.getMethod()); if (Options.v().allow_cg_errors()) { logger.error(msg, e); } else { throw new RuntimeException(msg, e); } } mpag.addToPAG(m.context()); } } private void processCallEdges() { while (callEdges.hasNext()) { Edge e = callEdges.next(); if (e == null) { continue; } MethodPAG amp = MethodPAG.v(pag, e.tgt()); amp.build(); amp.addToPAG(e.tgtCtxt()); pag.addCallTarget(e); } } public OnFlyCallGraphBuilder ofcgb() { return ofcgb; } public void updatedFieldRef(final AllocDotField df, PointsToSetInternal ptsi) { if (df.getField() != ArrayElement.v()) { return; } if (ofcgb.wantArrayField(df)) { ptsi.forall(new P2SetVisitor() { @Override public void visit(Node n) { ofcgb.addInvokeArgType(df, null, n.getType()); } }); } } public void updatedNode(VarNode vn) {<FILL_FUNCTION_BODY>} /** Node uses this to notify PAG that n2 has been merged into n1. */ public void mergedWith(Node n1, Node n2) { } /* End of public methods. */ /* End of package methods. */ private PAG pag; }
Object r = vn.getVariable(); if (!(r instanceof Local)) { return; } final Local receiver = (Local) r; final Context context = vn.context(); PointsToSetInternal p2set = vn.getP2Set().getNewSet(); if (ofcgb.wantTypes(receiver)) { p2set.forall(new P2SetVisitor() { public final void visit(Node n) { if (n instanceof AllocNode) { ofcgb.addType(receiver, context, n.getType(), (AllocNode) n); } } }); } if (ofcgb.wantStringConstants(receiver)) { p2set.forall(new P2SetVisitor() { public final void visit(Node n) { if (n instanceof StringConstantNode) { String constant = ((StringConstantNode) n).getString(); ofcgb.addStringConstant(receiver, context, constant); } else { ofcgb.addStringConstant(receiver, context, null); } } }); } if (ofcgb.wantInvokeArg(receiver)) { p2set.forall(new P2SetVisitor() { @Override public void visit(Node n) { if (n instanceof AllocNode) { AllocNode an = ((AllocNode) n); ofcgb.addInvokeArgDotField(receiver, pag.makeAllocDotField(an, ArrayElement.v())); assert an.getNewExpr() instanceof NewArrayExpr; NewArrayExpr nae = (NewArrayExpr) an.getNewExpr(); if (!(nae.getSize() instanceof IntConstant)) { ofcgb.setArgArrayNonDetSize(receiver, context); } else { IntConstant sizeConstant = (IntConstant) nae.getSize(); ofcgb.addPossibleArgArraySize(receiver, sizeConstant.value, context); } } } }); for (Type ty : pag.reachingObjectsOfArrayElement(p2set).possibleTypes()) { ofcgb.addInvokeArgType(receiver, context, ty); } }
1,043
562
1,605
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/solver/PropMerge.java
PropMerge
handleVarNode
class PropMerge extends Propagator { private static final Logger logger = LoggerFactory.getLogger(PropMerge.class); protected final Set<Node> varNodeWorkList = new TreeSet<Node>(); public PropMerge(PAG pag) { this.pag = pag; } /** Actually does the propagation. */ public void propagate() { new TopoSorter(pag, false).sort(); for (Object object : pag.allocSources()) { handleAllocNode((AllocNode) object); } boolean verbose = pag.getOpts().verbose(); do { if (verbose) { logger.debug("Worklist has " + varNodeWorkList.size() + " nodes."); } int iter = 0; while (!varNodeWorkList.isEmpty()) { VarNode src = (VarNode) varNodeWorkList.iterator().next(); varNodeWorkList.remove(src); handleVarNode(src); if (verbose) { iter++; if (iter >= 1000) { iter = 0; logger.debug("Worklist has " + varNodeWorkList.size() + " nodes."); } } } if (verbose) { logger.debug("Now handling field references"); } for (Object object : pag.storeSources()) { final VarNode src = (VarNode) object; Node[] storeTargets = pag.storeLookup(src); for (Node element0 : storeTargets) { final FieldRefNode fr = (FieldRefNode) element0; fr.makeP2Set().addAll(src.getP2Set(), null); } } for (Object object : pag.loadSources()) { final FieldRefNode src = (FieldRefNode) object; if (src != src.getReplacement()) { throw new RuntimeException("shouldn't happen"); } Node[] targets = pag.loadLookup(src); for (Node element0 : targets) { VarNode target = (VarNode) element0; if (target.makeP2Set().addAll(src.getP2Set(), null)) { varNodeWorkList.add(target); } } } } while (!varNodeWorkList.isEmpty()); } /* End of public methods. */ /* End of package methods. */ /** * Propagates new points-to information of node src to all its successors. */ protected boolean handleAllocNode(AllocNode src) { boolean ret = false; Node[] targets = pag.allocLookup(src); for (Node element : targets) { if (element.makeP2Set().add(src)) { varNodeWorkList.add(element); ret = true; } } return ret; } /** * Propagates new points-to information of node src to all its successors. */ protected boolean handleVarNode(final VarNode src) {<FILL_FUNCTION_BODY>} protected PAG pag; }
boolean ret = false; if (src.getReplacement() != src) { return ret; /* * throw new RuntimeException( "Got bad node "+src+" with rep "+src.getReplacement() ); */ } final PointsToSetInternal newP2Set = src.getP2Set(); if (newP2Set.isEmpty()) { return false; } Node[] simpleTargets = pag.simpleLookup(src); for (Node element : simpleTargets) { if (element.makeP2Set().addAll(newP2Set, null)) { varNodeWorkList.add(element); ret = true; } } Node[] storeTargets = pag.storeLookup(src); for (Node element : storeTargets) { final FieldRefNode fr = (FieldRefNode) element; if (fr.makeP2Set().addAll(newP2Set, null)) { ret = true; } } for (final FieldRefNode fr : src.getAllFieldRefs()) { final SparkField field = fr.getField(); ret = newP2Set.forall(new P2SetVisitor() { public final void visit(Node n) { AllocDotField nDotF = pag.makeAllocDotField((AllocNode) n, field); Node nDotFNode = nDotF.getReplacement(); if (nDotFNode != fr) { fr.mergeWith(nDotFNode); returnValue = true; } } }) | ret; } // src.getP2Set().flushNew(); return ret;
785
437
1,222
<methods>public non-sealed void <init>() ,public abstract void propagate() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/spark/solver/TopoSorter.java
TopoSorter
sort
class TopoSorter { /** Actually perform the topological sort on the PAG. */ public void sort() {<FILL_FUNCTION_BODY>} public TopoSorter(PAG pag, boolean ignoreTypes) { this.pag = pag; this.ignoreTypes = ignoreTypes; // this.visited = new NumberedSet( pag.getVarNodeNumberer() ); this.visited = new HashSet<VarNode>(); } /* End of public methods. */ /* End of package methods. */ protected boolean ignoreTypes; protected PAG pag; protected int nextFinishNumber = 1; protected HashSet<VarNode> visited; protected void dfsVisit(VarNode n) { if (visited.contains(n)) { return; } List<VarNode> stack = new ArrayList<>(); List<VarNode> all = new ArrayList<>(); stack.add(n); while (!stack.isEmpty()) { VarNode s = stack.remove(stack.size() - 1); if (visited.add(s)) { all.add(s); Node[] succs = pag.simpleLookup(s); for (Node element : succs) { if (ignoreTypes || pag.getTypeManager().castNeverFails(n.getType(), element.getType())) { stack.add((VarNode) element); } } } } for (int i = all.size() - 1; i >= 0; i--) { all.get(i).setFinishingNumber(nextFinishNumber++); } } }
for (VarNode v : pag.getVarNodeNumberer()) { dfsVisit(v); } visited = null;
415
38
453
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/AvailExprTagger.java
AvailExprTagger
internalTransform
class AvailExprTagger extends BodyTransformer { public AvailExprTagger(Singletons.Global g) { } public static AvailExprTagger v() { return G.v().soot_jimple_toolkits_annotation_AvailExprTagger(); } protected void internalTransform(Body b, String phaseName, Map opts) {<FILL_FUNCTION_BODY>} }
SideEffectTester sideEffect; if (Scene.v().hasCallGraph() && !PhaseOptions.getBoolean(opts, "naive-side-effect")) { sideEffect = new PASideEffectTester(); } else { sideEffect = new NaiveSideEffectTester(); } sideEffect.newMethod(b.getMethod()); AETOptions options = new AETOptions(opts); if (options.kind() == AETOptions.kind_optimistic) { new SlowAvailableExpressionsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b)); } else { new PessimisticAvailableExpressionsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b), b.getMethod(), sideEffect); }
107
197
304
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/DominatorsTagger.java
DominatorsTagger
internalTransform
class DominatorsTagger extends BodyTransformer { public DominatorsTagger(Singletons.Global g) { } public static DominatorsTagger v() { return G.v().soot_jimple_toolkits_annotation_DominatorsTagger(); } protected void internalTransform(Body b, String phaseName, Map opts) {<FILL_FUNCTION_BODY>} }
MHGDominatorsFinder analysis = new MHGDominatorsFinder(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b)); Iterator it = b.getUnits().iterator(); while (it.hasNext()) { Stmt s = (Stmt) it.next(); List dominators = analysis.getDominators(s); Iterator dIt = dominators.iterator(); while (dIt.hasNext()) { Stmt ds = (Stmt) dIt.next(); String info = ds + " dominates " + s; s.addTag(new LinkTag(info, ds, b.getMethod().getDeclaringClass().getName(), "Dominators")); } }
104
181
285
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/LineNumberAdder.java
LineNumberAdder
internalTransform
class LineNumberAdder extends SceneTransformer { public LineNumberAdder(Singletons.Global g) { } public static LineNumberAdder v() { return G.v().soot_jimple_toolkits_annotation_LineNumberAdder(); } @Override public void internalTransform(String phaseName, Map<String, String> opts) {<FILL_FUNCTION_BODY>} }
// using a snapshot iterator because Application classes may change if LambdaMetaFactory translates // invokedynamic to new classes; no need to visit new classes for (Iterator<SootClass> it = Scene.v().getApplicationClasses().snapshotIterator(); it.hasNext();) { SootClass sc = it.next(); // make map of first line to each method HashMap<Integer, SootMethod> lineToMeth = new HashMap<Integer, SootMethod>(); for (SootMethod meth : new ArrayList<>(sc.getMethods())) { if (!meth.isConcrete()) { continue; } Chain<Unit> units = meth.retrieveActiveBody().getUnits(); Unit s = units.getFirst(); while (s instanceof IdentityStmt) { s = units.getSuccOf(s); } LineNumberTag tag = (LineNumberTag) s.getTag(LineNumberTag.NAME); if (tag != null) { lineToMeth.put(tag.getLineNumber(), meth); } } for (SootMethod meth : sc.getMethods()) { if (!meth.isConcrete()) { continue; } Chain<Unit> units = meth.retrieveActiveBody().getUnits(); Unit s = units.getFirst(); while (s instanceof IdentityStmt) { s = units.getSuccOf(s); } LineNumberTag tag = (LineNumberTag) s.getTag(LineNumberTag.NAME); if (tag != null) { int line_num = tag.getLineNumber() - 1; // already taken if (lineToMeth.containsKey(line_num)) { meth.addTag(new LineNumberTag(line_num + 1)); } else { // still available - so use it for this meth meth.addTag(new LineNumberTag(line_num)); } } } }
111
499
610
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/Array2ndDimensionSymbol.java
Array2ndDimensionSymbol
equals
class Array2ndDimensionSymbol { private Object var; public static Array2ndDimensionSymbol v(Object which) { Array2ndDimensionSymbol tdal = G.v().Array2ndDimensionSymbol_pool.get(which); if (tdal == null) { tdal = new Array2ndDimensionSymbol(which); G.v().Array2ndDimensionSymbol_pool.put(which, tdal); } return tdal; } private Array2ndDimensionSymbol(Object which) { this.var = which; } public Object getVar() { return this.var; } public int hashCode() { return var.hashCode() + 1; } public boolean equals(Object other) {<FILL_FUNCTION_BODY>} public String toString() { return var + "["; } }
if (other instanceof Array2ndDimensionSymbol) { Array2ndDimensionSymbol another = (Array2ndDimensionSymbol) other; return (this.var == another.var); } else { return false; }
232
63
295
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/ArrayReferenceNode.java
ArrayReferenceNode
equals
class ArrayReferenceNode { private final SootMethod m; private final Local l; public ArrayReferenceNode(SootMethod method, Local local) { m = method; l = local; } public SootMethod getMethod() { return m; } public Local getLocal() { return l; } public int hashCode() { return m.hashCode() + l.hashCode() + 1; } public boolean equals(Object other) {<FILL_FUNCTION_BODY>} public String toString() { return "[" + m.getSignature() + " : " + l.toString() + "[ ]"; } }
if (other instanceof ArrayReferenceNode) { ArrayReferenceNode another = (ArrayReferenceNode) other; return m.equals(another.getMethod()) && l.equals(another.getLocal()); } return false;
180
59
239
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/BoolValue.java
BoolValue
or
class BoolValue { private boolean isRectangular; private static final BoolValue trueValue = new BoolValue(true); private static final BoolValue falseValue = new BoolValue(false); public BoolValue(boolean v) { isRectangular = v; } public static BoolValue v(boolean v) { if (v) { return trueValue; } else { return falseValue; } } public boolean getValue() { return isRectangular; } public boolean or(BoolValue other) {<FILL_FUNCTION_BODY>} public boolean or(boolean other) { if (other) { isRectangular = true; } return isRectangular; } public boolean and(BoolValue other) { if (!other.getValue()) { isRectangular = false; } return isRectangular; } public boolean and(boolean other) { if (!other) { isRectangular = false; } return isRectangular; } public int hashCode() { if (isRectangular) { return 1; } else { return 0; } } public boolean equals(Object other) { if (other instanceof BoolValue) { return isRectangular == ((BoolValue) other).getValue(); } return false; } public String toString() { return "[" + isRectangular + "]"; } }
if (other.getValue()) { isRectangular = true; } return isRectangular;
400
31
431
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/BoundedPriorityList.java
BoundedPriorityList
addAll
class BoundedPriorityList implements Collection { protected final List fulllist; protected ArrayList worklist; public BoundedPriorityList(List list) { this.fulllist = list; this.worklist = new ArrayList(list); } public boolean isEmpty() { return worklist.isEmpty(); } public Object removeFirst() { return worklist.remove(0); } public boolean add(Object toadd) { if (contains(toadd)) { return false; } /* it is not added to the end, but keep it in the order */ int index = fulllist.indexOf(toadd); for (ListIterator worklistIter = worklist.listIterator(); worklistIter.hasNext();) { Object tocomp = worklistIter.next(); int tmpidx = fulllist.indexOf(tocomp); if (index < tmpidx) { worklistIter.add(toadd); return true; } } return false; } // rest is only necessary to implement the Collection interface /** * {@inheritDoc} */ public boolean addAll(Collection c) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ public boolean addAll(int index, Collection c) { throw new RuntimeException("Not supported. You should use addAll(Collection) to keep priorities."); } /** * {@inheritDoc} */ public void clear() { worklist.clear(); } /** * {@inheritDoc} */ public boolean contains(Object o) { return worklist.contains(o); } /** * {@inheritDoc} */ public boolean containsAll(Collection c) { return worklist.containsAll(c); } /** * {@inheritDoc} */ public Iterator iterator() { return worklist.iterator(); } /** * {@inheritDoc} */ public boolean remove(Object o) { return worklist.remove(o); } /** * {@inheritDoc} */ public boolean removeAll(Collection c) { return worklist.removeAll(c); } /** * {@inheritDoc} */ public boolean retainAll(Collection c) { return worklist.retainAll(c); } /** * {@inheritDoc} */ public int size() { return worklist.size(); } /** * {@inheritDoc} */ public Object[] toArray() { return worklist.toArray(); } /** * {@inheritDoc} */ public Object[] toArray(Object[] a) { return worklist.toArray(a); } /** * {@inheritDoc} */ public String toString() { return worklist.toString(); } /** * {@inheritDoc} */ public boolean equals(Object obj) { return worklist.equals(obj); } /** * {@inheritDoc} */ public int hashCode() { return worklist.hashCode(); } }
boolean addedSomething = false; for (Iterator iter = c.iterator(); iter.hasNext();) { Object o = iter.next(); addedSomething |= add(o); } return addedSomething;
837
56
893
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/IntContainer.java
IntContainer
v
class IntContainer { static IntContainer[] pool = new IntContainer[100]; static { for (int i = 0; i < 100; i++) { pool[i] = new IntContainer(i - 50); } } int value; public IntContainer(int v) { this.value = v; } public static IntContainer v(int v) {<FILL_FUNCTION_BODY>} public IntContainer dup() { return new IntContainer(value); } public int hashCode() { return value; } public boolean equals(Object other) { if (other instanceof IntContainer) { return ((IntContainer) other).value == this.value; } return false; } public String toString() { return "" + value; } }
if ((v >= -50) && (v <= 49)) { return pool[v + 50]; } else { return new IntContainer(v); }
229
48
277
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/IntValueContainer.java
IntValueContainer
equals
class IntValueContainer { private static final int BOT = 0; private static final int TOP = 1; private static final int INT = 2; private int type; private int value; public IntValueContainer() { this.type = BOT; } public IntValueContainer(int v) { this.type = INT; this.value = v; } public boolean isBottom() { return (this.type == BOT); } public boolean isTop() { return (this.type == TOP); } public boolean isInteger() { return this.type == INT; } public int getValue() { if (this.type != INT) { throw new RuntimeException("IntValueContainer: not integer type"); } return this.value; } public void setTop() { this.type = TOP; } public void setValue(int v) { this.type = INT; this.value = v; } public void setBottom() { this.type = BOT; } public String toString() { if (type == BOT) { return "[B]"; } else if (type == TOP) { return "[T]"; } else { return "[" + value + "]"; } } public boolean equals(Object other) {<FILL_FUNCTION_BODY>} public IntValueContainer dup() { IntValueContainer other = new IntValueContainer(); other.type = this.type; other.value = this.value; return other; } }
if (!(other instanceof IntValueContainer)) { return false; } IntValueContainer otherv = (IntValueContainer) other; if ((this.type == INT) && (otherv.type == INT)) { return (this.value == otherv.value); } else { return (this.type == otherv.type); }
433
94
527
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/MethodParameter.java
MethodParameter
toString
class MethodParameter { private SootMethod m; private int param; public MethodParameter(SootMethod m, int i) { this.m = m; this.param = i; } public Type getType() { return m.getParameterType(param); } public int hashCode() { return m.hashCode() + param; } public SootMethod getMethod() { return m; } public int getIndex() { return param; } public boolean equals(Object other) { if (other instanceof MethodParameter) { MethodParameter another = (MethodParameter) other; return (m.equals(another.getMethod()) && param == another.getIndex()); } return false; } public String toString() {<FILL_FUNCTION_BODY>} }
return "[" + m.getSignature() + " : P" + param + "]";
226
25
251
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/arraycheck/MethodReturn.java
MethodReturn
equals
class MethodReturn { private SootMethod m; public MethodReturn(SootMethod m) { this.m = m; } public SootMethod getMethod() { return m; } public Type getType() { return m.getReturnType(); } public int hashCode() { return m.hashCode() + m.getParameterCount(); } public boolean equals(Object other) {<FILL_FUNCTION_BODY>} public String toString() { return "[" + m.getSignature() + " : R]"; } }
if (other instanceof MethodReturn) { return m.equals(((MethodReturn) other).getMethod()); } return false;
158
38
196
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/callgraph/CallGraphGrapher.java
CallGraphGrapher
reset
class CallGraphGrapher extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(CallGraphGrapher.class); public CallGraphGrapher(Singletons.Global g) { } public static CallGraphGrapher v() { return G.v().soot_jimple_toolkits_annotation_callgraph_CallGraphGrapher(); } private MethodToContexts methodToContexts; private CallGraph cg; private boolean showLibMeths; private ArrayList<MethInfo> getTgtMethods(SootMethod method, boolean recurse) { // logger.debug("meth for tgts: "+method); if (!method.hasActiveBody()) { return new ArrayList<MethInfo>(); } Body b = method.getActiveBody(); ArrayList<MethInfo> list = new ArrayList<MethInfo>(); Iterator sIt = b.getUnits().iterator(); while (sIt.hasNext()) { Stmt s = (Stmt) sIt.next(); Iterator edges = cg.edgesOutOf(s); while (edges.hasNext()) { Edge e = (Edge) edges.next(); SootMethod sm = e.tgt(); // logger.debug("found target method: "+sm); if (sm.getDeclaringClass().isLibraryClass()) { if (isShowLibMeths()) { if (recurse) { list.add(new MethInfo(sm, hasTgtMethods(sm) | hasSrcMethods(sm), e.kind())); } else { list.add(new MethInfo(sm, true, e.kind())); } } } else { if (recurse) { list.add(new MethInfo(sm, hasTgtMethods(sm) | hasSrcMethods(sm), e.kind())); } else { list.add(new MethInfo(sm, true, e.kind())); } } } } return list; } private boolean hasTgtMethods(SootMethod meth) { ArrayList<MethInfo> list = getTgtMethods(meth, false); if (!list.isEmpty()) { return true; } else { return false; } } private boolean hasSrcMethods(SootMethod meth) { ArrayList<MethInfo> list = getSrcMethods(meth, false); if (list.size() > 1) { return true; } else { return false; } } private ArrayList<MethInfo> getSrcMethods(SootMethod method, boolean recurse) { // logger.debug("meth for srcs: "+method); ArrayList<MethInfo> list = new ArrayList<MethInfo>(); for (Iterator momcIt = methodToContexts.get(method).iterator(); momcIt.hasNext();) { final MethodOrMethodContext momc = (MethodOrMethodContext) momcIt.next(); Iterator callerEdges = cg.edgesInto(momc); while (callerEdges.hasNext()) { Edge callEdge = (Edge) callerEdges.next(); SootMethod methodCaller = callEdge.src(); if (methodCaller.getDeclaringClass().isLibraryClass()) { if (isShowLibMeths()) { if (recurse) { list.add( new MethInfo(methodCaller, hasTgtMethods(methodCaller) | hasSrcMethods(methodCaller), callEdge.kind())); } else { list.add(new MethInfo(methodCaller, true, callEdge.kind())); } } } else { if (recurse) { list.add(new MethInfo(methodCaller, hasTgtMethods(methodCaller) | hasSrcMethods(methodCaller), callEdge.kind())); } else { list.add(new MethInfo(methodCaller, true, callEdge.kind())); } } } } return list; } protected void internalTransform(String phaseName, Map options) { CGGOptions opts = new CGGOptions(options); if (opts.show_lib_meths()) { setShowLibMeths(true); } cg = Scene.v().getCallGraph(); if (Options.v().interactive_mode()) { reset(); } } public void reset() {<FILL_FUNCTION_BODY>} private SootMethod getFirstMethod(SootClass sc) { ArrayList paramTypes = new ArrayList(); paramTypes.add(soot.ArrayType.v(soot.RefType.v("java.lang.String"), 1)); SootMethod sm = sc.getMethodUnsafe("main", paramTypes, soot.VoidType.v()); if (sm != null) { return sm; } else { return (SootMethod) sc.getMethods().get(0); } } public void handleNextMethod() { if (!getNextMethod().hasActiveBody()) { return; } ArrayList<MethInfo> tgts = getTgtMethods(getNextMethod(), true); // System.out.println("for: "+getNextMethod().getName()+" tgts: "+tgts); ArrayList<MethInfo> srcs = getSrcMethods(getNextMethod(), true); // System.out.println("for: "+getNextMethod().getName()+" srcs: "+srcs); CallGraphInfo info = new CallGraphInfo(getNextMethod(), tgts, srcs); // System.out.println("sending next method"); InteractionHandler.v().handleCallGraphPart(info); // handleNextMethod(); } private SootMethod nextMethod; public void setNextMethod(SootMethod m) { nextMethod = m; } public SootMethod getNextMethod() { return nextMethod; } public void setShowLibMeths(boolean b) { showLibMeths = b; } public boolean isShowLibMeths() { return showLibMeths; } }
if (methodToContexts == null) { methodToContexts = new MethodToContexts(Scene.v().getReachableMethods().listener()); } if (Scene.v().hasCallGraph()) { SootClass sc = Scene.v().getMainClass(); SootMethod sm = getFirstMethod(sc); // logger.debug("got first method"); ArrayList<MethInfo> tgts = getTgtMethods(sm, true); // logger.debug("got tgt methods"); ArrayList<MethInfo> srcs = getSrcMethods(sm, true); // logger.debug("got src methods"); CallGraphInfo info = new CallGraphInfo(sm, tgts, srcs); // logger.debug("will handle new call graph"); InteractionHandler.v().handleCallGraphStart(info, this); }
1,609
218
1,827
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/fields/UnreachableFieldsTagger.java
UnreachableFieldsTagger
internalTransform
class UnreachableFieldsTagger extends SceneTransformer { public UnreachableFieldsTagger(Singletons.Global g) { } public static UnreachableFieldsTagger v() { return G.v().soot_jimple_toolkits_annotation_fields_UnreachableFieldsTagger(); } protected void internalTransform(String phaseName, Map options) {<FILL_FUNCTION_BODY>} }
// make list of all fields ArrayList<SootField> fieldList = new ArrayList<SootField>(); Iterator getClassesIt = Scene.v().getApplicationClasses().iterator(); while (getClassesIt.hasNext()) { SootClass appClass = (SootClass) getClassesIt.next(); // System.out.println("class to check: "+appClass); Iterator getFieldsIt = appClass.getFields().iterator(); while (getFieldsIt.hasNext()) { SootField field = (SootField) getFieldsIt.next(); // System.out.println("adding field: "+field); fieldList.add(field); } } // from all bodies get all use boxes and eliminate used fields getClassesIt = Scene.v().getApplicationClasses().iterator(); while (getClassesIt.hasNext()) { SootClass appClass = (SootClass) getClassesIt.next(); Iterator mIt = appClass.getMethods().iterator(); while (mIt.hasNext()) { SootMethod sm = (SootMethod) mIt.next(); // System.out.println("checking method: "+sm.getName()); if (!sm.hasActiveBody() || !Scene.v().getReachableMethods().contains(sm)) { continue; } Body b = sm.getActiveBody(); Iterator usesIt = b.getUseBoxes().iterator(); while (usesIt.hasNext()) { ValueBox vBox = (ValueBox) usesIt.next(); Value v = vBox.getValue(); if (v instanceof FieldRef) { FieldRef fieldRef = (FieldRef) v; SootField f = fieldRef.getField(); if (fieldList.contains(f)) { int index = fieldList.indexOf(f); fieldList.remove(index); // System.out.println("removed field: "+f); } } } } } // tag unused fields Iterator<SootField> unusedIt = fieldList.iterator(); while (unusedIt.hasNext()) { SootField unusedField = unusedIt.next(); unusedField.addTag(new StringTag("Field " + unusedField.getName() + " is not used!", "Unreachable Fields")); unusedField.addTag(new ColorTag(ColorTag.RED, true, "Unreachable Fields")); // System.out.println("tagged field: "+unusedField); }
112
637
749
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/j5anno/AnnotationGenerator.java
AnnotationGenerator
findOrAdd
class AnnotationGenerator { public AnnotationGenerator(Global g) { } /** * Returns the unique instance of AnnotationGenerator. */ public static AnnotationGenerator v() { return G.v().soot_jimple_toolkits_annotation_j5anno_AnnotationGenerator(); } /** * Applies a Java 1.5-style annotation to a given Host. The Host must be of type {@link SootClass}, {@link SootMethod} or * {@link SootField}. * * @param h * a method, field, or class * @param klass * the class of the annotation to apply to <code>h</code> * @param elems * a (possibly empty) sequence of AnnotationElem objects corresponding to the elements that should be contained in * this annotation */ public void annotate(Host h, Class<? extends Annotation> klass, AnnotationElem... elems) { annotate(h, klass, Arrays.asList(elems)); } /** * Applies a Java 1.5-style annotation to a given Host. The Host must be of type {@link SootClass}, {@link SootMethod} or * {@link SootField}. * * @param h * a method, field, or class * @param klass * the class of the annotation to apply to <code>h</code> * @param elems * a (possibly empty) sequence of AnnotationElem objects corresponding to the elements that should be contained in * this annotation */ public void annotate(Host h, Class<? extends Annotation> klass, List<AnnotationElem> elems) { // error-checking -- is this annotation appropriate for the target Host? Target t = klass.getAnnotation(Target.class); Collection<ElementType> elementTypes = Arrays.asList(t.value()); final String ERR = "Annotation class " + klass + " not applicable to host of type " + h.getClass() + "."; if (h instanceof SootClass) { if (!elementTypes.contains(ElementType.TYPE)) { throw new RuntimeException(ERR); } } else if (h instanceof SootMethod) { if (!elementTypes.contains(ElementType.METHOD)) { throw new RuntimeException(ERR); } } else if (h instanceof SootField) { if (!elementTypes.contains(ElementType.FIELD)) { throw new RuntimeException(ERR); } } else { throw new RuntimeException("Tried to attach annotation to host of type " + h.getClass() + "."); } // get the retention type of the class Retention r = klass.getAnnotation(Retention.class); // CLASS (runtime invisible) retention is the default int retPolicy = AnnotationConstants.RUNTIME_INVISIBLE; if (r != null) { // TODO why actually do we have AnnotationConstants at all and don't use // RetentionPolicy directly? (Eric Bodden 20/05/2008) switch (r.value()) { case CLASS: retPolicy = AnnotationConstants.RUNTIME_INVISIBLE; break; case RUNTIME: retPolicy = AnnotationConstants.RUNTIME_VISIBLE; break; default: throw new RuntimeException("Unexpected retention policy: " + retPolicy); } } annotate(h, klass.getCanonicalName(), retPolicy, elems); } /** * Applies a Java 1.5-style annotation to a given Host. The Host must be of type {@link SootClass}, {@link SootMethod} or * {@link SootField}. * * @param h * a method, field, or class * @param annotationName * the qualified name of the annotation class * @param visibility * any of the constants in {@link AnnotationConstants} * @param elems * a (possibly empty) sequence of AnnotationElem objects corresponding to the elements that should be contained in * this annotation */ public void annotate(Host h, String annotationName, int visibility, List<AnnotationElem> elems) { annotationName = annotationName.replace('.', '/'); if (!annotationName.endsWith(";")) { annotationName = "L" + annotationName + ';'; } VisibilityAnnotationTag tagToAdd = findOrAdd(h, visibility); AnnotationTag at = new AnnotationTag(annotationName, elems); tagToAdd.addAnnotation(at); } /** * Finds a VisibilityAnnotationTag attached to a given Host with the appropriate visibility, or adds one if no such tag is * attached. * * @param h * an Host * @param visibility * a visibility level, taken from soot.tagkit.AnnotationConstants * @return */ private VisibilityAnnotationTag findOrAdd(Host h, int visibility) {<FILL_FUNCTION_BODY>} }
ArrayList<VisibilityAnnotationTag> va_tags = new ArrayList<VisibilityAnnotationTag>(); for (Tag t : h.getTags()) { if (t instanceof VisibilityAnnotationTag) { VisibilityAnnotationTag vat = (VisibilityAnnotationTag) t; if (vat.getVisibility() == visibility) { va_tags.add(vat); } } } if (va_tags.isEmpty()) { VisibilityAnnotationTag vat = new VisibilityAnnotationTag(visibility); h.addTag(vat); return vat; } // return the first visibility annotation with the right visibility return (va_tags.get(0));
1,305
177
1,482
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/liveness/LiveVarsTagger.java
LiveVarsTagger
internalTransform
class LiveVarsTagger extends BodyTransformer { public LiveVarsTagger(Singletons.Global g) { } public static LiveVarsTagger v() { return G.v().soot_jimple_toolkits_annotation_liveness_LiveVarsTagger(); } protected void internalTransform(Body b, String phaseName, Map options) {<FILL_FUNCTION_BODY>} }
LiveLocals sll = new SimpleLiveLocals(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b)); Iterator it = b.getUnits().iterator(); while (it.hasNext()) { Stmt s = (Stmt) it.next(); // System.out.println("stmt: "+s); Iterator liveLocalsIt = sll.getLiveLocalsAfter(s).iterator(); while (liveLocalsIt.hasNext()) { Value v = (Value) liveLocalsIt.next(); s.addTag(new StringTag("Live Variable: " + v, "Live Variable")); Iterator usesIt = s.getUseBoxes().iterator(); while (usesIt.hasNext()) { ValueBox use = (ValueBox) usesIt.next(); if (use.getValue().equals(v)) { use.addTag(new ColorTag(ColorTag.GREEN, "Live Variable")); } } Iterator defsIt = s.getDefBoxes().iterator(); while (defsIt.hasNext()) { ValueBox def = (ValueBox) defsIt.next(); if (def.getValue().equals(v)) { def.addTag(new ColorTag(ColorTag.GREEN, "Live Variable")); } } } }
111
338
449
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/logic/Loop.java
Loop
getLoopExits
class Loop { protected final Stmt header; protected final Stmt backJump; protected final List<Stmt> loopStatements; protected final UnitGraph g; protected Collection<Stmt> loopExits; /** * Creates a new loop. Expects that the last statement in the list is the loop head and the second-last statement is the * back-jump to the head. {@link LoopFinder} will normally guarantee this. * * @param head * the loop header * @param loopStatements * an ordered list of loop statements, ending with the header * @param g * the unit graph according to which the loop exists */ Loop(Stmt head, List<Stmt> loopStatements, UnitGraph g) { this.header = head; this.g = g; // put header to the top loopStatements.remove(head); loopStatements.add(0, head); // last statement this.backJump = loopStatements.get(loopStatements.size() - 1); assert g.getSuccsOf(this.backJump).contains(head); // must branch back to the head this.loopStatements = loopStatements; } /** * @return the loop head */ public Stmt getHead() { return header; } /** * Returns the statement that jumps back to the head, thereby constituing the loop. */ public Stmt getBackJumpStmt() { return backJump; } /** * @return all statements of the loop, including the header; the header will be the first element returned and then the * other statements follow in the natural ordering of the loop */ public List<Stmt> getLoopStatements() { return loopStatements; } /** * Returns all loop exists. A loop exit is a statement which has a successor that is not contained in the loop. */ public Collection<Stmt> getLoopExits() {<FILL_FUNCTION_BODY>} /** * Computes all targets of the given loop exit, i.e. statements that the exit jumps to but which are not part of this loop. */ public Collection<Stmt> targetsOfLoopExit(Stmt loopExit) { assert getLoopExits().contains(loopExit); List<Unit> succs = g.getSuccsOf(loopExit); Collection<Stmt> res = new HashSet<Stmt>(); for (Unit u : succs) { Stmt s = (Stmt) u; res.add(s); } res.removeAll(loopStatements); return res; } /** * Returns <code>true</code> if this loop certainly loops forever, i.e. if it has not exit. * * @see #getLoopExits() */ public boolean loopsForever() { return getLoopExits().isEmpty(); } /** * Returns <code>true</code> if this loop has a single exit statement. * * @see #getLoopExits() */ public boolean hasSingleExit() { return getLoopExits().size() == 1; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((header == null) ? 0 : header.hashCode()); result = prime * result + ((loopStatements == null) ? 0 : loopStatements.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } final Loop other = (Loop) obj; if (header == null) { if (other.header != null) { return false; } } else if (!header.equals(other.header)) { return false; } if (loopStatements == null) { if (other.loopStatements != null) { return false; } } else if (!loopStatements.equals(other.loopStatements)) { return false; } return true; } }
if (loopExits == null) { loopExits = new HashSet<Stmt>(); for (Stmt s : loopStatements) { for (Unit succ : g.getSuccsOf(s)) { if (!loopStatements.contains(succ)) { loopExits.add(s); } } } } return loopExits;
1,141
102
1,243
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/logic/LoopFinder.java
LoopFinder
getLoops
class LoopFinder extends BodyTransformer { private Set<Loop> loops; public LoopFinder() { loops = null; } protected void internalTransform(Body b, String phaseName, Map<String, String> options) { getLoops(b); } public Set<Loop> getLoops(Body b) { if (loops != null) { return loops; } return getLoops(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b)); } public Set<Loop> getLoops(UnitGraph g) {<FILL_FUNCTION_BODY>} private List<Stmt> getLoopBodyFor(Unit header, Unit node, UnitGraph g) { List<Stmt> loopBody = new ArrayList<Stmt>(); Deque<Unit> stack = new ArrayDeque<Unit>(); loopBody.add((Stmt) header); stack.push(node); while (!stack.isEmpty()) { Stmt next = (Stmt) stack.pop(); if (!loopBody.contains(next)) { // add next to loop body loopBody.add(0, next); // put all preds of next on stack for (Unit u : g.getPredsOf(next)) { stack.push(u); } } } assert (node == header && loopBody.size() == 1) || loopBody.get(loopBody.size() - 2) == node; assert loopBody.get(loopBody.size() - 1) == header; return loopBody; } private List<Stmt> union(List<Stmt> l1, List<Stmt> l2) { for (Stmt next : l2) { if (!l1.contains(next)) { l1.add(next); } } return l1; } }
if (loops != null) { return loops; } MHGDominatorsFinder<Unit> a = new MHGDominatorsFinder<Unit>(g); Map<Stmt, List<Stmt>> loops = new HashMap<Stmt, List<Stmt>>(); for (Unit u : g.getBody().getUnits()) { List<Unit> succs = g.getSuccsOf(u); List<Unit> dominaters = a.getDominators(u); List<Stmt> headers = new ArrayList<Stmt>(); for (Unit succ : succs) { if (dominaters.contains(succ)) { // header succeeds and dominates s, we have a loop headers.add((Stmt) succ); } } for (Unit header : headers) { List<Stmt> loopBody = getLoopBodyFor(header, u, g); if (loops.containsKey(header)) { // merge bodies List<Stmt> lb1 = loops.get(header); loops.put((Stmt) header, union(lb1, loopBody)); } else { loops.put((Stmt) header, loopBody); } } } Set<Loop> ret = new HashSet<Loop>(); for (Map.Entry<Stmt, List<Stmt>> entry : loops.entrySet()) { ret.add(new Loop(entry.getKey(), entry.getValue(), g)); } this.loops = ret; return ret;
488
400
888
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/nullcheck/LocalRefVarsAnalysisWrapper.java
LocalRefVarsAnalysisWrapper
buildList
class LocalRefVarsAnalysisWrapper { // compilation options private static final boolean computeChecks = true; private static final boolean discardKTop = true; private final BranchedRefVarsAnalysis analysis; private final Map<Unit, List<RefIntPair>> unitToVarsBefore; private final Map<Unit, List<RefIntPair>> unitToVarsAfterFall; private final Map<Unit, List<List<RefIntPair>>> unitToListsOfVarsAfterBranches; private final Map<Unit, List<Object>> unitToVarsNeedCheck; private final Map<Unit, List<RefIntPair>> unitToVarsDontNeedCheck; // constructor, where we do all our computations public LocalRefVarsAnalysisWrapper(ExceptionalUnitGraph graph) { this.analysis = new BranchedRefVarsAnalysis(graph); final int size = graph.size() * 2 + 1; this.unitToVarsBefore = new HashMap<Unit, List<RefIntPair>>(size, 0.7f); this.unitToVarsAfterFall = new HashMap<Unit, List<RefIntPair>>(size, 0.7f); this.unitToListsOfVarsAfterBranches = new HashMap<Unit, List<List<RefIntPair>>>(size, 0.7f); this.unitToVarsNeedCheck = new HashMap<Unit, List<Object>>(size, 0.7f); this.unitToVarsDontNeedCheck = new HashMap<Unit, List<RefIntPair>>(size, 0.7f); // end while for (Unit s : graph) { unitToVarsAfterFall.put(s, Collections.unmodifiableList(buildList(analysis.getFallFlowAfter(s)))); // we get a list of flow sets for branches, iterate over them { List<FlowSet<RefIntPair>> branchesFlowsets = analysis.getBranchFlowAfter(s); List<List<RefIntPair>> lst = new ArrayList<List<RefIntPair>>(branchesFlowsets.size()); for (FlowSet<RefIntPair> set : branchesFlowsets) { lst.add(Collections.unmodifiableList(buildList(set))); } unitToListsOfVarsAfterBranches.put(s, lst); } // done with branches final FlowSet<RefIntPair> set = analysis.getFlowBefore(s); unitToVarsBefore.put(s, Collections.unmodifiableList(buildList(set))); // NOTE: that set is used in the compute check bellow too if (computeChecks) { ArrayList<RefIntPair> dontNeedCheckVars = new ArrayList<RefIntPair>(); ArrayList<Object> needCheckVars = new ArrayList<Object>(); HashSet<Value> allChecksSet = new HashSet<Value>(5, 0.7f); allChecksSet.addAll(analysis.unitToArrayRefChecksSet.get(s)); allChecksSet.addAll(analysis.unitToInstanceFieldRefChecksSet.get(s)); allChecksSet.addAll(analysis.unitToInstanceInvokeExprChecksSet.get(s)); allChecksSet.addAll(analysis.unitToLengthExprChecksSet.get(s)); // set of all references that are subject to a null pointer check at this statement for (Value v : allChecksSet) { int vInfo = analysis.anyRefInfo(v, set); switch (vInfo) { case BranchedRefVarsAnalysis.kTop: // since it's a check, just print the name of the variable, we know it's top needCheckVars.add(v); break; case BranchedRefVarsAnalysis.kBottom: // this could happen in some rare cases; cf known limitations // in the BranchedRefVarsAnalysis implementation notes needCheckVars.add(analysis.getKRefIntPair(new EquivalentValue(v), vInfo)); break; default: // no check, print the pair (ref, value), so we know why we are not doing the check dontNeedCheckVars.add(analysis.getKRefIntPair(new EquivalentValue(v), vInfo)); break; } } unitToVarsNeedCheck.put(s, Collections.unmodifiableList(needCheckVars)); unitToVarsDontNeedCheck.put(s, Collections.unmodifiableList(dontNeedCheckVars)); } // end if computeChecks } } // end constructor & computations // utility method to build lists of (ref, value) pairs for a given flow set // optionally discard (ref, kTop) pairs. private List<RefIntPair> buildList(FlowSet<RefIntPair> set) {<FILL_FUNCTION_BODY>} // buildList /* * * Accesor methods. * * Public accessor methods to the various class fields containing the results of the computations. * */ public List<RefIntPair> getVarsBefore(Unit s) { return unitToVarsBefore.get(s); } // end getVarsBefore public List<RefIntPair> getVarsAfterFall(Unit s) { return unitToVarsAfterFall.get(s); } // end getVarsAfterFall public List<List<RefIntPair>> getListsOfVarsAfterBranch(Unit s) { return unitToListsOfVarsAfterBranches.get(s); } // end getListsOfVarsAfterBranch public List<Object> getVarsNeedCheck(Unit s) { if (computeChecks) { return unitToVarsNeedCheck.get(s); } else { return new ArrayList<Object>(); } } // end getVarsNeedCheck public List<RefIntPair> getVarsDontNeedCheck(Unit s) { if (computeChecks) { return unitToVarsDontNeedCheck.get(s); } else { return new ArrayList<RefIntPair>(); } } // end getVarsNeedCheck }
List<RefIntPair> lst = new ArrayList<RefIntPair>(); for (EquivalentValue r : analysis.refTypeValues) { int refInfo = analysis.refInfo(r, set); if (!discardKTop || (refInfo != BranchedRefVarsAnalysis.kTop)) { lst.add(analysis.getKRefIntPair(r, refInfo)); // remove tops from the list that will be printed for readability } } return lst;
1,569
126
1,695
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullPointerChecker.java
NullPointerChecker
internalTransform
class NullPointerChecker extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(NullPointerChecker.class); public NullPointerChecker(Singletons.Global g) { } public static NullPointerChecker v() { return G.v().soot_jimple_toolkits_annotation_nullcheck_NullPointerChecker(); } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} }
final boolean isProfiling = PhaseOptions.getBoolean(options, "profiling"); final boolean enableOther = !PhaseOptions.getBoolean(options, "onlyarrayref"); final Date start = new Date(); if (Options.v().verbose()) { logger.debug("[npc] Null pointer check for " + body.getMethod().getName() + " started on " + start); } final BranchedRefVarsAnalysis analysis = new BranchedRefVarsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body)); final SootMethod increase = isProfiling ? Scene.v().loadClassAndSupport("MultiCounter").getMethod("void increase(int)") : null; final Chain<Unit> units = body.getUnits(); for (Iterator<Unit> stmtIt = units.snapshotIterator(); stmtIt.hasNext();) { Stmt s = (Stmt) stmtIt.next(); Value obj = null; if (s.containsArrayRef()) { obj = s.getArrayRef().getBase(); } else if (enableOther) { // Throw if (s instanceof ThrowStmt) { obj = ((ThrowStmt) s).getOp(); } else if (s instanceof MonitorStmt) { // Monitor enter and exit obj = ((MonitorStmt) s).getOp(); } else { for (ValueBox vBox : s.getDefBoxes()) { Value v = vBox.getValue(); // putfield, and getfield if (v instanceof InstanceFieldRef) { obj = ((InstanceFieldRef) v).getBase(); break; } else if (v instanceof InstanceInvokeExpr) { // invokevirtual, invokespecial, invokeinterface obj = ((InstanceInvokeExpr) v).getBase(); break; } else if (v instanceof LengthExpr) { // arraylength obj = ((LengthExpr) v).getOp(); break; } } for (ValueBox vBox : s.getUseBoxes()) { Value v = vBox.getValue(); // putfield, and getfield if (v instanceof InstanceFieldRef) { obj = ((InstanceFieldRef) v).getBase(); break; } else if (v instanceof InstanceInvokeExpr) { // invokevirtual, invokespecial, invokeinterface obj = ((InstanceInvokeExpr) v).getBase(); break; } else if (v instanceof LengthExpr) { // arraylength obj = ((LengthExpr) v).getOp(); break; } } } } // annotate it or now if (obj != null) { boolean needCheck = (analysis.anyRefInfo(obj, analysis.getFlowBefore(s)) != BranchedRefVarsAnalysis.kNonNull); if (isProfiling) { final int count = needCheck ? 5 : 6; final Jimple jimp = Jimple.v(); units.insertBefore(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(increase.makeRef(), IntConstant.v(count))), s); } s.addTag(new NullCheckTag(needCheck)); } } if (Options.v().verbose()) { Date finish = new Date(); long runtime = finish.getTime() - start.getTime(); long mins = runtime / 60000; long secs = (runtime % 60000) / 1000; logger.debug("[npc] Null pointer checker finished. It took " + mins + " mins and " + secs + " secs."); }
139
940
1,079
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullnessAnalysis.java
AnalysisInfo
handleIfStmt
class AnalysisInfo extends java.util.BitSet { private static final long serialVersionUID = -9200043127757823764L; public AnalysisInfo() { super(used); } public AnalysisInfo(AnalysisInfo other) { super(used); or(other); } public int get(Value key) { if (!valueToIndex.containsKey(key)) { return BOTTOM; } int index = valueToIndex.get(key); return (get(index) ? 2 : 0) + (get(index + 1) ? 1 : 0); } public void put(Value key, int val) { int index; if (!valueToIndex.containsKey(key)) { index = used; used += 2; valueToIndex.put(key, index); } else { index = valueToIndex.get(key); } set(index, (val & 2) == 2); set(index + 1, (val & 1) == 1); } } protected final static int BOTTOM = 0; protected final static int NULL = 1; protected final static int NON_NULL = 2; protected final static int TOP = 3; protected final HashMap<Value, Integer> valueToIndex = new HashMap<Value, Integer>(); protected int used = 0; /** * Creates a new analysis for the given graph/ * * @param graph * any unit graph */ public NullnessAnalysis(UnitGraph graph) { super(graph); doAnalysis(); } /** * {@inheritDoc} */ @Override protected void flowThrough(AnalysisInfo in, Unit u, List<AnalysisInfo> fallOut, List<AnalysisInfo> branchOuts) { AnalysisInfo out = new AnalysisInfo(in); AnalysisInfo outBranch = new AnalysisInfo(in); Stmt s = (Stmt) u; // in case of an if statement, we need to compute the branch-flow; // e.g. for a statement "if(x!=null) goto s" we have x==null for the fallOut and // x!=null for the branchOut // or for an instanceof expression if (s instanceof JIfStmt) { handleIfStmt((JIfStmt) s, in, out, outBranch); } else if (s instanceof MonitorStmt) { // in case of a monitor statement, we know that if it succeeds, we have a non-null value out.put(((MonitorStmt) s).getOp(), NON_NULL); } // if we have an array ref, set the base to non-null if (s.containsArrayRef()) { handleArrayRef(s.getArrayRef(), out); } // for field refs, set the receiver object to non-null, if there is one if (s.containsFieldRef()) { handleFieldRef(s.getFieldRef(), out); } // for invoke expr, set the receiver object to non-null, if there is one if (s.containsInvokeExpr()) { handleInvokeExpr(s.getInvokeExpr(), out); } // if we have a definition (assignment) statement to a ref-like type, handle it, // i.e. assign it TOP, except in the following special cases: // x=null, assign NULL // x=@this or x= new... assign NON_NULL // x=y, copy the info for y (for locals x,y) if (s instanceof DefinitionStmt) { DefinitionStmt defStmt = (DefinitionStmt) s; if (defStmt.getLeftOp().getType() instanceof RefLikeType) { handleRefTypeAssignment(defStmt, out); } } // now copy the computed info to all successors for (AnalysisInfo next : fallOut) { copy(out, next); } for (AnalysisInfo next : branchOuts) { copy(outBranch, next); } } /** * This can be overwritten by subclasses to mark a certain value as constantly non-null. * * @param v * any value * @return true if it is known that this value (e.g. a method return value) is never null */ protected boolean isAlwaysNonNull(Value v) { return false; } private void handleIfStmt(JIfStmt ifStmt, AnalysisInfo in, AnalysisInfo out, AnalysisInfo outBranch) {<FILL_FUNCTION_BODY>
Value condition = ifStmt.getCondition(); if (condition instanceof JInstanceOfExpr) { // a instanceof X ; if this succeeds, a is not null handleInstanceOfExpression((JInstanceOfExpr) condition, in, out, outBranch); } else if (condition instanceof JEqExpr || condition instanceof JNeExpr) { // a==b or a!=b handleEqualityOrNonEqualityCheck((AbstractBinopExpr) condition, in, out, outBranch); }
1,185
125
1,310
<methods>public void <init>(soot.toolkits.graph.UnitGraph) <variables>private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/nullcheck/RefIntPair.java
RefIntPair
toString
class RefIntPair { private final EquivalentValue _ref; private final int _val; // constructor is not public so that people go throught the ref pair constants factory on the analysis RefIntPair(EquivalentValue r, int v, BranchedRefVarsAnalysis brva) { this._ref = r; this._val = v; } public EquivalentValue ref() { return this._ref; } public int val() { return this._val; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
String prefix = "(" + _ref + ", "; switch (_val) { case BranchedRefVarsAnalysis.kNull: return prefix + "null)"; case BranchedRefVarsAnalysis.kNonNull: return prefix + "non-null)"; case BranchedRefVarsAnalysis.kTop: return prefix + "top)"; case BranchedRefVarsAnalysis.kBottom: return prefix + "bottom)"; default: return prefix + _val + ")"; }
156
135
291
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/parity/ParityTagger.java
ParityTagger
internalTransform
class ParityTagger extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(ParityTagger.class); public ParityTagger(Singletons.Global g) { } public static ParityTagger v() { return G.v().soot_jimple_toolkits_annotation_parity_ParityTagger(); } protected void internalTransform(Body b, String phaseName, Map options) {<FILL_FUNCTION_BODY>} private void addColorTag(ValueBox vb, String type) { if (type.equals("bottom")) { // green vb.addTag(new ColorTag(ColorTag.GREEN, "Parity Analysis")); } else if (type.equals("top")) { // red vb.addTag(new ColorTag(ColorTag.RED, "Parity Analysis")); } else if (type.equals("even")) { // yellow vb.addTag(new ColorTag(ColorTag.YELLOW, "Parity Analysis")); } else if (type.equals("odd")) { // blue vb.addTag(new ColorTag(ColorTag.BLUE, "Parity Analysis")); } } }
// System.out.println("parity tagger for method: "+b.getMethod().getName()); boolean isInteractive = Options.v().interactive_mode(); Options.v().set_interactive_mode(false); ParityAnalysis a; if (isInteractive) { LiveLocals sll = new SimpleLiveLocals(new BriefUnitGraph(b)); Options.v().set_interactive_mode(isInteractive); a = new ParityAnalysis(new BriefUnitGraph(b), sll); } else { a = new ParityAnalysis(new BriefUnitGraph(b)); } Iterator sIt = b.getUnits().iterator(); while (sIt.hasNext()) { Stmt s = (Stmt) sIt.next(); HashMap parityVars = (HashMap) a.getFlowAfter(s); Iterator it = parityVars.keySet().iterator(); while (it.hasNext()) { final Value variable = (Value) it.next(); if ((variable instanceof IntConstant) || (variable instanceof LongConstant)) { // don't add string tags (just color tags) } else { StringTag t = new StringTag("Parity variable: " + variable + " " + parityVars.get(variable), "Parity Analysis"); s.addTag(t); } } HashMap parityVarsUses = (HashMap) a.getFlowBefore(s); HashMap parityVarsDefs = (HashMap) a.getFlowAfter(s); // uses Iterator valBoxIt = s.getUseBoxes().iterator(); while (valBoxIt.hasNext()) { ValueBox vb = (ValueBox) valBoxIt.next(); if (parityVarsUses.containsKey(vb.getValue())) { // logger.debug("Parity variable for: "+vb.getValue()); String type = (String) parityVarsUses.get(vb.getValue()); addColorTag(vb, type); } } // defs valBoxIt = s.getDefBoxes().iterator(); while (valBoxIt.hasNext()) { ValueBox vb = (ValueBox) valBoxIt.next(); if (parityVarsDefs.containsKey(vb.getValue())) { // logger.debug("Parity variable for: "+vb.getValue()); String type = (String) parityVarsDefs.get(vb.getValue()); addColorTag(vb, type); } } } // add key to class Iterator keyIt = b.getMethod().getDeclaringClass().getTags().iterator(); boolean keysAdded = false; while (keyIt.hasNext()) { Object next = keyIt.next(); if (next instanceof KeyTag) { if (((KeyTag) next).analysisType().equals("Parity Analysis")) { keysAdded = true; } } } if (!keysAdded) { b.getMethod().getDeclaringClass().addTag(new KeyTag(255, 0, 0, "Parity: Top", "Parity Analysis")); b.getMethod().getDeclaringClass().addTag(new KeyTag(45, 255, 84, "Parity: Bottom", "Parity Analysis")); b.getMethod().getDeclaringClass().addTag(new KeyTag(255, 248, 35, "Parity: Even", "Parity Analysis")); b.getMethod().getDeclaringClass().addTag(new KeyTag(174, 210, 255, "Parity: Odd", "Parity Analysis")); }
314
952
1,266
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/profiling/ProfilingGenerator.java
ProfilingGenerator
internalTransform
class ProfilingGenerator extends BodyTransformer { public ProfilingGenerator(Singletons.Global g) { } public static ProfilingGenerator v() { return G.v().soot_jimple_toolkits_annotation_profiling_ProfilingGenerator(); } public String mainSignature = Options.v().src_prec() != Options.src_prec_dotnet ? "void main(java.lang.String[])" : DotnetMethod.MAIN_METHOD_SIGNATURE; // private String mainSignature = "long runBenchmark(java.lang.String[])"; protected void internalTransform(Body body, String phaseName, Map opts) {<FILL_FUNCTION_BODY>} }
ProfilingOptions options = new ProfilingOptions(opts); if (options.notmainentry()) { mainSignature = "long runBenchmark(java.lang.String[])"; } { SootMethod m = body.getMethod(); SootClass counterClass = Scene.v().loadClassAndSupport("MultiCounter"); SootMethod reset = counterClass.getMethod("void reset()"); SootMethod report = counterClass.getMethod("void report()"); boolean isMainMethod = m.getSubSignature().equals(mainSignature); Chain units = body.getUnits(); if (isMainMethod) { units.addFirst(Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(reset.makeRef()))); } Iterator stmtIt = body.getUnits().snapshotIterator(); while (stmtIt.hasNext()) { Stmt stmt = (Stmt) stmtIt.next(); if (stmt instanceof InvokeStmt) { InvokeExpr iexpr = ((InvokeStmt) stmt).getInvokeExpr(); if (iexpr instanceof StaticInvokeExpr) { SootMethod tempm = ((StaticInvokeExpr) iexpr).getMethod(); if (tempm.getSignature().equals("<java.lang.System: void exit(int)>")) { units.insertBefore(Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(report.makeRef())), stmt); } } } else if (isMainMethod && (stmt instanceof ReturnStmt || stmt instanceof ReturnVoidStmt)) { units.insertBefore(Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr(report.makeRef())), stmt); } } }
186
477
663
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityAnalysis.java
PurityAnalysis
internalTransform
class PurityAnalysis extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(PurityAnalysis.class); public PurityAnalysis(Singletons.Global g) { } public static PurityAnalysis v() { return G.v().soot_jimple_toolkits_annotation_purity_PurityAnalysis(); } @Override protected void internalTransform(String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} }
PurityOptions opts = new PurityOptions(options); logger.debug("[AM] Analysing purity"); final Scene sc = Scene.v(); // launch the analysis new PurityInterproceduralAnalysis(sc.getCallGraph(), sc.getEntryPoints().iterator(), opts);
132
80
212
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityGraphBox.java
PurityGraphBox
equals
class PurityGraphBox { public PurityGraph g; PurityGraphBox() { this.g = new PurityGraph(); } @Override public int hashCode() { return g.hashCode(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} }
if (o instanceof PurityGraphBox) { PurityGraphBox oo = (PurityGraphBox) o; return this.g.equals(oo.g); } else { return false; }
92
58
150
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityInterproceduralAnalysis.java
Filter
summaryOfUnanalysedMethod
class Filter implements SootMethodFilter { @Override public boolean want(SootMethod method) { // could be optimized with HashSet.... String c = method.getDeclaringClass().toString(); String m = method.getName(); for (String[] element : PurityInterproceduralAnalysis.pureMethods) { if (m.equals(element[1]) && c.startsWith(element[0])) { return false; } } for (String[] element : PurityInterproceduralAnalysis.impureMethods) { if (m.equals(element[1]) && c.startsWith(element[0])) { return false; } } for (String[] element : PurityInterproceduralAnalysis.alterMethods) { if (m.equals(element[1]) && c.startsWith(element[0])) { return false; } } return true; } } /** * The constructor does it all! */ PurityInterproceduralAnalysis(CallGraph cg, Iterator<SootMethod> heads, PurityOptions opts) { super(cg, new Filter(), heads, opts.dump_cg()); if (opts.dump_cg()) { logger.debug("[AM] Dumping empty .dot call-graph"); drawAsOneDot("EmptyCallGraph"); } { Date start = new Date(); logger.debug("[AM] Analysis began"); doAnalysis(opts.verbose()); logger.debug("[AM] Analysis finished"); Date finish = new Date(); long runtime = finish.getTime() - start.getTime(); logger.debug("[AM] run time: " + runtime / 1000. + " s"); } if (opts.dump_cg()) { logger.debug("[AM] Dumping annotated .dot call-graph"); drawAsOneDot("CallGraph"); } if (opts.dump_summaries()) { logger.debug("[AM] Dumping .dot summaries of analysed methods"); drawAsManyDot("Summary_", false); } if (opts.dump_intra()) { logger.debug("[AM] Dumping .dot full intra-procedural method analyses"); // relaunch the interprocedural analysis once on each method // to get a purity graph at each statement, not only summaries for (Iterator<SootMethod> it = getAnalysedMethods(); it.hasNext();) { SootMethod method = it.next(); if (opts.verbose()) { logger.debug(" |- " + method); } ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(method.retrieveActiveBody()); PurityIntraproceduralAnalysis r = new PurityIntraproceduralAnalysis(graph, this); r.drawAsOneDot("Intra_", method.toString()); r.copyResult(new PurityGraphBox()); } } { logger.debug("[AM] Annotate methods. "); for (Iterator<SootMethod> it = getAnalysedMethods(); it.hasNext();) { SootMethod m = it.next(); PurityGraphBox b = getSummaryFor(m); // purity boolean isPure = m.toString().contains("<init>") ? b.g.isPureConstructor() : b.g.isPure(); /* * m.addTag(new GenericAttribute("isPure", (new String(isPure?"yes":"no")).getBytes())); */ m.addTag(new StringTag("purity: " + (isPure ? "pure" : "impure"))); if (isPure && opts.annotate()) { m.addTag(new GenericAttribute("Pure", new byte[0])); } if (opts.print()) { logger.debug(" |- method " + m.toString() + " is " + (isPure ? "pure" : "impure")); } // param & this ro / safety if (!m.isStatic()) { String s; switch (b.g.thisStatus()) { case PurityGraph.PARAM_RW: s = "read/write"; break; case PurityGraph.PARAM_RO: s = "read-only"; break; case PurityGraph.PARAM_SAFE: s = "Safe"; break; default: s = "unknown"; } /* * m.addTag(new GenericAttribute("thisStatus",s.getBytes())); */ m.addTag(new StringTag("this: " + s)); if (opts.print()) { logger.debug(" | |- this is " + s); } } int i = 0; for (Type t : m.getParameterTypes()) { if (t instanceof RefLikeType) { String s; switch (b.g.paramStatus(i)) { case PurityGraph.PARAM_RW: s = "read/write"; break; case PurityGraph.PARAM_RO: s = "read-only"; break; case PurityGraph.PARAM_SAFE: s = "safe"; break; default: s = "unknown"; } /* * m.addTag(new GenericAttribute("param"+i+"Status", s.getBytes())); */ m.addTag(new StringTag("param" + i + ": " + s)); if (opts.print()) { logger.debug(" | |- param " + i + " is " + s); } } i++; } } } } @Override protected PurityGraphBox newInitialSummary() { return new PurityGraphBox(); } @Override protected void merge(PurityGraphBox in1, PurityGraphBox in2, PurityGraphBox out) { if (out != in1) { out.g = new PurityGraph(in1.g); } out.g.union(in2.g); } @Override protected void copy(PurityGraphBox source, PurityGraphBox dest) { dest.g = new PurityGraph(source.g); } @Override protected void analyseMethod(SootMethod method, PurityGraphBox dst) { new PurityIntraproceduralAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(method.retrieveActiveBody()), this).copyResult(dst); } /** * @return * * @see PurityGraph.conservativeGraph * @see PurityGraph.freshGraph */ @Override protected PurityGraphBox summaryOfUnanalysedMethod(SootMethod method) {<FILL_FUNCTION_BODY>
PurityGraphBox b = new PurityGraphBox(); String c = method.getDeclaringClass().toString(); String m = method.getName(); // impure with side-effect, unless otherwise specified b.g = PurityGraph.conservativeGraph(method, true); for (String[] element : PurityInterproceduralAnalysis.pureMethods) { if (m.equals(element[1]) && c.startsWith(element[0])) { b.g = PurityGraph.freshGraph(method); } } for (String[] element : PurityInterproceduralAnalysis.alterMethods) { if (m.equals(element[1]) && c.startsWith(element[0])) { b.g = PurityGraph.conservativeGraph(method, false); } } return b;
1,767
216
1,983
<methods>public void <init>(soot.jimple.toolkits.callgraph.CallGraph, soot.jimple.toolkits.annotation.purity.SootMethodFilter, Iterator<soot.SootMethod>, boolean) ,public void analyseCall(soot.jimple.toolkits.annotation.purity.PurityGraphBox, soot.jimple.Stmt, soot.jimple.toolkits.annotation.purity.PurityGraphBox) ,public void drawAsManyDot(java.lang.String, boolean) ,public void drawAsOneDot(java.lang.String) ,public Iterator<soot.SootMethod> getAnalysedMethods() ,public soot.jimple.toolkits.annotation.purity.PurityGraphBox getSummaryFor(soot.SootMethod) <variables>protected final non-sealed soot.jimple.toolkits.callgraph.CallGraph cg,protected final non-sealed Map<soot.SootMethod,soot.jimple.toolkits.annotation.purity.PurityGraphBox> data,protected final non-sealed DirectedGraph<soot.SootMethod> dg,public static final boolean doCheck,private static final org.slf4j.Logger logger,protected final non-sealed Map<soot.SootMethod,java.lang.Integer> order,protected final non-sealed Map<soot.SootMethod,soot.jimple.toolkits.annotation.purity.PurityGraphBox> unanalysed
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityMethodNode.java
PurityMethodNode
equals
class PurityMethodNode implements PurityNode { /** gives a unique id, for pretty-printing purposes */ private static final Map<SootMethod, Integer> nMap = new HashMap<SootMethod, Integer>(); private static int n = 0; /** Method that created the node */ private SootMethod id; PurityMethodNode(SootMethod id) { this.id = id; if (!nMap.containsKey(id)) { nMap.put(id, n); n++; } } @Override public String toString() { return "M_" + nMap.get(id); } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public boolean isInside() { return true; } @Override public boolean isLoad() { return false; } @Override public boolean isParam() { return false; } }
if (o instanceof PurityMethodNode) { PurityMethodNode oo = (PurityMethodNode) o; return this.id.equals(oo.id); } else { return false; }
285
58
343
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityParamNode.java
PurityParamNode
equals
class PurityParamNode implements PurityNode { private final int id; PurityParamNode(int id) { this.id = id; } @Override public String toString() { return "P_" + id; } @Override public int hashCode() { return id; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public boolean isInside() { return false; } @Override public boolean isLoad() { return false; } @Override public boolean isParam() { return true; } }
if (o instanceof PurityParamNode) { return this.id == ((PurityParamNode) o).id; } else { return false; }
181
45
226
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/purity/PurityStmtNode.java
PurityStmtNode
equals
class PurityStmtNode implements PurityNode { /** gives a unique id, for pretty-printing purposes */ private static final Map<Stmt, Integer> nMap = new HashMap<Stmt, Integer>(); private static int n = 0; /** Statement that created the node */ private final Stmt id; /** true if an inside node, false if an load node */ private final boolean inside; PurityStmtNode(Stmt id, boolean inside) { this.id = id; this.inside = inside; if (!nMap.containsKey(id)) { nMap.put(id, n); n++; } } @Override public String toString() { return inside ? ("I_" + nMap.get(id)) : ("L_" + nMap.get(id)); } @Override public int hashCode() { return id.hashCode(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public boolean isInside() { return inside; } @Override public boolean isLoad() { return !inside; } @Override public boolean isParam() { return false; } }
if (o instanceof PurityStmtNode) { PurityStmtNode oo = (PurityStmtNode) o; return this.id.equals(oo.id) && this.inside == oo.inside; } else { return false; }
336
73
409
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/tags/ArrayNullTagAggregator.java
ArrayNullTagAggregator
considerTag
class ArrayNullTagAggregator extends TagAggregator { public ArrayNullTagAggregator(Singletons.Global g) { } public static ArrayNullTagAggregator v() { return G.v().soot_jimple_toolkits_annotation_tags_ArrayNullTagAggregator(); } public boolean wantTag(Tag t) { return (t instanceof OneByteCodeTag); } @Override public void considerTag(Tag t, Unit u, LinkedList<Tag> tags, LinkedList<Unit> units) {<FILL_FUNCTION_BODY>} public String aggregatedName() { return "ArrayNullCheckAttribute"; } }
Inst i = (Inst) u; if (!(i.containsInvokeExpr() || i.containsFieldRef() || i.containsArrayRef())) { return; } OneByteCodeTag obct = (OneByteCodeTag) t; if (units.size() == 0 || units.getLast() != u) { units.add(u); tags.add(new ArrayNullCheckTag()); } ArrayNullCheckTag anct = (ArrayNullCheckTag) tags.getLast(); anct.accumulate(obct.getValue()[0]);
171
148
319
<methods>public non-sealed void <init>() ,public abstract java.lang.String aggregatedName() ,public abstract void considerTag(soot.tagkit.Tag, soot.Unit, LinkedList<soot.tagkit.Tag>, LinkedList<soot.Unit>) ,public void fini() ,public abstract boolean wantTag(soot.tagkit.Tag) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/annotation/tags/NullCheckTag.java
NullCheckTag
toString
class NullCheckTag implements OneByteCodeTag { public static final String NAME = "NullCheckTag"; private final byte value; public NullCheckTag(boolean needCheck) { if (needCheck) { this.value = 0x04; } else { this.value = 0; } } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[] { value }; } public boolean needCheck() { return (value != 0); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return (value == 0) ? "[not null]" : "[unknown]";
179
21
200
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/base/RenameDuplicatedClasses.java
RenameDuplicatedClasses
internalTransform
class RenameDuplicatedClasses extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(RenameDuplicatedClasses.class); private static final String FIXED_CLASS_NAME_SPERATOR = "-"; public RenameDuplicatedClasses(Singletons.Global g) { } public static RenameDuplicatedClasses v() { return G.v().soot_jimple_toolkits_base_RenameDuplicatedClasses(); } @Override protected void internalTransform(String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} public void duplicatedCheck(Iterable<String> classNames) { Set<String> classNameSet = new HashSet<String>(); for (String className : classNames) { if (classNameSet.contains(className.toLowerCase())) { throw new RuntimeException("The fixed class names cannot contain duplicated class names."); } else { classNameSet.add(className.toLowerCase()); } } } /** * An naive approach to check whether the file system is case sensitive or not * * @return */ public boolean isFileSystemCaseSensitive() { File[] allFiles = (new File(".")).listFiles(); if (allFiles != null) { for (File f : allFiles) { if (f.isFile()) { if (!(new File(f.getAbsolutePath().toLowerCase())).exists() || !(new File(f.getAbsolutePath().toUpperCase())).exists()) { return true; } } } } return false; } }
// If the file system is case sensitive, no need to rename the classes if (isFileSystemCaseSensitive()) { return; } final Set<String> fixedClassNames = new HashSet<>(Arrays.asList(PhaseOptions.getString(options, "fixedClassNames").split(FIXED_CLASS_NAME_SPERATOR))); duplicatedCheck(fixedClassNames); if (Options.v().verbose()) { logger.debug("The fixed class names are: " + fixedClassNames); } int count = 0; Map<String, String> lowerCaseClassNameToReal = new HashMap<String, String>(); for (Iterator<SootClass> iter = Scene.v().getClasses().snapshotIterator(); iter.hasNext();) { SootClass sootClass = iter.next(); String className = sootClass.getName(); if (lowerCaseClassNameToReal.containsKey(className.toLowerCase())) { if (fixedClassNames.contains(className)) { sootClass = Scene.v().getSootClass(lowerCaseClassNameToReal.get(className.toLowerCase())); className = lowerCaseClassNameToReal.get(className.toLowerCase()); } String newClassName = className + (count++); sootClass.rename(newClassName); // if(Options.v().verbose()) // { logger.debug("Rename duplicated class " + className + " to class " + newClassName); // } } else { lowerCaseClassNameToReal.put(className.toLowerCase(), className); } }
435
412
847
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/base/ThisInliner.java
ThisInliner
internalTransform
class ThisInliner extends BodyTransformer { private static final boolean DEBUG = false; @Override public void internalTransform(Body b, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} private InvokeStmt getFirstSpecialInvoke(Body b) { for (Unit u : b.getUnits()) { if (u instanceof InvokeStmt) { InvokeStmt s = (InvokeStmt) u; if (s.getInvokeExpr() instanceof SpecialInvokeExpr) { return s; } } } // but there will always be either a call to this() or to super() from the constructor return null; } private IdentityStmt findIdentityStmt(Body b) { for (Unit u : b.getUnits()) { if (u instanceof IdentityStmt) { IdentityStmt s = (IdentityStmt) u; if (s.getRightOp() instanceof ThisRef) { return s; } } } return null; } }
assert (b instanceof JimpleBody || b instanceof ShimpleBody); // Ensure body is a constructor if (!"<init>".equals(b.getMethod().getName())) { return; } // If the first invoke is a this() and not a super() inline the this() final InvokeStmt invokeStmt = getFirstSpecialInvoke(b); if (invokeStmt == null) { return; } final SpecialInvokeExpr specInvokeExpr = (SpecialInvokeExpr) invokeStmt.getInvokeExpr(); final SootMethod specInvokeMethod = specInvokeExpr.getMethod(); if (specInvokeMethod.getDeclaringClass().equals(b.getMethod().getDeclaringClass())) { // Get or construct the body for the method final Body specInvokeBody = specInvokeMethod.retrieveActiveBody(); assert (b.getClass() == specInvokeBody.getClass()); // Put locals from inlinee into container HashMap<Local, Local> oldLocalsToNew = new HashMap<Local, Local>(); for (Local l : specInvokeBody.getLocals()) { Local newLocal = (Local) l.clone(); b.getLocals().add(newLocal); oldLocalsToNew.put(l, newLocal); } if (DEBUG) { System.out.println("locals: " + b.getLocals()); } // Find @this identity stmt of original method final Value origIdStmtLHS = findIdentityStmt(b).getLeftOp(); final HashMap<Unit, Unit> oldStmtsToNew = new HashMap<Unit, Unit>(); final Chain<Unit> containerUnits = b.getUnits(); for (Unit u : specInvokeBody.getUnits()) { Stmt inlineeStmt = (Stmt) u; if (inlineeStmt instanceof IdentityStmt) { // Handle identity stmts final IdentityStmt idStmt = (IdentityStmt) inlineeStmt; final Value rightOp = idStmt.getRightOp(); if (rightOp instanceof ThisRef) { Stmt newThis = Jimple.v().newAssignStmt(oldLocalsToNew.get((Local) idStmt.getLeftOp()), origIdStmtLHS); containerUnits.insertBefore(newThis, invokeStmt); oldStmtsToNew.put(inlineeStmt, newThis); } else if (rightOp instanceof CaughtExceptionRef) { Stmt newInlinee = (Stmt) inlineeStmt.clone(); for (ValueBox vb : newInlinee.getUseAndDefBoxes()) { Value val = vb.getValue(); if (val instanceof Local) { vb.setValue(oldLocalsToNew.get((Local) val)); } } containerUnits.insertBefore(newInlinee, invokeStmt); oldStmtsToNew.put(inlineeStmt, newInlinee); } else if (rightOp instanceof ParameterRef) { Stmt newParam = Jimple.v().newAssignStmt(oldLocalsToNew.get((Local) idStmt.getLeftOp()), specInvokeExpr.getArg(((ParameterRef) rightOp).getIndex())); containerUnits.insertBefore(newParam, invokeStmt); oldStmtsToNew.put(inlineeStmt, newParam); } } else if (inlineeStmt instanceof ReturnVoidStmt) { // Handle return void stmts (cannot return anything else from a constructor) Stmt newRet = Jimple.v().newGotoStmt(containerUnits.getSuccOf(invokeStmt)); containerUnits.insertBefore(newRet, invokeStmt); if (DEBUG) { System.out.println("adding to stmt map: " + inlineeStmt + " and " + newRet); } oldStmtsToNew.put(inlineeStmt, newRet); } else { Stmt newInlinee = (Stmt) inlineeStmt.clone(); for (ValueBox vb : newInlinee.getUseAndDefBoxes()) { Value val = vb.getValue(); if (val instanceof Local) { vb.setValue(oldLocalsToNew.get((Local) val)); } } containerUnits.insertBefore(newInlinee, invokeStmt); oldStmtsToNew.put(inlineeStmt, newInlinee); } } // handleTraps for (Trap t : specInvokeBody.getTraps()) { Unit newBegin = oldStmtsToNew.get(t.getBeginUnit()); Unit newEnd = oldStmtsToNew.get(t.getEndUnit()); Unit newHandler = oldStmtsToNew.get(t.getHandlerUnit()); if (DEBUG) { System.out.println("begin: " + t.getBeginUnit()); System.out.println("end: " + t.getEndUnit()); System.out.println("handler: " + t.getHandlerUnit()); } if (newBegin == null || newEnd == null || newHandler == null) { throw new RuntimeException("couldn't map trap!"); } b.getTraps().add(Jimple.v().newTrap(t.getException(), newBegin, newEnd, newHandler)); } // patch gotos for (Unit u : specInvokeBody.getUnits()) { if (u instanceof GotoStmt) { GotoStmt inlineeStmt = (GotoStmt) u; if (DEBUG) { System.out.println("inlinee goto target: " + inlineeStmt.getTarget()); } ((GotoStmt) oldStmtsToNew.get(inlineeStmt)).setTarget(oldStmtsToNew.get(inlineeStmt.getTarget())); } } // remove original invoke containerUnits.remove(invokeStmt); // resolve name collisions LocalNameStandardizer.v().transform(b, "ji.lns"); } if (DEBUG) { System.out.println("locals: " + b.getLocals()); System.out.println("units: " + b.getUnits()); }
280
1,611
1,891
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/base/Zonation.java
Zonation
getZoneOf
class Zonation { private final Map<Unit, Zone> unitToZone; private int zoneCount; public Zonation(StmtBody body) { final Chain<Unit> units = body.getUnits(); this.zoneCount = 0; this.unitToZone = new HashMap<Unit, Zone>(units.size() * 2 + 1, 0.7f); // Build trap boundaries Map<Unit, List<Trap>> unitToTrapBoundaries = new HashMap<Unit, List<Trap>>(); for (Trap t : body.getTraps()) { addTrapBoundary(t.getBeginUnit(), t, unitToTrapBoundaries); addTrapBoundary(t.getEndUnit(), t, unitToTrapBoundaries); } // Traverse units, assigning each to a zone Map<List<Trap>, Zone> trapListToZone = new HashMap<List<Trap>, Zone>(10, 0.7f); List<Trap> currentTraps = new ArrayList<Trap>(); // Initialize first empty zone Zone currentZone = new Zone("0"); trapListToZone.put(new ArrayList<Trap>(), currentZone); for (Unit u : units) { // Process trap boundaries { List<Trap> trapBoundaries = unitToTrapBoundaries.get(u); if (trapBoundaries != null && !trapBoundaries.isEmpty()) { for (Trap trap : trapBoundaries) { if (currentTraps.contains(trap)) { currentTraps.remove(trap); } else { currentTraps.add(trap); } } if (trapListToZone.containsKey(currentTraps)) { currentZone = trapListToZone.get(currentTraps); } else { // Create a new zone zoneCount++; currentZone = new Zone(Integer.toString(zoneCount)); trapListToZone.put(currentTraps, currentZone); } } } unitToZone.put(u, currentZone); } } private void addTrapBoundary(Unit unit, Trap t, Map<Unit, List<Trap>> unitToTrapBoundaries) { List<Trap> boundary = unitToTrapBoundaries.get(unit); if (boundary == null) { boundary = new ArrayList<Trap>(); unitToTrapBoundaries.put(unit, boundary); } boundary.add(t); } public Zone getZoneOf(Unit u) {<FILL_FUNCTION_BODY>} public int getZoneCount() { return zoneCount; } }
Zone z = unitToZone.get(u); if (z == null) { throw new RuntimeException("null zone!"); } else { return z; }
707
49
756
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/CHATransformer.java
CHATransformer
internalTransform
class CHATransformer extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(CHATransformer.class); public CHATransformer(Singletons.Global g) { } public static CHATransformer v() { return G.v().soot_jimple_toolkits_callgraph_CHATransformer(); } @Override protected void internalTransform(String phaseName, Map<String, String> opts) {<FILL_FUNCTION_BODY>} }
CHAOptions options = new CHAOptions(opts); CallGraphBuilder cg = options.apponly() ? new CallGraphBuilder() : new CallGraphBuilder(DumbPointerAnalysis.v()); cg.build(); if (options.verbose()) { logger.debug("Number of reachable methods: " + Scene.v().getReachableMethods().size()); }
135
96
231
<methods>public non-sealed void <init>() ,public final void transform(java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(java.lang.String) ,public final void transform() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/CallGraphBuilder.java
CallGraphBuilder
processArrays
class CallGraphBuilder { private static final Logger logger = LoggerFactory.getLogger(CallGraphBuilder.class); private final PointsToAnalysis pa; private final ReachableMethods reachables; private final OnFlyCallGraphBuilder ofcgb; private final CallGraph cg; /** * This constructor builds the incomplete hack call graph for the Dava ThrowFinder. It uses all application class methods * as entry points, and it ignores any calls by non-application class methods. Don't use this constructor if you need a * real call graph. */ public CallGraphBuilder() { logger.warn("using incomplete callgraph containing " + "only application classes."); this.pa = soot.jimple.toolkits.pointer.DumbPointerAnalysis.v(); this.cg = Scene.v().internalMakeCallGraph(); Scene.v().setCallGraph(cg); List<MethodOrMethodContext> entryPoints = new ArrayList<MethodOrMethodContext>(); entryPoints.addAll(EntryPoints.v().methodsOfApplicationClasses()); entryPoints.addAll(EntryPoints.v().implicit()); this.reachables = new ReachableMethods(cg, entryPoints); this.ofcgb = new OnFlyCallGraphBuilder(new ContextInsensitiveContextManager(cg), reachables, true); } /** * This constructor builds a complete call graph using the given PointsToAnalysis to resolve virtual calls. */ public CallGraphBuilder(PointsToAnalysis pa) { this.pa = pa; this.cg = Scene.v().internalMakeCallGraph(); Scene.v().setCallGraph(cg); this.reachables = Scene.v().getReachableMethods(); this.ofcgb = createCGBuilder(makeContextManager(cg), reachables); } protected OnFlyCallGraphBuilder createCGBuilder(ContextManager cm, ReachableMethods reachables2) { return new OnFlyCallGraphBuilder(cm, reachables); } public CallGraph getCallGraph() { return cg; } public ReachableMethods reachables() { return reachables; } public static ContextManager makeContextManager(CallGraph cg) { return new ContextInsensitiveContextManager(cg); } public void build() { for (QueueReader<MethodOrMethodContext> worklist = reachables.listener();;) { ofcgb.processReachables(); reachables.update(); if (!worklist.hasNext()) { break; } final MethodOrMethodContext momc = worklist.next(); if (momc != null && !process(momc)) { break; } } } /** * Processes one item. * * @param momc * the method or method context * @return true if the next item should be processed. */ protected boolean process(MethodOrMethodContext momc) { processReceivers(momc); processBases(momc); processArrays(momc); processStringConstants(momc); return true; } protected void processStringConstants(final MethodOrMethodContext momc) { List<Local> stringConstants = ofcgb.methodToStringConstants().get(momc.method()); if (stringConstants != null) { for (Local stringConstant : stringConstants) { Collection<String> possibleStringConstants = pa.reachingObjects(stringConstant).possibleStringConstants(); if (possibleStringConstants == null) { ofcgb.addStringConstant(stringConstant, momc.context(), null); } else { for (String constant : possibleStringConstants) { ofcgb.addStringConstant(stringConstant, momc.context(), constant); } } } } } protected void processArrays(final MethodOrMethodContext momc) {<FILL_FUNCTION_BODY>} protected void processBases(final MethodOrMethodContext momc) { List<Local> bases = ofcgb.methodToInvokeArgs().get(momc.method()); if (bases != null) { for (Local base : bases) { for (Type ty : pa.reachingObjects(base).possibleTypes()) { ofcgb.addBaseType(base, momc.context(), ty); } } } } protected void processReceivers(final MethodOrMethodContext momc) { List<Local> receivers = ofcgb.methodToReceivers().get(momc.method()); if (receivers != null) { for (Local receiver : receivers) { for (Type type : pa.reachingObjects(receiver).possibleTypes()) { ofcgb.addType(receiver, momc.context(), type, null); } } } } }
List<Local> argArrays = ofcgb.methodToInvokeBases().get(momc.method()); if (argArrays != null) { for (final Local argArray : argArrays) { PointsToSet pts = pa.reachingObjects(argArray); if (pts instanceof PointsToSetInternal) { PointsToSetInternal ptsi = (PointsToSetInternal) pts; ptsi.forall(new P2SetVisitor() { @Override public void visit(Node n) { assert (n instanceof AllocNode); AllocNode an = (AllocNode) n; Object newExpr = an.getNewExpr(); ofcgb.addInvokeArgDotField(argArray, an.dot(ArrayElement.v())); if (newExpr instanceof NewArrayExpr) { NewArrayExpr nae = (NewArrayExpr) newExpr; Value size = nae.getSize(); if (size instanceof IntConstant) { IntConstant arrSize = (IntConstant) size; ofcgb.addPossibleArgArraySize(argArray, arrSize.value, momc.context()); } else { ofcgb.setArgArrayNonDetSize(argArray, momc.context()); } } } }); } for (Type t : pa.reachingObjectsOfArrayElement(pts).possibleTypes()) { ofcgb.addInvokeArgType(argArray, momc.context(), t); } } }
1,245
384
1,629
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/ClinitElimAnalysis.java
ClinitElimAnalysis
calculateInitialFlow
class ClinitElimAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<SootMethod>> { private final CallGraph cg = Scene.v().getCallGraph(); private final UnitGraph g; private static FlowSet<SootMethod> cachedFlowSet = null; public ClinitElimAnalysis(UnitGraph g) { super(g); this.g = g; doAnalysis(); } @Override public void merge(FlowSet<SootMethod> in1, FlowSet<SootMethod> in2, FlowSet<SootMethod> out) { in1.intersection(in2, out); } @Override public void copy(FlowSet<SootMethod> src, FlowSet<SootMethod> dest) { src.copy(dest); } @Override protected void copyFreshToExisting(FlowSet<SootMethod> in, FlowSet<SootMethod> dest) { in.copyFreshToExisting(dest); } // out(s) = in(s) intersect { target methods of s where edge kind is clinit} @Override protected void flowThrough(FlowSet<SootMethod> inVal, Unit stmt, FlowSet<SootMethod> outVal) { inVal.copy(outVal); for (Iterator<Edge> edges = cg.edgesOutOf(stmt); edges.hasNext();) { Edge e = edges.next(); if (e.isClinit()) { outVal.add(e.tgt()); } } } @Override protected FlowSet<SootMethod> entryInitialFlow() { return new HashSparseSet<SootMethod>(); } @Override protected FlowSet<SootMethod> newInitialFlow() { HashSparseSet<SootMethod> returnedFlowSet = new HashSparseSet<>(); if (cachedFlowSet == null) { cachedFlowSet = calculateInitialFlow(); } cachedFlowSet.copy(returnedFlowSet); return returnedFlowSet; } protected FlowSet<SootMethod> calculateInitialFlow() {<FILL_FUNCTION_BODY>} }
HashSparseSet<SootMethod> newFlowSet = new HashSparseSet<>(); for (Iterator<Edge> mIt = cg.edgesOutOf(g.getBody().getMethod()); mIt.hasNext();) { Edge edge = mIt.next(); if (edge.isClinit()) { newFlowSet.add(edge.tgt()); } } return newFlowSet;
553
107
660
<methods>public void <init>(DirectedGraph<soot.Unit>) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/ClinitElimTransformer.java
ClinitElimTransformer
internalTransform
class ClinitElimTransformer extends BodyTransformer { @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} }
ClinitElimAnalysis a = new ClinitElimAnalysis(new BriefUnitGraph(b)); CallGraph cg = Scene.v().getCallGraph(); for (Iterator<Edge> edgeIt = cg.edgesOutOf(b.getMethod()); edgeIt.hasNext();) { Edge e = edgeIt.next(); if (e.isClinit()) { Stmt srcStmt = e.srcStmt(); if (srcStmt != null) { if (a.getFlowBefore(srcStmt).contains(e.tgt())) { cg.removeEdge(e); } } } }
55
167
222
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/Filter.java
Filter
advance
class Filter implements Iterator<Edge> { private final EdgePredicate pred; private Iterator<Edge> source; private Edge next = null; public Filter(EdgePredicate pred) { this.pred = pred; } public Iterator<Edge> wrap(Iterator<Edge> source) { this.source = source; advance(); return this; } private void advance() {<FILL_FUNCTION_BODY>} @Override public boolean hasNext() { return next != null; } @Override public Edge next() { Edge ret = next; advance(); return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }
while (source.hasNext()) { next = source.next(); if (next == null) { continue; } if (pred.want(next)) { return; } } next = null;
200
65
265
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/ReachableMethods.java
ReachableMethods
update
class ReachableMethods { protected final ChunkedQueue<MethodOrMethodContext> reachables = new ChunkedQueue<>(); protected final Set<MethodOrMethodContext> set = new HashSet<>(); protected final QueueReader<MethodOrMethodContext> allReachables = reachables.reader(); protected QueueReader<MethodOrMethodContext> unprocessedMethods; protected Iterator<Edge> edgeSource; protected CallGraph cg; protected Filter filter; public ReachableMethods(CallGraph graph, Iterator<? extends MethodOrMethodContext> entryPoints, Filter filter) { this.filter = filter; this.cg = graph; addMethods(entryPoints); this.unprocessedMethods = reachables.reader(); this.edgeSource = (filter == null) ? graph.listener() : filter.wrap(graph.listener()); } public ReachableMethods(CallGraph graph, Iterator<? extends MethodOrMethodContext> entryPoints) { this(graph, entryPoints, null); } public ReachableMethods(CallGraph graph, Collection<? extends MethodOrMethodContext> entryPoints) { this(graph, entryPoints.iterator()); } protected void addMethods(Iterator<? extends MethodOrMethodContext> methods) { while (methods.hasNext()) { addMethod(methods.next()); } } protected void addMethod(MethodOrMethodContext m) { if (set.add(m)) { reachables.add(m); } } /** * Causes the QueueReader objects to be filled up with any methods that have become reachable since the last call. */ public void update() {<FILL_FUNCTION_BODY>} /** * Returns a QueueReader object containing all methods found reachable so far, and which will be informed of any new * methods that are later found to be reachable. */ public QueueReader<MethodOrMethodContext> listener() { return allReachables.clone(); } /** * Returns a QueueReader object which will contain ONLY NEW methods which will be found to be reachable, but not those that * have already been found to be reachable. */ public QueueReader<MethodOrMethodContext> newListener() { return reachables.reader(); } /** * Returns true iff method is reachable. */ public boolean contains(MethodOrMethodContext m) { return set.contains(m); } /** * Returns the number of methods that are reachable. */ public int size() { return set.size(); } }
while (edgeSource.hasNext()) { Edge e = edgeSource.next(); if (e != null) { MethodOrMethodContext srcMethod = e.getSrc(); if (srcMethod != null && !e.isInvalid() && set.contains(srcMethod)) { addMethod(e.getTgt()); } } } while (unprocessedMethods.hasNext()) { MethodOrMethodContext m = unprocessedMethods.next(); if (m == null) { continue; } Iterator<Edge> targets = cg.edgesOutOf(m); if (filter != null) { targets = filter.wrap(targets); } addMethods(new Targets(targets)); }
667
197
864
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/SlowCallGraph.java
SlowCallGraph
toString
class SlowCallGraph extends CallGraph { private final Set<Edge> edges = new HashSet<Edge>(); private final MultiMap<Unit, Edge> unitMap = new HashMultiMap<Unit, Edge>(); private final MultiMap<MethodOrMethodContext, Edge> srcMap = new HashMultiMap<MethodOrMethodContext, Edge>(); private final MultiMap<MethodOrMethodContext, Edge> tgtMap = new HashMultiMap<MethodOrMethodContext, Edge>(); private final ChunkedQueue<Edge> stream = new ChunkedQueue<Edge>(); private final QueueReader<Edge> reader = stream.reader(); /** * Used to add an edge to the call graph. Returns true iff the edge was not already present. */ @Override public boolean addEdge(Edge e) { if (edges.add(e)) { stream.add(e); srcMap.put(e.getSrc(), e); tgtMap.put(e.getTgt(), e); unitMap.put(e.srcUnit(), e); return true; } else { return false; } } /** * Removes the edge e from the call graph. Returns true iff the edge was originally present in the call graph. */ @Override public boolean removeEdge(Edge e) { if (edges.remove(e)) { srcMap.remove(e.getSrc(), e); tgtMap.remove(e.getTgt(), e); unitMap.remove(e.srcUnit(), e); return true; } else { return false; } } /** * Returns an iterator over all methods that are the sources of at least one edge. */ @Override public Iterator<MethodOrMethodContext> sourceMethods() { return new ArrayList<MethodOrMethodContext>(srcMap.keySet()).iterator(); } /** * Returns an iterator over all edges that have u as their source unit. */ @Override public Iterator<Edge> edgesOutOf(Unit u) { return new ArrayList<Edge>(unitMap.get(u)).iterator(); } /** * Returns an iterator over all edges that have m as their source method. */ @Override public Iterator<Edge> edgesOutOf(MethodOrMethodContext m) { return new ArrayList<Edge>(srcMap.get(m)).iterator(); } /** * Returns an iterator over all edges that have m as their target method. */ @Override public Iterator<Edge> edgesInto(MethodOrMethodContext m) { return new ArrayList<Edge>(tgtMap.get(m)).iterator(); } /** * Returns a QueueReader object containing all edges added so far, and which will be informed of any new edges that are * later added to the graph. */ @Override public QueueReader<Edge> listener() { return (QueueReader<Edge>) reader.clone(); } /** * Returns a QueueReader object which will contain ONLY NEW edges which will be added to the graph. */ @Override public QueueReader<Edge> newListener() { return stream.reader(); } @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Returns the number of edges in the call graph. */ @Override public int size() { return edges.size(); } }
StringBuilder out = new StringBuilder(); for (QueueReader<Edge> rdr = listener(); rdr.hasNext();) { Edge e = rdr.next(); if (e != null) { out.append(e.toString()).append('\n'); } } return out.toString();
886
83
969
<methods>public non-sealed void <init>() ,public boolean addEdge(soot.jimple.toolkits.callgraph.Edge) ,public Iterator<soot.jimple.toolkits.callgraph.Edge> edgesInto(soot.MethodOrMethodContext) ,public Iterator<soot.jimple.toolkits.callgraph.Edge> edgesOutOf(soot.Unit) ,public Iterator<soot.jimple.toolkits.callgraph.Edge> edgesOutOf(soot.MethodOrMethodContext) ,public soot.jimple.toolkits.callgraph.Edge findEdge(soot.Unit, soot.SootMethod) ,public boolean isEntryMethod(soot.SootMethod) ,public Iterator<soot.jimple.toolkits.callgraph.Edge> iterator() ,public QueueReader<soot.jimple.toolkits.callgraph.Edge> listener() ,public QueueReader<soot.jimple.toolkits.callgraph.Edge> newListener() ,public boolean removeAllEdgesOutOf(soot.Unit) ,public boolean removeEdge(soot.jimple.toolkits.callgraph.Edge) ,public boolean removeEdge(soot.jimple.toolkits.callgraph.Edge, boolean) ,public boolean removeEdges(Collection<soot.jimple.toolkits.callgraph.Edge>) ,public int size() ,public Iterator<soot.MethodOrMethodContext> sourceMethods() ,public boolean swapEdgesOutOf(soot.jimple.Stmt, soot.jimple.Stmt) ,public java.lang.String toString() <variables>protected soot.jimple.toolkits.callgraph.Edge dummy,protected Set<soot.jimple.toolkits.callgraph.Edge> edges,protected QueueReader<soot.jimple.toolkits.callgraph.Edge> reader,protected Map<soot.MethodOrMethodContext,soot.jimple.toolkits.callgraph.Edge> srcMethodToEdge,protected Map<soot.Unit,soot.jimple.toolkits.callgraph.Edge> srcUnitToEdge,protected ChunkedQueue<soot.jimple.toolkits.callgraph.Edge> stream,protected Map<soot.MethodOrMethodContext,soot.jimple.toolkits.callgraph.Edge> tgtToEdge
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/TransitiveTargets.java
TransitiveTargets
iterator
class TransitiveTargets { private final CallGraph cg; private final Filter filter; public TransitiveTargets(CallGraph cg) { this(cg, null); } public TransitiveTargets(CallGraph cg, Filter filter) { this.cg = cg; this.filter = filter; } public Iterator<MethodOrMethodContext> iterator(Unit u) { ArrayList<MethodOrMethodContext> methods = new ArrayList<MethodOrMethodContext>(); Iterator<Edge> it = cg.edgesOutOf(u); if (filter != null) { it = filter.wrap(it); } while (it.hasNext()) { Edge e = it.next(); methods.add(e.getTgt()); } return iterator(methods.iterator()); } public Iterator<MethodOrMethodContext> iterator(MethodOrMethodContext momc) { ArrayList<MethodOrMethodContext> methods = new ArrayList<MethodOrMethodContext>(); Iterator<Edge> it = cg.edgesOutOf(momc); if (filter != null) { it = filter.wrap(it); } while (it.hasNext()) { Edge e = it.next(); methods.add(e.getTgt()); } return iterator(methods.iterator()); } public Iterator<MethodOrMethodContext> iterator(Iterator<? extends MethodOrMethodContext> methods) { Set<MethodOrMethodContext> s = new HashSet<MethodOrMethodContext>(); ArrayList<MethodOrMethodContext> worklist = new ArrayList<MethodOrMethodContext>(); while (methods.hasNext()) { MethodOrMethodContext method = methods.next(); if (s.add(method)) { worklist.add(method); } } return iterator(s, worklist); } private Iterator<MethodOrMethodContext> iterator(Set<MethodOrMethodContext> s, ArrayList<MethodOrMethodContext> worklist) {<FILL_FUNCTION_BODY>} }
for (int i = 0, end = worklist.size(); i < end; i++) { MethodOrMethodContext method = worklist.get(i); Iterator<Edge> it = cg.edgesOutOf(method); if (filter != null) { it = filter.wrap(it); } while (it.hasNext()) { Edge e = it.next(); if (s.add(e.getTgt())) { worklist.add(e.getTgt()); } } } return worklist.iterator();
532
148
680
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/callgraph/UnreachableMethodTransformer.java
UnreachableMethodTransformer
internalTransform
class UnreachableMethodTransformer extends BodyTransformer { @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} }
// System.out.println( "Performing UnreachableMethodTransformer" ); SootMethod method = b.getMethod(); final Scene scene = Scene.v(); // System.out.println( "Method: " + method.getName() ); if (scene.getReachableMethods().contains(method)) { return; } final Jimple jimp = Jimple.v(); List<Unit> list = new Vector<Unit>(); Local tmpRef = jimp.newLocal("tmpRef", RefType.v("java.io.PrintStream")); b.getLocals().add(tmpRef); list.add(jimp.newAssignStmt(tmpRef, jimp.newStaticFieldRef(scene.getField("<java.lang.System: java.io.PrintStream out>").makeRef()))); SootMethod toCall = scene.getMethod("<java.lang.Thread: void dumpStack()>"); list.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(toCall.makeRef()))); toCall = scene.getMethod("<java.io.PrintStream: void println(java.lang.String)>"); list.add(jimp.newInvokeStmt( jimp.newVirtualInvokeExpr(tmpRef, toCall.makeRef(), StringConstant.v("Executing supposedly unreachable method:")))); list.add(jimp.newInvokeStmt(jimp.newVirtualInvokeExpr(tmpRef, toCall.makeRef(), StringConstant.v("\t" + method.getDeclaringClass().getName() + "." + method.getName())))); toCall = scene.getMethod("<java.lang.System: void exit(int)>"); list.add(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(toCall.makeRef(), IntConstant.v(1)))); /* * Stmt r; if( method.getReturnType() instanceof VoidType ) { list.add( r=Jimple.v().newReturnVoidStmt() ); } else if( * method.getReturnType() instanceof RefLikeType ) { list.add( r=Jimple.v().newReturnStmt( NullConstant.v() ) ); } else * if( method.getReturnType() instanceof PrimType ) { if( method.getReturnType() instanceof DoubleType ) { list.add( * r=Jimple.v().newReturnStmt( DoubleConstant.v( 0 ) ) ); } else if( method.getReturnType() instanceof LongType ) { * list.add( r=Jimple.v().newReturnStmt( LongConstant.v( 0 ) ) ); } else if( method.getReturnType() instanceof FloatType * ) { list.add( r=Jimple.v().newReturnStmt( FloatConstant.v( 0 ) ) ); } else { list.add( r=Jimple.v().newReturnStmt( * IntConstant.v( 0 ) ) ); } } else { throw new RuntimeException( "Wrong return method type: " + method.getReturnType() * ); } */ UnitPatchingChain units = b.getUnits(); /* * if( method.getName().equals( "<init>" ) || method.getName().equals( "<clinit>" ) ) { * * Object o = units.getFirst(); boolean insertFirst = false; while( true ) { //System.out.println( "Unit: " + o ); * //System.out.println( "\tClass: " + o.getClass() ); if( o == null ) { insertFirst = true; break; } if( o instanceof * JInvokeStmt ) { JInvokeStmt stmt = (JInvokeStmt) o; if( (stmt.getInvokeExpr() instanceof SpecialInvokeExpr) ) { * SootMethodRef break; } } o = units.getSuccOf( o ); } if( insertFirst ) { units.insertBefore( list, units.getFirst() ); * } else { units.insertAfter( list, o ) ; } } else { */ units.insertBefore(list, units.getFirst()); /* * ArrayList toRemove = new ArrayList(); for( Iterator sIt = units.iterator(r); sIt.hasNext(); ) { final Stmt s = (Stmt) * sIt.next(); if(s == r) continue; toRemove.add(s); } for( Iterator sIt = toRemove.iterator(); sIt.hasNext(); ) { final * Stmt s = (Stmt) sIt.next(); units.getNonPatchingChain().remove(s); } body.getTraps().clear(); */
55
1,173
1,228
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/graph/CriticalEdgeRemover.java
CriticalEdgeRemover
removeCriticalEdges
class CriticalEdgeRemover extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(CriticalEdgeRemover.class); public CriticalEdgeRemover(Singletons.Global g) { } public static CriticalEdgeRemover v() { return G.v().soot_jimple_toolkits_graph_CriticalEdgeRemover(); } /** * performs critical edge-removing. */ @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { if (Options.v().verbose()) { logger.debug("[" + b.getMethod().getName() + "] Removing Critical Edges..."); } removeCriticalEdges(b); if (Options.v().verbose()) { logger.debug("[" + b.getMethod().getName() + "] Removing Critical Edges done."); } } /** * inserts a Jimple<code>Goto</code> to <code> target, directly after * <code>node</code> in the given <code>unitChain</code>.<br> * As we use <code>JGoto</code> the chain must contain Jimple-stmts. * * @param unitChain * the Chain where we will insert the <code>Goto</code>. * @param node * the <code>Goto</code> will be inserted just after this node. * @param target * is the Unit the <code>goto</code> will jump to. * @return the newly inserted <code>Goto</code> */ private static Unit insertGotoAfter(Chain<Unit> unitChain, Unit node, Unit target) { Unit newGoto = Jimple.v().newGotoStmt(target); unitChain.insertAfter(newGoto, node); return newGoto; } /** * inserts a Jimple<code>Goto</code> to <code> target, directly before * <code>node</code> in the given <code>unitChain</code>.<br> * As we use <code>JGoto</code> the chain must contain Jimple-stmts. * * @param unitChain * the Chain where we will insert the <code>Goto</code>. * @param node * the <code>Goto</code> will be inserted just before this node. * @param target * is the Unit the <code>goto</code> will jump to. * @return the newly inserted <code>Goto</code> */ /* note, that this method has slightly more overhead than the insertGotoAfter */ private static Unit insertGotoBefore(Chain<Unit> unitChain, Unit node, Unit target) { Unit newGoto = Jimple.v().newGotoStmt(target); unitChain.insertBefore(newGoto, node); newGoto.redirectJumpsToThisTo(node); return newGoto; } /** * takes <code>node</code> and redirects all branches to <code>oldTarget</code> to <code>newTarget</code>. * * @param node * the Unit where we redirect * @param oldTarget * @param newTarget */ private static void redirectBranch(Unit node, Unit oldTarget, Unit newTarget) { for (UnitBox targetBox : node.getUnitBoxes()) { if (targetBox.getUnit() == oldTarget) { targetBox.setUnit(newTarget); } } } /** * Splits critical edges by introducing synthetic nodes.<br> * This method <b>will modify</b> the <code>UnitGraph</code> of the body. Synthetic nodes are always <code>JGoto</code>s. * Therefore the body must be in <tt>Jimple</tt>.<br> * As a side-effect, after the transformation, the direct predecessor of a block/node with multiple predecessors will will * not fall through anymore. This simplifies the algorithm and is nice to work with afterwards. * * Note, that critical edges can only appear on edges between blocks!. Our algorithm will *not* take into account * exceptions. (this is nearly impossible anyways) * * @param b * the Jimple-body that will be physicly modified so that there are no critical edges anymore. */ private void removeCriticalEdges(Body b) {<FILL_FUNCTION_BODY>} }
final Chain<Unit> unitChain = b.getUnits(); final Map<Unit, List<Unit>> predecessors = new HashMap<Unit, List<Unit>>(2 * unitChain.size() + 1, 0.7f); // First get the predecessors of each node (although direct predecessors are // predecessors too, we'll not include them in the lists) for (Iterator<Unit> unitIt = unitChain.snapshotIterator(); unitIt.hasNext();) { Unit currentUnit = unitIt.next(); for (UnitBox ub : currentUnit.getUnitBoxes()) { Unit target = ub.getUnit(); List<Unit> predList = predecessors.get(target); if (predList == null) { predecessors.put(target, predList = new ArrayList<Unit>()); } predList.add(currentUnit); } } { // for each node: if we have more than two predecessors, split these edges // if the node at the other end has more than one successor. Unit currentUnit = null; for (Iterator<Unit> unitIt = unitChain.snapshotIterator(); unitIt.hasNext();) { Unit directPredecessor = currentUnit; currentUnit = unitIt.next(); List<Unit> predList = predecessors.get(currentUnit); int nbPreds = (predList == null) ? 0 : predList.size(); if (directPredecessor != null && directPredecessor.fallsThrough()) { nbPreds++; } if (nbPreds >= 2) { assert (predList != null); // redirect the directPredecessor (if it falls through), so we can easily insert the synthetic nodes. This // redirection might not be necessary, but is pleasant anyways (see the Javadoc for this method) if (directPredecessor != null && directPredecessor.fallsThrough()) { directPredecessor = insertGotoAfter(unitChain, directPredecessor, currentUnit); } // if the predecessors have more than one successor insert the synthetic node. for (Unit predecessor : predList) { // Although in Jimple there should be only two ways of having more // than one successor (If and Case) we'll do it the hard way :) int nbSuccs = predecessor.getUnitBoxes().size() + (predecessor.fallsThrough() ? 1 : 0); if (nbSuccs >= 2) { // insert synthetic node (insertGotoAfter should be slightly faster) if (directPredecessor == null) { directPredecessor = insertGotoBefore(unitChain, currentUnit, currentUnit); } else { directPredecessor = insertGotoAfter(unitChain, directPredecessor, currentUnit); } // update the branch redirectBranch(predecessor, currentUnit, directPredecessor); } } } } }
1,187
745
1,932
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/JimpleIDESolver.java
JimpleIDESolver
dumpResults
class JimpleIDESolver<D, V, I extends InterproceduralCFG<Unit, SootMethod>> extends IDESolver<Unit, D, SootMethod, V, I> { private static final Logger logger = LoggerFactory.getLogger(JimpleIDESolver.class); private final boolean DUMP_RESULTS; public JimpleIDESolver(IDETabulationProblem<Unit, D, SootMethod, V, I> problem) { this(problem, false); } public JimpleIDESolver(IDETabulationProblem<Unit, D, SootMethod, V, I> problem, boolean dumpResults) { super(problem); this.DUMP_RESULTS = dumpResults; } @Override public void solve() { super.solve(); if (DUMP_RESULTS) { dumpResults(); } } public void dumpResults() {<FILL_FUNCTION_BODY>} }
try { PrintWriter out = new PrintWriter(new FileOutputStream("ideSolverDump" + System.currentTimeMillis() + ".csv")); List<String> res = new ArrayList<String>(); for (Cell<Unit, D, V> entry : val.cellSet()) { SootMethod methodOf = (SootMethod) icfg.getMethodOf(entry.getRowKey()); PatchingChain<Unit> units = methodOf.getActiveBody().getUnits(); int i = 0; for (Unit unit : units) { if (unit == entry.getRowKey()) { break; } i++; } res.add(methodOf + ";" + entry.getRowKey() + "@" + i + ";" + entry.getColumnKey() + ";" + entry.getValue()); } Collections.sort(res); for (String string : res) { out.println(string); } out.flush(); out.close(); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); }
254
280
534
<methods>public void <init>(IDETabulationProblem<soot.Unit,D,soot.SootMethod,V,I>) ,public void <init>(IDETabulationProblem<soot.Unit,D,soot.SootMethod,V,I>, CacheBuilder#RAW, CacheBuilder#RAW) ,public void printStats() ,public V resultAt(soot.Unit, D) ,public Map<D,V> resultsAt(soot.Unit) ,public void solve() <variables>public static boolean DEBUG,public static CacheBuilder<java.lang.Object,java.lang.Object> DEFAULT_CACHE_BUILDER,protected final EdgeFunction<V> allTop,protected final boolean computeValues,protected Table<soot.Unit,soot.Unit,Map<D,Set<D>>> computedInterPEdges,protected Table<soot.Unit,soot.Unit,Map<D,Set<D>>> computedIntraPEdges,public long durationFlowFunctionApplication,public long durationFlowFunctionConstruction,protected final EdgeFunctions<soot.Unit,D,soot.SootMethod,V> edgeFunctions,protected final EdgeFunctionCache<soot.Unit,D,soot.SootMethod,V> efCache,protected final Table<soot.Unit,D,Table<soot.Unit,D,EdgeFunction<V>>> endSummary,protected heros.solver.CountingThreadPoolExecutor executor,protected final FlowFunctionCache<soot.Unit,D,soot.SootMethod> ffCache,public long flowFunctionApplicationCount,public long flowFunctionConstructionCount,protected final FlowFunctions<soot.Unit,D,soot.SootMethod> flowFunctions,protected final boolean followReturnsPastSeeds,protected final I icfg,protected final Table<soot.Unit,D,Map<soot.Unit,Set<D>>> incoming,protected final Map<soot.Unit,Set<D>> initialSeeds,protected final JumpFunctions<soot.Unit,D,V> jumpFn,protected static final org.slf4j.Logger logger,protected int numThreads,public long propagationCount,private boolean recordEdges,protected final Set<soot.Unit> unbalancedRetSites,protected final Table<soot.Unit,D,V> val,protected final MeetLattice<V> valueLattice,protected final D zeroValue
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/JimpleIFDSSolver.java
JimpleIFDSSolver
dumpResults
class JimpleIFDSSolver<D, I extends InterproceduralCFG<Unit, SootMethod>> extends IFDSSolver<Unit, D, SootMethod, I> { private static final Logger logger = LoggerFactory.getLogger(JimpleIFDSSolver.class); private final boolean DUMP_RESULTS; public JimpleIFDSSolver(IFDSTabulationProblem<Unit, D, SootMethod, I> problem) { this(problem, false); } public JimpleIFDSSolver(IFDSTabulationProblem<Unit, D, SootMethod, I> problem, boolean dumpResults) { super(problem); this.DUMP_RESULTS = dumpResults; } @Override public void solve() { super.solve(); if (DUMP_RESULTS) { dumpResults(); } } public void dumpResults() {<FILL_FUNCTION_BODY>} }
try { PrintWriter out = new PrintWriter(new FileOutputStream("ideSolverDump" + System.currentTimeMillis() + ".csv")); List<SortableCSVString> res = new ArrayList<SortableCSVString>(); for (Cell<Unit, D, ?> entry : val.cellSet()) { SootMethod methodOf = (SootMethod) icfg.getMethodOf(entry.getRowKey()); PatchingChain<Unit> units = methodOf.getActiveBody().getUnits(); int i = 0; for (Unit unit : units) { if (unit == entry.getRowKey()) { break; } i++; } res.add(new SortableCSVString( methodOf + ";" + entry.getRowKey() + "@" + i + ";" + entry.getColumnKey() + ";" + entry.getValue(), i)); } Collections.sort(res); // replacement is bugfix for excel view: for (SortableCSVString string : res) { out.println(string.value.replace("\"", "'")); } out.flush(); out.close(); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); }
251
322
573
<methods>public void <init>(IFDSTabulationProblem<soot.Unit,D,soot.SootMethod,I>) ,public Set<D> ifdsResultsAt(soot.Unit) <variables>private static final EdgeFunction<heros.solver.IFDSSolver.BinaryDomain> ALL_BOTTOM
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSLiveVariables.java
IFDSLiveVariables
computeTargets
class IFDSLiveVariables extends DefaultJimpleIFDSTabulationProblem<Value, InterproceduralCFG<Unit, SootMethod>> { public IFDSLiveVariables(InterproceduralCFG<Unit, SootMethod> icfg) { super(icfg); } @Override public FlowFunctions<Unit, Value, SootMethod> createFlowFunctionsFactory() { return new FlowFunctions<Unit, Value, SootMethod>() { @Override public FlowFunction<Value> getNormalFlowFunction(Unit curr, Unit succ) { if (curr.getUseAndDefBoxes().isEmpty()) { return Identity.v(); } final Stmt s = (Stmt) curr; return new FlowFunction<Value>() { public Set<Value> computeTargets(Value source) { // kill defs List<ValueBox> defs = s.getDefBoxes(); if (!defs.isEmpty()) { if (defs.get(0).getValue().equivTo(source)) { return Collections.emptySet(); } } // gen uses out of zero value if (source.equals(zeroValue())) { Set<Value> liveVars = new HashSet<Value>(); for (ValueBox useBox : s.getUseBoxes()) { Value value = useBox.getValue(); liveVars.add(value); } return liveVars; } // else just propagate return Collections.singleton(source); } }; } @Override public FlowFunction<Value> getCallFlowFunction(Unit callStmt, final SootMethod destinationMethod) { final Stmt s = (Stmt) callStmt; return new FlowFunction<Value>() { public Set<Value> computeTargets(Value source) { if (!s.getDefBoxes().isEmpty()) { Value callerSideReturnValue = s.getDefBoxes().get(0).getValue(); if (callerSideReturnValue.equivTo(source)) { Set<Value> calleeSideReturnValues = new HashSet<Value>(); for (Unit calleeUnit : interproceduralCFG().getStartPointsOf(destinationMethod)) { if (calleeUnit instanceof ReturnStmt) { ReturnStmt returnStmt = (ReturnStmt) calleeUnit; calleeSideReturnValues.add(returnStmt.getOp()); } } return calleeSideReturnValues; } } // no return value, nothing to propagate return Collections.emptySet(); } }; } @Override public FlowFunction<Value> getReturnFlowFunction(final Unit callSite, SootMethod calleeMethod, final Unit exitStmt, Unit returnSite) { Stmt s = (Stmt) callSite; InvokeExpr ie = s.getInvokeExpr(); final List<Value> callArgs = ie.getArgs(); final List<Local> paramLocals = new ArrayList<Local>(); for (int i = 0; i < calleeMethod.getParameterCount(); i++) { paramLocals.add(calleeMethod.getActiveBody().getParameterLocal(i)); } return new FlowFunction<Value>() { public Set<Value> computeTargets(Value source) { Set<Value> liveParamsAtCallee = new HashSet<Value>(); for (int i = 0; i < paramLocals.size(); i++) { if (paramLocals.get(i).equivTo(source)) { liveParamsAtCallee.add(callArgs.get(i)); } } return liveParamsAtCallee; } }; } @Override public FlowFunction<Value> getCallToReturnFlowFunction(Unit callSite, Unit returnSite) { if (callSite.getUseAndDefBoxes().isEmpty()) { return Identity.v(); } final Stmt s = (Stmt) callSite; return new FlowFunction<Value>() { public Set<Value> computeTargets(Value source) {<FILL_FUNCTION_BODY>} }; } }; } public Map<Unit, Set<Value>> initialSeeds() { return DefaultSeeds.make(interproceduralCFG().getStartPointsOf(Scene.v().getMainMethod()), zeroValue()); } public Value createZeroValue() { return new JimpleLocal("<<zero>>", NullType.v()); } }
// kill defs List<ValueBox> defs = s.getDefBoxes(); if (!defs.isEmpty()) { if (defs.get(0).getValue().equivTo(source)) { return Collections.emptySet(); } } // gen uses out of zero value if (source.equals(zeroValue())) { Set<Value> liveVars = new HashSet<Value>(); // only "gen" those values that are not parameter values; // the latter are taken care of by the return-flow function List<Value> args = s.getInvokeExpr().getArgs(); for (ValueBox useBox : s.getUseBoxes()) { Value value = useBox.getValue(); if (!args.contains(value)) { liveVars.add(value); } } return liveVars; } // else just propagate return Collections.singleton(source);
1,158
242
1,400
<methods>public void <init>(InterproceduralCFG<soot.Unit,soot.SootMethod>) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSPossibleTypes.java
IFDSPossibleTypes
createFlowFunctionsFactory
class IFDSPossibleTypes extends DefaultJimpleIFDSTabulationProblem<Pair<Value, Type>, InterproceduralCFG<Unit, SootMethod>> { public IFDSPossibleTypes(InterproceduralCFG<Unit, SootMethod> icfg) { super(icfg); } public FlowFunctions<Unit, Pair<Value, Type>, SootMethod> createFlowFunctionsFactory() {<FILL_FUNCTION_BODY>} public Map<Unit, Set<Pair<Value, Type>>> initialSeeds() { return DefaultSeeds.make(Collections.singleton(Scene.v().getMainMethod().getActiveBody().getUnits().getFirst()), zeroValue()); } public Pair<Value, Type> createZeroValue() { return new Pair<Value, Type>(Jimple.v().newLocal("<dummy>", UnknownType.v()), UnknownType.v()); } }
return new FlowFunctions<Unit, Pair<Value, Type>, SootMethod>() { public FlowFunction<Pair<Value, Type>> getNormalFlowFunction(Unit src, Unit dest) { if (src instanceof DefinitionStmt) { DefinitionStmt defnStmt = (DefinitionStmt) src; if (defnStmt.containsInvokeExpr()) { return Identity.v(); } final Value right = defnStmt.getRightOp(); final Value left = defnStmt.getLeftOp(); // won't track primitive-typed variables if (right.getType() instanceof PrimType) { return Identity.v(); } if (right instanceof Constant || right instanceof NewExpr) { return new FlowFunction<Pair<Value, Type>>() { public Set<Pair<Value, Type>> computeTargets(Pair<Value, Type> source) { if (source == zeroValue()) { Set<Pair<Value, Type>> res = new LinkedHashSet<Pair<Value, Type>>(); res.add(new Pair<Value, Type>(left, right.getType())); res.add(zeroValue()); return res; } else if (source.getO1() instanceof Local && source.getO1().equivTo(left)) { // strong update for local variables return Collections.emptySet(); } else { return Collections.singleton(source); } } }; } else if (right instanceof Ref || right instanceof Local) { return new FlowFunction<Pair<Value, Type>>() { public Set<Pair<Value, Type>> computeTargets(final Pair<Value, Type> source) { Value value = source.getO1(); if (source.getO1() instanceof Local && source.getO1().equivTo(left)) { // strong update for local variables return Collections.emptySet(); } else if (maybeSameLocation(value, right)) { return new LinkedHashSet<Pair<Value, Type>>() { { add(new Pair<Value, Type>(left, source.getO2())); add(source); } }; } else { return Collections.singleton(source); } } private boolean maybeSameLocation(Value v1, Value v2) { if (!(v1 instanceof InstanceFieldRef && v2 instanceof InstanceFieldRef) && !(v1 instanceof ArrayRef && v2 instanceof ArrayRef)) { return v1.equivTo(v2); } if (v1 instanceof InstanceFieldRef && v2 instanceof InstanceFieldRef) { InstanceFieldRef ifr1 = (InstanceFieldRef) v1; InstanceFieldRef ifr2 = (InstanceFieldRef) v2; if (!ifr1.getField().getName().equals(ifr2.getField().getName())) { return false; } Local base1 = (Local) ifr1.getBase(); Local base2 = (Local) ifr2.getBase(); PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); PointsToSet pts1 = pta.reachingObjects(base1); PointsToSet pts2 = pta.reachingObjects(base2); return pts1.hasNonEmptyIntersection(pts2); } else { // v1 instanceof ArrayRef && v2 instanceof ArrayRef ArrayRef ar1 = (ArrayRef) v1; ArrayRef ar2 = (ArrayRef) v2; Local base1 = (Local) ar1.getBase(); Local base2 = (Local) ar2.getBase(); PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); PointsToSet pts1 = pta.reachingObjects(base1); PointsToSet pts2 = pta.reachingObjects(base2); return pts1.hasNonEmptyIntersection(pts2); } } }; } } return Identity.v(); } public FlowFunction<Pair<Value, Type>> getCallFlowFunction(final Unit src, final SootMethod dest) { Stmt stmt = (Stmt) src; InvokeExpr ie = stmt.getInvokeExpr(); final List<Value> callArgs = ie.getArgs(); final List<Local> paramLocals = new ArrayList<Local>(); for (int i = 0; i < dest.getParameterCount(); i++) { paramLocals.add(dest.getActiveBody().getParameterLocal(i)); } return new FlowFunction<Pair<Value, Type>>() { public Set<Pair<Value, Type>> computeTargets(Pair<Value, Type> source) { if (!dest.getName().equals("<clinit>") && !dest.getSubSignature().equals("void run()")) { Value value = source.getO1(); int argIndex = callArgs.indexOf(value); if (argIndex > -1) { return Collections.singleton(new Pair<Value, Type>(paramLocals.get(argIndex), source.getO2())); } } return Collections.emptySet(); } }; } public FlowFunction<Pair<Value, Type>> getReturnFlowFunction(Unit callSite, SootMethod callee, Unit exitStmt, Unit retSite) { if (exitStmt instanceof ReturnStmt) { ReturnStmt returnStmt = (ReturnStmt) exitStmt; Value op = returnStmt.getOp(); if (op instanceof Local) { if (callSite instanceof DefinitionStmt) { DefinitionStmt defnStmt = (DefinitionStmt) callSite; Value leftOp = defnStmt.getLeftOp(); if (leftOp instanceof Local) { final Local tgtLocal = (Local) leftOp; final Local retLocal = (Local) op; return new FlowFunction<Pair<Value, Type>>() { public Set<Pair<Value, Type>> computeTargets(Pair<Value, Type> source) { if (source.getO1() == retLocal) { return Collections.singleton(new Pair<Value, Type>(tgtLocal, source.getO2())); } return Collections.emptySet(); } }; } } } } return KillAll.v(); } public FlowFunction<Pair<Value, Type>> getCallToReturnFlowFunction(Unit call, Unit returnSite) { return Identity.v(); } };
241
1,648
1,889
<methods>public void <init>(InterproceduralCFG<soot.Unit,soot.SootMethod>) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSReachingDefinitions.java
IFDSReachingDefinitions
computeTargets
class IFDSReachingDefinitions extends DefaultJimpleIFDSTabulationProblem<Pair<Value, Set<DefinitionStmt>>, InterproceduralCFG<Unit, SootMethod>> { public IFDSReachingDefinitions(InterproceduralCFG<Unit, SootMethod> icfg) { super(icfg); } @Override public FlowFunctions<Unit, Pair<Value, Set<DefinitionStmt>>, SootMethod> createFlowFunctionsFactory() { return new FlowFunctions<Unit, Pair<Value, Set<DefinitionStmt>>, SootMethod>() { @Override public FlowFunction<Pair<Value, Set<DefinitionStmt>>> getNormalFlowFunction(final Unit curr, Unit succ) { if (curr instanceof DefinitionStmt) { final DefinitionStmt assignment = (DefinitionStmt) curr; return new FlowFunction<Pair<Value, Set<DefinitionStmt>>>() { @Override public Set<Pair<Value, Set<DefinitionStmt>>> computeTargets(Pair<Value, Set<DefinitionStmt>> source) { if (source != zeroValue()) { if (source.getO1().equivTo(assignment.getLeftOp())) { return Collections.emptySet(); } return Collections.singleton(source); } else { LinkedHashSet<Pair<Value, Set<DefinitionStmt>>> res = new LinkedHashSet<Pair<Value, Set<DefinitionStmt>>>(); res.add(new Pair<Value, Set<DefinitionStmt>>(assignment.getLeftOp(), Collections.<DefinitionStmt>singleton(assignment))); return res; } } }; } return Identity.v(); } @Override public FlowFunction<Pair<Value, Set<DefinitionStmt>>> getCallFlowFunction(Unit callStmt, final SootMethod destinationMethod) { Stmt stmt = (Stmt) callStmt; InvokeExpr invokeExpr = stmt.getInvokeExpr(); final List<Value> args = invokeExpr.getArgs(); final List<Local> localArguments = new ArrayList<Local>(args.size()); for (Value value : args) { if (value instanceof Local) { localArguments.add((Local) value); } else { localArguments.add(null); } } return new FlowFunction<Pair<Value, Set<DefinitionStmt>>>() { @Override public Set<Pair<Value, Set<DefinitionStmt>>> computeTargets(Pair<Value, Set<DefinitionStmt>> source) {<FILL_FUNCTION_BODY>} }; } @Override public FlowFunction<Pair<Value, Set<DefinitionStmt>>> getReturnFlowFunction(final Unit callSite, SootMethod calleeMethod, final Unit exitStmt, Unit returnSite) { if (!(callSite instanceof DefinitionStmt) || (exitStmt instanceof ReturnVoidStmt)) { return KillAll.v(); } return new FlowFunction<Pair<Value, Set<DefinitionStmt>>>() { @Override public Set<Pair<Value, Set<DefinitionStmt>>> computeTargets(Pair<Value, Set<DefinitionStmt>> source) { if (exitStmt instanceof ReturnStmt) { ReturnStmt returnStmt = (ReturnStmt) exitStmt; if (returnStmt.getOp().equivTo(source.getO1())) { DefinitionStmt definitionStmt = (DefinitionStmt) callSite; Pair<Value, Set<DefinitionStmt>> pair = new Pair<Value, Set<DefinitionStmt>>(definitionStmt.getLeftOp(), source.getO2()); return Collections.singleton(pair); } } return Collections.emptySet(); } }; } @Override public FlowFunction<Pair<Value, Set<DefinitionStmt>>> getCallToReturnFlowFunction(Unit callSite, Unit returnSite) { if (!(callSite instanceof DefinitionStmt)) { return Identity.v(); } final DefinitionStmt definitionStmt = (DefinitionStmt) callSite; return new FlowFunction<Pair<Value, Set<DefinitionStmt>>>() { @Override public Set<Pair<Value, Set<DefinitionStmt>>> computeTargets(Pair<Value, Set<DefinitionStmt>> source) { if (source.getO1().equivTo(definitionStmt.getLeftOp())) { return Collections.emptySet(); } else { return Collections.singleton(source); } } }; } }; } public Map<Unit, Set<Pair<Value, Set<DefinitionStmt>>>> initialSeeds() { return DefaultSeeds.make(Collections.singleton(Scene.v().getMainMethod().getActiveBody().getUnits().getFirst()), zeroValue()); } public Pair<Value, Set<DefinitionStmt>> createZeroValue() { return new Pair<Value, Set<DefinitionStmt>>(new JimpleLocal("<<zero>>", NullType.v()), Collections.<DefinitionStmt>emptySet()); } }
if (!destinationMethod.getName().equals("<clinit>") && !destinationMethod.getSubSignature().equals("void run()")) { if (localArguments.contains(source.getO1())) { int paramIndex = args.indexOf(source.getO1()); Pair<Value, Set<DefinitionStmt>> pair = new Pair<Value, Set<DefinitionStmt>>( new EquivalentValue( Jimple.v().newParameterRef(destinationMethod.getParameterType(paramIndex), paramIndex)), source.getO2()); return Collections.singleton(pair); } } return Collections.emptySet();
1,300
166
1,466
<methods>public void <init>(InterproceduralCFG<soot.Unit,soot.SootMethod>) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSUninitializedVariables.java
IFDSUninitializedVariables
createFlowFunctionsFactory
class IFDSUninitializedVariables extends DefaultJimpleIFDSTabulationProblem<Local, InterproceduralCFG<Unit, SootMethod>> { public IFDSUninitializedVariables(InterproceduralCFG<Unit, SootMethod> icfg) { super(icfg); } @Override public FlowFunctions<Unit, Local, SootMethod> createFlowFunctionsFactory() {<FILL_FUNCTION_BODY>} public Map<Unit, Set<Local>> initialSeeds() { return DefaultSeeds.make(Collections.singleton(Scene.v().getMainMethod().getActiveBody().getUnits().getFirst()), zeroValue()); } @Override public Local createZeroValue() { return new JimpleLocal("<<zero>>", NullType.v()); } }
return new FlowFunctions<Unit, Local, SootMethod>() { @Override public FlowFunction<Local> getNormalFlowFunction(Unit curr, Unit succ) { final SootMethod m = interproceduralCFG().getMethodOf(curr); if (Scene.v().getEntryPoints().contains(m) && interproceduralCFG().isStartPoint(curr)) { return new FlowFunction<Local>() { @Override public Set<Local> computeTargets(Local source) { if (source == zeroValue()) { Set<Local> res = new LinkedHashSet<Local>(); res.addAll(m.getActiveBody().getLocals()); for (int i = 0; i < m.getParameterCount(); i++) { res.remove(m.getActiveBody().getParameterLocal(i)); } return res; } return Collections.emptySet(); } }; } if (curr instanceof DefinitionStmt) { final DefinitionStmt definition = (DefinitionStmt) curr; final Value leftOp = definition.getLeftOp(); if (leftOp instanceof Local) { final Local leftOpLocal = (Local) leftOp; return new FlowFunction<Local>() { @Override public Set<Local> computeTargets(final Local source) { List<ValueBox> useBoxes = definition.getUseBoxes(); for (ValueBox valueBox : useBoxes) { if (valueBox.getValue().equivTo(source)) { LinkedHashSet<Local> res = new LinkedHashSet<Local>(); res.add(source); res.add(leftOpLocal); return res; } } if (leftOp.equivTo(source)) { return Collections.emptySet(); } return Collections.singleton(source); } }; } } return Identity.v(); } @Override public FlowFunction<Local> getCallFlowFunction(Unit callStmt, final SootMethod destinationMethod) { Stmt stmt = (Stmt) callStmt; InvokeExpr invokeExpr = stmt.getInvokeExpr(); final List<Value> args = invokeExpr.getArgs(); final List<Local> localArguments = new ArrayList<Local>(); for (Value value : args) { if (value instanceof Local) { localArguments.add((Local) value); } } return new FlowFunction<Local>() { @Override public Set<Local> computeTargets(final Local source) { // Do not map parameters for <clinit> edges if (destinationMethod.getName().equals("<clinit>") || destinationMethod.getSubSignature().equals("void run()")) { return Collections.emptySet(); } for (Local localArgument : localArguments) { if (source.equivTo(localArgument)) { return Collections .<Local>singleton(destinationMethod.getActiveBody().getParameterLocal(args.indexOf(localArgument))); } } if (source == zeroValue()) { // gen all locals that are not parameter locals Collection<Local> locals = destinationMethod.getActiveBody().getLocals(); LinkedHashSet<Local> uninitializedLocals = new LinkedHashSet<Local>(locals); for (int i = 0; i < destinationMethod.getParameterCount(); i++) { uninitializedLocals.remove(destinationMethod.getActiveBody().getParameterLocal(i)); } return uninitializedLocals; } return Collections.emptySet(); } }; } @Override public FlowFunction<Local> getReturnFlowFunction(final Unit callSite, SootMethod calleeMethod, final Unit exitStmt, Unit returnSite) { if (callSite instanceof DefinitionStmt) { final DefinitionStmt definition = (DefinitionStmt) callSite; if (definition.getLeftOp() instanceof Local) { final Local leftOpLocal = (Local) definition.getLeftOp(); if (exitStmt instanceof ReturnStmt) { final ReturnStmt returnStmt = (ReturnStmt) exitStmt; return new FlowFunction<Local>() { @Override public Set<Local> computeTargets(Local source) { if (returnStmt.getOp().equivTo(source)) { return Collections.singleton(leftOpLocal); } return Collections.emptySet(); } }; } else if (exitStmt instanceof ThrowStmt) { // if we throw an exception, LHS of call is undefined return new FlowFunction<Local>() { @Override public Set<Local> computeTargets(final Local source) { if (source == zeroValue()) { return Collections.singleton(leftOpLocal); } else { return Collections.emptySet(); } } }; } } } return KillAll.v(); } @Override public FlowFunction<Local> getCallToReturnFlowFunction(Unit callSite, Unit returnSite) { if (callSite instanceof DefinitionStmt) { DefinitionStmt definition = (DefinitionStmt) callSite; if (definition.getLeftOp() instanceof Local) { final Local leftOpLocal = (Local) definition.getLeftOp(); return new Kill<Local>(leftOpLocal); } } return Identity.v(); } };
214
1,398
1,612
<methods>public void <init>(InterproceduralCFG<soot.Unit,soot.SootMethod>) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/icfg/JimpleBasedInterproceduralCFG.java
EdgeFilter
load
class EdgeFilter extends Filter { protected EdgeFilter() { super(new EdgePredicate() { @Override public boolean want(Edge e) { return e.kind().isExplicit() || e.kind().isFake() || e.kind().isClinit() || (includeReflectiveCalls && e.kind().isReflection()); } }); } public EdgeFilter(EdgePredicate p) { super(p); } } @DontSynchronize("readonly") protected final CallGraph cg; protected CacheLoader<Unit, Collection<SootMethod>> loaderUnitToCallees = new CacheLoader<Unit, Collection<SootMethod>>() { @Override public Collection<SootMethod> load(Unit u) throws Exception { ArrayList<SootMethod> res = null; // only retain callers that are explicit call sites or // Thread.start() Iterator<Edge> edgeIter = createEdgeFilter().wrap(cg.edgesOutOf(u)); while (edgeIter.hasNext()) { Edge edge = edgeIter.next(); SootMethod m = edge.getTgt().method(); if (includePhantomCallees || m.hasActiveBody()) { if (res == null) { res = new ArrayList<SootMethod>(); } res.add(m); } else if (IDESolver.DEBUG) { logger.error(String.format("Method %s is referenced but has no body!", m.getSignature(), new Exception())); } } if (res != null) { res.trimToSize(); return res; } else { if (fallbackToImmediateCallees && u instanceof Stmt) { Stmt s = (Stmt) u; if (s.containsInvokeExpr()) { SootMethod immediate = s.getInvokeExpr().getMethod(); if (includePhantomCallees || immediate.hasActiveBody()) { return Collections.singleton(immediate); } } } return Collections.emptySet(); } } }; @SynchronizedBy("by use of synchronized LoadingCache class") protected final LoadingCache<Unit, Collection<SootMethod>> unitToCallees = IDESolver.DEFAULT_CACHE_BUILDER.build(loaderUnitToCallees); protected CacheLoader<SootMethod, Collection<Unit>> loaderMethodToCallers = new CacheLoader<SootMethod, Collection<Unit>>() { @Override public Collection<Unit> load(SootMethod m) throws Exception {<FILL_FUNCTION_BODY>
ArrayList<Unit> res = new ArrayList<Unit>(); // only retain callers that are explicit call sites or // Thread.start() Iterator<Edge> edgeIter = createEdgeFilter().wrap(cg.edgesInto(m)); while (edgeIter.hasNext()) { Edge edge = edgeIter.next(); res.add(edge.srcUnit()); } res.trimToSize(); return res;
675
111
786
<methods>public void <init>() ,public void <init>(boolean) ,public Set<soot.Unit> allNonCallEndNodes() ,public Set<soot.Unit> allNonCallStartNodes() ,public soot.Body getBodyOf(soot.Unit) ,public Set<soot.Unit> getCallsFromWithin(soot.SootMethod) ,public Collection<soot.Unit> getEndPointsOf(soot.SootMethod) ,public soot.SootMethod getMethodOf(soot.Unit) ,public DirectedGraph<soot.Unit> getOrCreateUnitGraph(soot.SootMethod) ,public DirectedGraph<soot.Unit> getOrCreateUnitGraph(soot.Body) ,public List<soot.Value> getParameterRefs(soot.SootMethod) ,public List<soot.Unit> getPredsOf(soot.Unit) ,public List<soot.Unit> getPredsOfCallAt(soot.Unit) ,public Collection<soot.Unit> getReturnSitesOfCallAt(soot.Unit) ,public Collection<soot.Unit> getStartPointsOf(soot.SootMethod) ,public List<soot.Unit> getSuccsOf(soot.Unit) ,public void initializeUnitToOwner(soot.SootMethod) ,public void initializeUnitToOwner(soot.Body) ,public boolean isBranchTarget(soot.Unit, soot.Unit) ,public boolean isCallStmt(soot.Unit) ,public boolean isExitStmt(soot.Unit) ,public boolean isFallThroughSuccessor(soot.Unit, soot.Unit) ,public boolean isReachable(soot.Unit) ,public boolean isReturnSite(soot.Unit) ,public boolean isStartPoint(soot.Unit) ,public boolean setOwnerStatement(soot.Unit, soot.Body) <variables>protected LoadingCache<soot.Body,DirectedGraph<soot.Unit>> bodyToUnitGraph,protected final non-sealed boolean enableExceptions,protected LoadingCache<soot.SootMethod,Set<soot.Unit>> methodToCallsFromWithin,protected LoadingCache<soot.SootMethod,List<soot.Value>> methodToParameterRefs,private final Map<soot.Unit,soot.Body> unitToOwner
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/icfg/dotexport/ICFGDotVisualizer.java
ICFGDotVisualizer
graphTraverse
class ICFGDotVisualizer { private static final Logger logger = LoggerFactory.getLogger(ICFGDotVisualizer.class); private DotGraph dotIcfg = new DotGraph(""); private ArrayList<Unit> visited = new ArrayList<Unit>(); String fileName; Unit startPoint; InterproceduralCFG<Unit, SootMethod> icfg; /** * This class will save your ICFG in DOT format by traversing the ICFG Depth-first! * * @param fileName: * Name of the file to save ICFG in DOT extension * @param startPoint: * This is of type Unit and is the starting point of the graph (eg. main method) * @param InterproceduralCFG<Unit, * SootMethod>: Object of InterproceduralCFG which represents the entire ICFG */ public ICFGDotVisualizer(String fileName, Unit startPoint, InterproceduralCFG<Unit, SootMethod> icfg) { this.fileName = fileName; this.startPoint = startPoint; this.icfg = icfg; if (this.fileName == null || this.fileName == "") { System.out.println("Please provide a vaid filename"); } if (this.startPoint == null) { System.out.println("startPoint is null!"); } if (this.icfg == null) { System.out.println("ICFG is null!"); } } /** * For the given file name, export the ICFG into DOT format. All parameters initialized through the constructor */ public void exportToDot() { if (this.startPoint != null && this.icfg != null && this.fileName != null) { graphTraverse(this.startPoint, this.icfg); dotIcfg.plot(this.fileName); logger.debug("" + fileName + DotGraph.DOT_EXTENSION); } else { System.out.println("Parameters not properly initialized!"); } } private void graphTraverse(Unit startPoint, InterproceduralCFG<Unit, SootMethod> icfg) {<FILL_FUNCTION_BODY>} }
List<Unit> currentSuccessors = icfg.getSuccsOf(startPoint); if (currentSuccessors.size() == 0) { System.out.println("Traversal complete"); return; } else { for (Unit succ : currentSuccessors) { System.out.println("Succesor: " + succ.toString()); if (!visited.contains(succ)) { dotIcfg.drawEdge(startPoint.toString(), succ.toString()); visited.add(succ); graphTraverse(succ, icfg); } else { dotIcfg.drawEdge(startPoint.toString(), succ.toString()); } } }
587
178
765
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/libsumm/FixedMethods.java
FixedMethods
clientOverwriteableOverwrites
class FixedMethods { public final static boolean ASSUME_PACKAGES_SEALED = false; /** * Returns true if a method call is fixed, i.e., assuming that all classes in the Scene resemble library code, then client * code cannot possible overwrite the called method. This is trivially true for InvokeStatic and InvokeSpecial, but can * also hold for virtual invokes if all possible call targets in the library cannot be overwritten. * * @see #clientOverwriteableOverwrites(SootMethod) */ public static boolean isFixed(InvokeExpr ie) { return ie instanceof StaticInvokeExpr || ie instanceof SpecialInvokeExpr || !clientOverwriteableOverwrites(ie.getMethod()); } /** * Returns true if this method itself is visible to the client and overwriteable or if the same holds for any of the * methods in the library that overwrite the argument method. * * @see #clientOverwriteable(SootMethod) */ private static boolean clientOverwriteableOverwrites(SootMethod m) {<FILL_FUNCTION_BODY>} /** * Returns true if the given method itself is visible to the client and overwriteable. This is true if neither the method * nor its declaring class are final, if the method is visible and if the declaring class can be instantiated. * * @see #visible(SootMethod) * @see #clientCanInstantiate(SootClass) */ private static boolean clientOverwriteable(SootMethod m) { SootClass c = m.getDeclaringClass(); if (!c.isFinal() && !m.isFinal() && visible(m) && clientCanInstantiate(c)) { return true; } return false; } /** * Returns true if clients can instantiate the given class. This holds if the given class is actually an interface, or if * it contains a visible constructor. If the class is an inner class, then the enclosing classes must be instantiable as * well. */ private static boolean clientCanInstantiate(SootClass cPrime) { // subtypes of interface types can always be instantiated if (cPrime.isInterface()) { return true; } for (SootMethod m : cPrime.getMethods()) { if (m.getName().equals(SootMethod.constructorName)) { if (visible(m)) { return true; } } } return false; } /** * Returns true if the given method is visible to client code. */ private static boolean visible(SootMethod mPrime) { SootClass cPrime = mPrime.getDeclaringClass(); return (cPrime.isPublic() || cPrime.isProtected() || (!cPrime.isPrivate() && !ASSUME_PACKAGES_SEALED)) && (mPrime.isPublic() || mPrime.isProtected() || (!mPrime.isPrivate() && !ASSUME_PACKAGES_SEALED)); } }
if (clientOverwriteable(m)) { return true; } SootClass c = m.getDeclaringClass(); // TODO could use PTA and call graph to filter subclasses further for (SootClass cPrime : Scene.v().getFastHierarchy().getSubclassesOf(c)) { SootMethod mPrime = cPrime.getMethodUnsafe(m.getSubSignature()); if (mPrime != null) { if (clientOverwriteable(mPrime)) { return true; } } } return false;
794
153
947
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/ide/libsumm/Main.java
Main
internalTransform
class Main { static int yes = 0, no = 0; /** * @param args */ public static void main(String[] args) { PackManager.v().getPack("jtp").add(new Transform("jtp.fixedie", new BodyTransformer() { @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) {<FILL_FUNCTION_BODY>} })); soot.Main.main(args); System.err.println("+++ " + yes); System.err.println(" - " + no); } }
for (Unit u : b.getUnits()) { Stmt s = (Stmt) u; if (s.containsInvokeExpr()) { InvokeExpr ie = s.getInvokeExpr(); if (FixedMethods.isFixed(ie)) { System.err.println("+++ " + ie); yes++; } else { System.err.println(" - " + ie); no++; } } }
162
123
285
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/infoflow/FakeJimpleLocal.java
FakeJimpleLocal
equivTo
class FakeJimpleLocal extends JimpleLocal { Local realLocal; Object info; // whatever you want to attach to it... /** Constructs a FakeJimpleLocal of the given name and type. */ public FakeJimpleLocal(String name, Type t, Local realLocal) { this(name, t, realLocal, null); } public FakeJimpleLocal(String name, Type t, Local realLocal, Object info) { super(name, t); this.realLocal = realLocal; this.info = info; } /** Returns true if the given object is structurally equal to this one. */ public boolean equivTo(Object o) {<FILL_FUNCTION_BODY>} public boolean equals(Object o) { return equivTo(o); } /** Returns a clone of the current JimpleLocal. */ public Object clone() { return new FakeJimpleLocal(getName(), getType(), realLocal, info); } public Local getRealLocal() { return realLocal; } public Object getInfo() { return info; } public void setInfo(Object o) { info = o; } }
if (o == null) { return false; } if (o instanceof JimpleLocal) { if (getName() != null && getType() != null) { return getName().equals(((Local) o).getName()) && getType().equals(((Local) o).getType()); } else if (getName() != null) { return getName().equals(((Local) o).getName()) && ((Local) o).getType() == null; } else if (getType() != null) { return ((Local) o).getName() == null && getType().equals(((Local) o).getType()); } else { return ((Local) o).getName() == null && ((Local) o).getType() == null; } } return false;
317
198
515
<methods>public void <init>(java.lang.String, soot.Type) ,public void apply(soot.util.Switch) ,public java.lang.Object clone() ,public void convertToBaf(soot.jimple.JimpleToBafContext, List<soot.Unit>) ,public int equivHashCode() ,public boolean equivTo(java.lang.Object) ,public java.lang.String getName() ,public final int getNumber() ,public soot.Type getType() ,public final List<soot.ValueBox> getUseBoxes() ,public boolean isStackLocal() ,public void setName(java.lang.String) ,public void setNumber(int) ,public void setType(soot.Type) ,public java.lang.String toString() ,public void toString(soot.UnitPrinter) <variables>protected java.lang.String name,private volatile int number,protected soot.Type type
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/infoflow/SimpleMethodLocalObjectsAnalysis.java
SimpleMethodLocalObjectsAnalysis
isObjectLocal
class SimpleMethodLocalObjectsAnalysis extends SimpleMethodInfoFlowAnalysis { private static final Logger logger = LoggerFactory.getLogger(SimpleMethodLocalObjectsAnalysis.class); public static int mlocounter = 0; public SimpleMethodLocalObjectsAnalysis(UnitGraph g, ClassLocalObjectsAnalysis cloa, InfoFlowAnalysis dfa) { super(g, dfa, true, true); // special version doesn't run analysis yet mlocounter++; printMessages = false; SootMethod method = g.getBody().getMethod(); AbstractDataSource sharedDataSource = new AbstractDataSource(new String("SHARED")); // Add a source for every parameter that is shared for (int i = 0; i < method.getParameterCount(); i++) // no need to worry about return value... { EquivalentValue paramEqVal = InfoFlowAnalysis.getNodeForParameterRef(method, i); if (!cloa.parameterIsLocal(method, paramEqVal)) { addToEntryInitialFlow(sharedDataSource, paramEqVal.getValue()); addToNewInitialFlow(sharedDataSource, paramEqVal.getValue()); } } for (SootField sf : cloa.getSharedFields()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(method, sf); addToEntryInitialFlow(sharedDataSource, fieldRefEqVal.getValue()); addToNewInitialFlow(sharedDataSource, fieldRefEqVal.getValue()); } if (printMessages) { logger.debug("----- STARTING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } doFlowInsensitiveAnalysis(); if (printMessages) { logger.debug("----- ENDING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } } public SimpleMethodLocalObjectsAnalysis(UnitGraph g, CallLocalityContext context, InfoFlowAnalysis dfa) { super(g, dfa, true, true); // special version doesn't run analysis yet mlocounter++; printMessages = false; SootMethod method = g.getBody().getMethod(); AbstractDataSource sharedDataSource = new AbstractDataSource(new String("SHARED")); List<Object> sharedRefs = context.getSharedRefs(); Iterator<Object> sharedRefEqValIt = sharedRefs.iterator(); // returns a list of (correctly structured) EquivalentValue // wrapped refs that should be // treated as shared while (sharedRefEqValIt.hasNext()) { EquivalentValue refEqVal = (EquivalentValue) sharedRefEqValIt.next(); addToEntryInitialFlow(sharedDataSource, refEqVal.getValue()); addToNewInitialFlow(sharedDataSource, refEqVal.getValue()); } if (printMessages) { logger.debug("----- STARTING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); logger.debug(" " + context.toString().replaceAll("\n", "\n ")); logger.debug("found " + sharedRefs.size() + " shared refs in context."); } doFlowInsensitiveAnalysis(); if (printMessages) { logger.debug("----- ENDING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } } // Interesting sources are summarized (and possibly printed) public boolean isInterestingSource(Value source) { return (source instanceof AbstractDataSource); } // Interesting sinks are possibly printed public boolean isInterestingSink(Value sink) { return true; // (sink instanceof Local); // we're interested in all values } // public boolean isObjectLocal(Value local) // to this analysis of this method (which depends on context) {<FILL_FUNCTION_BODY>} }
EquivalentValue source = new CachedEquivalentValue(new AbstractDataSource(new String("SHARED"))); if (infoFlowGraph.containsNode(source)) { List sinks = infoFlowGraph.getSuccsOf(source); if (printMessages) { logger.debug(" Requested value " + local + " is " + (!sinks.contains(new CachedEquivalentValue(local)) ? "Local" : "Shared") + " in " + sm + " "); } return !sinks.contains(new CachedEquivalentValue(local)); } else { if (printMessages) { logger.debug(" Requested value " + local + " is Local (LIKE ALL VALUES) in " + sm + " "); } return true; // no shared data in this method }
1,001
204
1,205
<methods>public void <init>(soot.toolkits.graph.UnitGraph, soot.jimple.toolkits.infoflow.InfoFlowAnalysis, boolean) ,public void addToEntryInitialFlow(soot.Value, soot.Value) ,public void addToNewInitialFlow(soot.Value, soot.Value) ,public void doFlowInsensitiveAnalysis() ,public MutableDirectedGraph<soot.EquivalentValue> getMethodInfoFlowSummary() ,public soot.Value getThisLocal() ,public boolean isInterestingSink(soot.Value) ,public boolean isInterestingSource(soot.Value) ,public boolean isTrackableSink(soot.Value) ,public boolean isTrackableSource(soot.Value) <variables>public static int counter,soot.jimple.toolkits.infoflow.InfoFlowAnalysis dfa,FlowSet<Pair<soot.EquivalentValue,soot.EquivalentValue>> emptySet,FlowSet<Pair<soot.EquivalentValue,soot.EquivalentValue>> entrySet,MutableDirectedGraph<soot.EquivalentValue> infoFlowGraph,private static final org.slf4j.Logger logger,boolean printMessages,boolean refOnly,soot.jimple.Ref returnRef,soot.SootMethod sm,soot.Value thisLocal
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/invoke/ThrowManager.java
ThrowManager
addThrowAfter
class ThrowManager { /** * Iterate through the statements in b (starting at the end), returning the last instance of the following pattern: * * <code> * r928 = new java.lang.NullPointerException; specialinvoke r928."<init>"(); throw r928; * </code> * * Creates if necessary. */ public static Stmt getNullPointerExceptionThrower(JimpleBody b) { return getNullPointerExceptionThrower((Body) b); } /** * Iterate through the statements in b (starting at the end), returning the last instance of the following pattern: * * <code> * r928 = new java.lang.NullPointerException; specialinvoke r928."<init>"(); throw r928; * </code> * * Creates if necessary. */ public static Stmt getNullPointerExceptionThrower(ShimpleBody b) { return getNullPointerExceptionThrower((Body) b); } static Stmt getNullPointerExceptionThrower(Body b) { assert (b instanceof JimpleBody || b instanceof ShimpleBody); final Set<Unit> trappedUnits = TrapManager.getTrappedUnitsOf(b); final Chain<Unit> units = b.getUnits(); final Unit first = units.getFirst(); final Stmt last = (Stmt) units.getLast(); for (Stmt s = last; s != first; s = (Stmt) units.getPredOf(s)) { if (!trappedUnits.contains(s) && s instanceof ThrowStmt) { Value throwee = ((ThrowStmt) s).getOp(); if (throwee instanceof Constant) { continue; } if (s == first) { break; } Stmt prosInvoke = (Stmt) units.getPredOf(s); if (!(prosInvoke instanceof InvokeStmt)) { continue; } if (prosInvoke == first) { break; } Stmt prosNew = (Stmt) units.getPredOf(prosInvoke); if (!(prosNew instanceof AssignStmt)) { continue; } InvokeExpr ie = ((InvokeStmt) prosInvoke).getInvokeExpr(); if (!(ie instanceof SpecialInvokeExpr) || ((SpecialInvokeExpr) ie).getBase() != throwee || !"<init>".equals(ie.getMethodRef().name())) { continue; } Value ro = ((AssignStmt) prosNew).getRightOp(); if (((AssignStmt) prosNew).getLeftOp() != throwee || !(ro instanceof NewExpr) || !((NewExpr) ro).getBaseType().equals(RefType.v("java.lang.NullPointerException"))) { continue; } // Whew! return prosNew; } } // Create. return addThrowAfter(b.getLocals(), units, last); } static Stmt addThrowAfter(JimpleBody b, Stmt target) { return addThrowAfter(b.getLocals(), b.getUnits(), target); } static Stmt addThrowAfter(ShimpleBody b, Stmt target) { return addThrowAfter(b.getLocals(), b.getUnits(), target); } static Stmt addThrowAfter(Chain<Local> locals, Chain<Unit> units, Stmt target) {<FILL_FUNCTION_BODY>} /** * If exception e is caught at stmt s in body b, return the handler; otherwise, return null. */ static boolean isExceptionCaughtAt(SootClass e, Stmt stmt, Body b) { // Look through the traps t of b, checking to see if (1) caught exception // is e and (2) stmt lies between t.beginUnit and t.endUnit Hierarchy h = new Hierarchy(); for (Trap t : b.getTraps()) { /* Ah ha, we might win. */ if (h.isClassSubclassOfIncluding(e, t.getException())) { for (Iterator<Unit> it = b.getUnits().iterator(t.getBeginUnit(), t.getEndUnit()); it.hasNext();) { if (stmt.equals(it.next())) { return true; } } } } return false; } }
int i = 0; boolean canAddI; do { canAddI = true; String name = "__throwee" + i; for (Local l : locals) { if (name.equals(l.getName())) { canAddI = false; } } if (!canAddI) { i++; } } while (!canAddI); final Jimple jimp = Jimple.v(); Local l = jimp.newLocal("__throwee" + i, RefType.v("java.lang.NullPointerException")); locals.add(l); Stmt newStmt = jimp.newAssignStmt(l, jimp.newNewExpr(RefType.v("java.lang.NullPointerException"))); Stmt invStmt = jimp.newInvokeStmt( jimp.newSpecialInvokeExpr(l, Scene.v().getMethod("<java.lang.NullPointerException: void <init>()>").makeRef())); Stmt throwStmt = jimp.newThrowStmt(l); units.insertAfter(newStmt, target); units.insertAfter(invStmt, newStmt); units.insertAfter(throwStmt, invStmt); return newStmt;
1,161
327
1,488
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/CodeBlockRWSet.java
CodeBlockRWSet
toString
class CodeBlockRWSet extends MethodRWSet { @Override public String toString() {<FILL_FUNCTION_BODY>} /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { if (other == null || isFull) { return false; } boolean ret = false; if (other instanceof MethodRWSet) { MethodRWSet o = (MethodRWSet) other; if (o.getCallsNative()) { ret = !getCallsNative() | ret; setCallsNative(); } if (o.isFull) { ret = !isFull | ret; isFull = true; if (true) { throw new RuntimeException("attempt to add full set " + o + " into " + this); } globals = null; fields = null; return ret; } if (o.globals != null) { if (globals == null) { globals = new HashSet<SootField>(); } ret = globals.addAll(o.globals) | ret; if (globals.size() > MAX_SIZE) { globals = null; isFull = true; throw new RuntimeException("attempt to add full set " + o + " into " + this); } } if (o.fields != null) { for (Object field : o.fields.keySet()) { ret = addFieldRef(o.getBaseForField(field), field) | ret; } } } else if (other instanceof StmtRWSet) { StmtRWSet oth = (StmtRWSet) other; if (oth.base != null) { ret = addFieldRef(oth.base, oth.field) | ret; } else if (oth.field != null) { ret = addGlobal((SootField) oth.field) | ret; } } else if (other instanceof SiteRWSet) { SiteRWSet oth = (SiteRWSet) other; for (RWSet set : oth.sets) { this.union(set); } } if (!getCallsNative() && other.getCallsNative()) { setCallsNative(); return true; } return ret; } public boolean containsField(Object field) { return fields != null && fields.containsKey(field); } public CodeBlockRWSet intersection(MethodRWSet other) { // May run slowly... O(n^2) CodeBlockRWSet ret = new CodeBlockRWSet(); if (isFull) { return ret; } if (globals != null && other.globals != null && !globals.isEmpty() && !other.globals.isEmpty()) { for (SootField sg : other.globals) { if (globals.contains(sg)) { ret.addGlobal(sg); } } } if (fields != null && other.fields != null && !fields.isEmpty() && !other.fields.isEmpty()) { for (Object field : other.fields.keySet()) { if (fields.containsKey(field)) { PointsToSet pts1 = getBaseForField(field); PointsToSet pts2 = other.getBaseForField(field); if (pts1 instanceof FullObjectSet) { ret.addFieldRef(pts2, field); } else if (pts2 instanceof FullObjectSet) { ret.addFieldRef(pts1, field); } else if (pts1.hasNonEmptyIntersection(pts2)) { if ((pts1 instanceof PointsToSetInternal) && (pts2 instanceof PointsToSetInternal)) { final PointsToSetInternal pti1 = (PointsToSetInternal) pts1; final PointsToSetInternal pti2 = (PointsToSetInternal) pts2; final PointsToSetInternal newpti = new HashPointsToSet(pti1.getType(), (PAG) Scene.v().getPointsToAnalysis()); pti1.forall(new P2SetVisitor() { @Override public void visit(Node n) { if (pti2.contains(n)) { newpti.add(n); } } }); ret.addFieldRef(newpti, field); } } } } } return ret; } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { boolean ret = false; if (fields == null) { fields = new HashMap<Object, PointsToSet>(); } // Get our points-to set, merge with other PointsToSet base = getBaseForField(field); if (base instanceof FullObjectSet) { return false; } if (otherBase instanceof FullObjectSet) { fields.put(field, otherBase); return true; } if (otherBase.equals(base)) { return false; } if (base == null) { // NOTE: this line makes unsafe assumptions about the PTA base = new HashPointsToSet(((PointsToSetInternal) otherBase).getType(), (PAG) Scene.v().getPointsToAnalysis()); fields.put(field, base); } return ((PointsToSetInternal) base).addAll((PointsToSetInternal) otherBase, null) | ret; } }
StringBuilder ret = new StringBuilder(); boolean empty = true; if (fields != null) { for (Map.Entry<Object, PointsToSet> e : fields.entrySet()) { ret.append("[Field: ").append(e.getKey()).append(' '); PointsToSet baseObj = e.getValue(); if (baseObj instanceof PointsToSetInternal) { /* * PointsToSetInternal base = (PointsToSetInternal) fields.get(field); base.forall( new P2SetVisitor() { public * void visit( Node n ) { ret.append(n.getNumber() + " "); } } ); */ int baseSize = ((PointsToSetInternal) baseObj).size(); ret.append(baseSize).append(baseSize == 1 ? " Node]\n" : " Nodes]\n"); } else { ret.append(baseObj).append("]\n"); } empty = false; } } if (globals != null) { for (SootField global : globals) { ret.append("[Global: ").append(global).append("]\n"); empty = false; } } if (empty) { ret.append("[emptyset]\n"); } return ret.toString();
1,436
331
1,767
<methods>public void <init>() ,public boolean addFieldRef(soot.PointsToSet, java.lang.Object) ,public boolean addGlobal(soot.SootField) ,public soot.PointsToSet getBaseForField(java.lang.Object) ,public boolean getCallsNative() ,public Set<java.lang.Object> getFields() ,public Set<soot.SootField> getGlobals() ,public boolean hasNonEmptyIntersection(soot.jimple.toolkits.pointer.RWSet) ,public boolean isEquivTo(soot.jimple.toolkits.pointer.RWSet) ,public boolean setCallsNative() ,public int size() ,public java.lang.String toString() ,public boolean union(soot.jimple.toolkits.pointer.RWSet) <variables>public static final int MAX_SIZE,protected boolean callsNative,public Map<java.lang.Object,soot.PointsToSet> fields,public Set<soot.SootField> globals,protected boolean isFull,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/DependenceGraph.java
Edge
addEdge
class Edge { final short from; final short to; public Edge(short from, short to) { this.from = from; this.to = to; } @Override public int hashCode() { return (this.from << 16) + this.to; } @Override public boolean equals(Object other) { Edge o = (Edge) other; return this.from == o.from && this.to == o.to; } } public boolean areAdjacent(short from, short to) { if (from > to) { return areAdjacent(to, from); } if (from < 0 || to < 0) { return false; } if (from == to) { return true; } return edges.contains(new Edge(from, to)); } public void addEdge(short from, short to) {<FILL_FUNCTION_BODY>
if (from < 0) { throw new RuntimeException("from < 0"); } if (to < 0) { throw new RuntimeException("to < 0"); } if (from > to) { addEdge(to, from); return; } edges.add(new Edge(from, to));
252
87
339
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/DumbPointerAnalysis.java
DumbPointerAnalysis
reachingObjects
class DumbPointerAnalysis implements PointsToAnalysis { public DumbPointerAnalysis(Singletons.Global g) { } public static DumbPointerAnalysis v() { return G.v().soot_jimple_toolkits_pointer_DumbPointerAnalysis(); } /** Returns the set of objects pointed to by variable l. */ @Override public PointsToSet reachingObjects(Local l) {<FILL_FUNCTION_BODY>} /** Returns the set of objects pointed to by variable l in context c. */ @Override public PointsToSet reachingObjects(Context c, Local l) { return reachingObjects(l); } /** Returns the set of objects pointed to by static field f. */ @Override public PointsToSet reachingObjects(SootField f) { Type t = f.getType(); return (t instanceof RefType) ? FullObjectSet.v((RefType) t) : FullObjectSet.v(); } /** * Returns the set of objects pointed to by instance field f of the objects in the PointsToSet s. */ @Override public PointsToSet reachingObjects(PointsToSet s, SootField f) { return reachingObjects(f); } /** * Returns the set of objects pointed to by instance field f of the objects pointed to by l. */ @Override public PointsToSet reachingObjects(Local l, SootField f) { return reachingObjects(f); } /** * Returns the set of objects pointed to by instance field f of the objects pointed to by l in context c. */ @Override public PointsToSet reachingObjects(Context c, Local l, SootField f) { return reachingObjects(f); } /** * Returns the set of objects pointed to by elements of the arrays in the PointsToSet s. */ @Override public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) { return FullObjectSet.v(); } }
Type t = l.getType(); if (t instanceof RefType) { return FullObjectSet.v((RefType) t); } if (t instanceof PrimType) { return FullObjectSet.v((PrimType) t); } return FullObjectSet.v();
514
76
590
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/FieldRWTagger.java
UniqueRWSets
getUnique
class UniqueRWSets implements Iterable<RWSet> { protected final ArrayList<RWSet> l = new ArrayList<RWSet>(); RWSet getUnique(RWSet s) {<FILL_FUNCTION_BODY>} @Override public Iterator<RWSet> iterator() { return l.iterator(); } short indexOf(RWSet s) { short i = 0; for (RWSet ret : l) { if (ret.isEquivTo(s)) { return i; } i++; } return -1; } }
if (s != null) { for (RWSet ret : l) { if (ret.isEquivTo(s)) { return ret; } } l.add(s); } return s;
167
66
233
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/InstanceKey.java
InstanceKey
mayNotAlias
class InstanceKey { protected final Local assignedLocal; protected final LocalMustAliasAnalysis lmaa; protected final LocalMustNotAliasAnalysis lnma; protected final Stmt stmtAfterAssignStmt; protected final SootMethod owner; protected final int hashCode; protected final PointsToSet pts; /** * Creates a new instance key representing the value stored in local, just before stmt. The identity of the key is defined * via lmaa, and its must-not-alias relationship to other keys via lmna. * * @param local * the local variable whose value this key represents * @param stmt * the statement at which this key represents the value * @param owner * the method containing local * @param lmaa * a {@link LocalMustAliasAnalysis} * @param lmna * a {@link LocalMustNotAliasAnalysis} */ public InstanceKey(Local local, Stmt stmt, SootMethod owner, LocalMustAliasAnalysis lmaa, LocalMustNotAliasAnalysis lmna) { this.assignedLocal = local; this.owner = owner; this.stmtAfterAssignStmt = stmt; this.lmaa = lmaa; this.lnma = lmna; PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); this.pts = new PointsToSetEqualsWrapper((EqualsSupportingPointsToSet) pta.reachingObjects(local)); this.hashCode = computeHashCode(); } public boolean mustAlias(InstanceKey otherKey) { if (stmtAfterAssignStmt == null || otherKey.stmtAfterAssignStmt == null) { // don't know return false; } return lmaa.mustAlias(assignedLocal, stmtAfterAssignStmt, otherKey.assignedLocal, otherKey.stmtAfterAssignStmt); } public boolean mayNotAlias(InstanceKey otherKey) {<FILL_FUNCTION_BODY>} public PointsToSet getPointsToSet() { return pts; } public Local getLocal() { return assignedLocal; } public boolean haveLocalInformation() { return stmtAfterAssignStmt != null; } @Override public String toString() { String instanceKeyString = stmtAfterAssignStmt != null ? lmaa.instanceKeyString(assignedLocal, stmtAfterAssignStmt) : "pts(" + hashCode + ")"; return instanceKeyString + "(" + assignedLocal.getName() + ")"; } /** * {@inheritDoc} */ @Override public int hashCode() { return hashCode; } /** * (Pre)computes the hash code. */ protected int computeHashCode() { final int prime = 31; int result = 1; result = prime * result + ((owner == null) ? 0 : owner.hashCode()); if (stmtAfterAssignStmt != null && (assignedLocal.getType() instanceof RefLikeType)) { // compute hash code based on instance key string result = prime * result + lmaa.instanceKeyString(assignedLocal, stmtAfterAssignStmt).hashCode(); } else if (stmtAfterAssignStmt == null) { result = prime * result + pts.hashCode(); } return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final InstanceKey other = (InstanceKey) obj; if (this.owner == null) { if (other.owner != null) { return false; } } else if (!this.owner.equals(other.owner)) { return false; } // two keys are equal if they must alias if (mustAlias(other)) { return true; } // or if both have no statement set but the same local return (this.stmtAfterAssignStmt == null && other.stmtAfterAssignStmt == null && this.pts.equals(other.pts)); } public boolean isOfReferenceType() { assert assignedLocal.getType() instanceof RefLikeType; return true; } public SootMethod getOwner() { return owner; } public Stmt getStmt() { return stmtAfterAssignStmt; } }
if (owner.equals(otherKey.owner) && stmtAfterAssignStmt != null && otherKey.stmtAfterAssignStmt != null) { if (lnma.notMayAlias(assignedLocal, stmtAfterAssignStmt, otherKey.assignedLocal, otherKey.stmtAfterAssignStmt)) { return true; } } // different methods or local not-may-alias was not successful: get points-to info if (Scene.v().getPointsToAnalysis() == null) { // no info; hence don't know for sure return false; } else { // may not alias if we have an empty intersection return !pts.hasNonEmptyIntersection(otherKey.pts); }
1,200
191
1,391
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/MemoryEfficientRasUnion.java
MemoryEfficientRasUnion
hasNonEmptyIntersection
class MemoryEfficientRasUnion extends Union { HashSet<PointsToSet> subsets; @Override public boolean isEmpty() { if (subsets != null) { for (PointsToSet subset : subsets) { if (!subset.isEmpty()) { return false; } } } return true; } @Override public boolean hasNonEmptyIntersection(PointsToSet other) {<FILL_FUNCTION_BODY>} @Override public boolean addAll(PointsToSet s) { if (subsets == null) { subsets = new HashSet<PointsToSet>(); } if (s instanceof MemoryEfficientRasUnion) { MemoryEfficientRasUnion meru = (MemoryEfficientRasUnion) s; if (meru.subsets == null || this.subsets.containsAll(meru.subsets)) { return false; } return this.subsets.addAll(meru.subsets); } else { return this.subsets.add(s); } } @Override public Object clone() { MemoryEfficientRasUnion ret = new MemoryEfficientRasUnion(); ret.addAll(this); return ret; } @Override public Set<Type> possibleTypes() { if (subsets == null) { return Collections.emptySet(); } else { HashSet<Type> ret = new HashSet<Type>(); for (PointsToSet subset : subsets) { ret.addAll(subset.possibleTypes()); } return ret; } } /** * {@inheritDoc} */ @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((subsets == null) ? 0 : subsets.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final MemoryEfficientRasUnion other = (MemoryEfficientRasUnion) obj; if (this.subsets == null) { if (other.subsets != null) { return false; } } else if (!this.subsets.equals(other.subsets)) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { return (subsets == null) ? "[]" : subsets.toString(); } }
if (subsets == null) { return true; } for (PointsToSet subset : subsets) { if (other instanceof Union) { if (other.hasNonEmptyIntersection(subset)) { return true; } } else { if (subset.hasNonEmptyIntersection(other)) { return true; } } } return false;
715
104
819
<methods>public non-sealed void <init>() ,public abstract boolean addAll(soot.PointsToSet) ,public static boolean hasNonEmptyIntersection(soot.PointsToSet, soot.PointsToSet) ,public Set<soot.jimple.ClassConstant> possibleClassConstants() ,public Set<java.lang.String> possibleStringConstants() <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/PASideEffectTester.java
PASideEffectTester
writeSet
class PASideEffectTester implements SideEffectTester { private final PointsToAnalysis pa = Scene.v().getPointsToAnalysis(); private final SideEffectAnalysis sea = Scene.v().getSideEffectAnalysis(); private HashMap<Unit, RWSet> unitToRead; private HashMap<Unit, RWSet> unitToWrite; private HashMap<Local, PointsToSet> localToReachingObjects; private SootMethod currentMethod; public PASideEffectTester() { if (G.v().Union_factory == null) { G.v().Union_factory = new UnionFactory() { @Override public Union newUnion() { return FullObjectSet.v(); } }; } } /** Call this when starting to analyze a new method to setup the cache. */ @Override public void newMethod(SootMethod m) { this.unitToRead = new HashMap<Unit, RWSet>(); this.unitToWrite = new HashMap<Unit, RWSet>(); this.localToReachingObjects = new HashMap<Local, PointsToSet>(); this.currentMethod = m; this.sea.findNTRWSets(m); } protected RWSet readSet(Unit u) { RWSet ret = unitToRead.get(u); if (ret == null) { unitToRead.put(u, ret = sea.readSet(currentMethod, (Stmt) u)); } return ret; } protected RWSet writeSet(Unit u) {<FILL_FUNCTION_BODY>} protected PointsToSet reachingObjects(Local l) { PointsToSet ret = localToReachingObjects.get(l); if (ret == null) { localToReachingObjects.put(l, ret = pa.reachingObjects(l)); } return ret; } /** * Returns true if the unit can read from v. Does not deal with expressions; deals with Refs. */ @Override public boolean unitCanReadFrom(Unit u, Value v) { return valueTouchesRWSet(readSet(u), v, u.getUseBoxes()); } /** * Returns true if the unit can read from v. Does not deal with expressions; deals with Refs. */ @Override public boolean unitCanWriteTo(Unit u, Value v) { return valueTouchesRWSet(writeSet(u), v, u.getDefBoxes()); } protected boolean valueTouchesRWSet(RWSet s, Value v, List<ValueBox> boxes) { for (ValueBox use : v.getUseBoxes()) { if (valueTouchesRWSet(s, use.getValue(), boxes)) { return true; } } // This doesn't really make any sense, but we need to return something. if (v instanceof Constant) { return false; } else if (v instanceof Expr) { throw new RuntimeException("can't deal with expr"); } for (ValueBox box : boxes) { if (box.getValue().equivTo(v)) { return true; } } if (v instanceof Local) { return false; } else if (v instanceof InstanceFieldRef) { if (s == null) { return false; } InstanceFieldRef ifr = (InstanceFieldRef) v; PointsToSet o1 = s.getBaseForField(ifr.getField()); if (o1 == null) { return false; } PointsToSet o2 = reachingObjects((Local) ifr.getBase()); if (o2 == null) { return false; } return o1.hasNonEmptyIntersection(o2); } else if (v instanceof ArrayRef) { if (s == null) { return false; } PointsToSet o1 = s.getBaseForField(PointsToAnalysis.ARRAY_ELEMENTS_NODE); if (o1 == null) { return false; } ArrayRef ar = (ArrayRef) v; PointsToSet o2 = reachingObjects((Local) ar.getBase()); if (o2 == null) { return false; } return o1.hasNonEmptyIntersection(o2); } else if (v instanceof StaticFieldRef) { if (s == null) { return false; } StaticFieldRef sfr = (StaticFieldRef) v; return s.getGlobals().contains(sfr.getField()); } throw new RuntimeException("Forgot to handle value " + v); } }
RWSet ret = unitToWrite.get(u); if (ret == null) { unitToWrite.put(u, ret = sea.writeSet(currentMethod, (Stmt) u)); } return ret;
1,210
61
1,271
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/SideEffectAnalysis.java
SideEffectAnalysis
findNTRWSets
class SideEffectAnalysis { private final Map<SootMethod, MethodRWSet> methodToNTReadSet = new HashMap<SootMethod, MethodRWSet>(); private final Map<SootMethod, MethodRWSet> methodToNTWriteSet = new HashMap<SootMethod, MethodRWSet>(); private final PointsToAnalysis pa; private final CallGraph cg; private final TransitiveTargets tt; private SideEffectAnalysis(PointsToAnalysis pa, CallGraph cg, TransitiveTargets tt) { if (G.v().Union_factory == null) { G.v().Union_factory = new UnionFactory() { @Override public Union newUnion() { return FullObjectSet.v(); } }; } this.pa = pa; this.cg = cg; this.tt = tt; } public SideEffectAnalysis(PointsToAnalysis pa, CallGraph cg) { this(pa, cg, new TransitiveTargets(cg)); } public SideEffectAnalysis(PointsToAnalysis pa, CallGraph cg, Filter filter) { // This constructor allows customization of call graph edges to // consider via the use of a transitive targets filter. // For example, using the NonClinitEdgesPred, you can create a // SideEffectAnalysis that will ignore static initializers // - R. Halpert 2006-12-02 this(pa, cg, new TransitiveTargets(cg, filter)); } public void findNTRWSets(SootMethod method) {<FILL_FUNCTION_BODY>} public RWSet nonTransitiveReadSet(SootMethod method) { findNTRWSets(method); return methodToNTReadSet.get(method); } public RWSet nonTransitiveWriteSet(SootMethod method) { findNTRWSets(method); return methodToNTWriteSet.get(method); } private RWSet ntReadSet(SootMethod method, Stmt stmt) { if (stmt instanceof AssignStmt) { return addValue(((AssignStmt) stmt).getRightOp(), method, stmt); } else { return null; } } public RWSet readSet(SootMethod method, Stmt stmt) { RWSet ret = null; for (Iterator<MethodOrMethodContext> targets = tt.iterator(stmt); targets.hasNext();) { SootMethod target = (SootMethod) targets.next(); if (target.isNative()) { if (ret == null) { ret = new SiteRWSet(); } ret.setCallsNative(); } else if (target.isConcrete()) { RWSet ntr = nonTransitiveReadSet(target); if (ntr != null) { if (ret == null) { ret = new SiteRWSet(); } ret.union(ntr); } } } if (ret == null) { return ntReadSet(method, stmt); } else { ret.union(ntReadSet(method, stmt)); return ret; } } private RWSet ntWriteSet(SootMethod method, Stmt stmt) { if (stmt instanceof AssignStmt) { return addValue(((AssignStmt) stmt).getLeftOp(), method, stmt); } else { return null; } } public RWSet writeSet(SootMethod method, Stmt stmt) { RWSet ret = null; for (Iterator<MethodOrMethodContext> targets = tt.iterator(stmt); targets.hasNext();) { SootMethod target = (SootMethod) targets.next(); if (target.isNative()) { if (ret == null) { ret = new SiteRWSet(); } ret.setCallsNative(); } else if (target.isConcrete()) { RWSet ntw = nonTransitiveWriteSet(target); if (ntw != null) { if (ret == null) { ret = new SiteRWSet(); } ret.union(ntw); } } } if (ret == null) { return ntWriteSet(method, stmt); } else { ret.union(ntWriteSet(method, stmt)); return ret; } } protected RWSet addValue(Value v, SootMethod m, Stmt s) { RWSet ret = null; if (v instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) v; PointsToSet base = pa.reachingObjects((Local) ifr.getBase()); ret = new StmtRWSet(); ret.addFieldRef(base, ifr.getField()); } else if (v instanceof StaticFieldRef) { StaticFieldRef sfr = (StaticFieldRef) v; ret = new StmtRWSet(); ret.addGlobal(sfr.getField()); } else if (v instanceof ArrayRef) { ArrayRef ar = (ArrayRef) v; PointsToSet base = pa.reachingObjects((Local) ar.getBase()); ret = new StmtRWSet(); ret.addFieldRef(base, PointsToAnalysis.ARRAY_ELEMENTS_NODE); } return ret; } @Override public String toString() { return "SideEffectAnalysis: PA=" + pa + " CG=" + cg; } }
if (methodToNTReadSet.containsKey(method) && methodToNTWriteSet.containsKey(method)) { return; } MethodRWSet read = null; MethodRWSet write = null; for (Unit next : method.retrieveActiveBody().getUnits()) { final Stmt s = (Stmt) next; RWSet ntr = ntReadSet(method, s); if (ntr != null) { if (read == null) { read = new MethodRWSet(); } read.union(ntr); } RWSet ntw = ntWriteSet(method, s); if (ntw != null) { if (write == null) { write = new MethodRWSet(); } write.union(ntw); } } methodToNTReadSet.put(method, read); methodToNTWriteSet.put(method, write);
1,447
248
1,695
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/SideEffectTagger.java
UniqueRWSets
getUnique
class UniqueRWSets implements Iterable<RWSet> { protected ArrayList<RWSet> l = new ArrayList<RWSet>(); RWSet getUnique(RWSet s) {<FILL_FUNCTION_BODY>} @Override public Iterator<RWSet> iterator() { return l.iterator(); } short indexOf(RWSet s) { short i = 0; for (RWSet ret : l) { if (ret.isEquivTo(s)) { return i; } i++; } return -1; } }
if (s == null) { return s; } for (RWSet ret : l) { if (ret.isEquivTo(s)) { return ret; } } l.add(s); return s;
166
70
236
<methods>public non-sealed void <init>() ,public final void transform(soot.Body, java.lang.String, Map<java.lang.String,java.lang.String>) ,public final void transform(soot.Body, java.lang.String) ,public final void transform(soot.Body) <variables>private static final Map<java.lang.String,java.lang.String> enabledOnlyMap
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/SiteRWSet.java
SiteRWSet
toString
class SiteRWSet extends RWSet { public HashSet<RWSet> sets = new HashSet<RWSet>(); protected boolean callsNative = false; @Override public int size() { Set globals = getGlobals(); Set fields = getFields(); if (globals == null) { return (fields == null) ? 0 : fields.size(); } else if (fields == null) { return globals.size(); } else { return globals.size() + fields.size(); } } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean getCallsNative() { return callsNative; } @Override public boolean setCallsNative() { boolean ret = !callsNative; callsNative = true; return ret; } /** Returns an iterator over any globals read/written. */ @Override public Set<Object> getGlobals() { HashSet<Object> ret = new HashSet<Object>(); for (RWSet s : sets) { ret.addAll(s.getGlobals()); } return ret; } /** Returns an iterator over any fields read/written. */ @Override public Set<Object> getFields() { HashSet<Object> ret = new HashSet<Object>(); for (RWSet s : sets) { ret.addAll(s.getFields()); } return ret; } /** Returns a set of base objects whose field f is read/written. */ @Override public PointsToSet getBaseForField(Object f) { Union ret = null; for (RWSet s : sets) { PointsToSet os = s.getBaseForField(f); if (os == null || os.isEmpty()) { continue; } if (ret == null) { ret = G.v().Union_factory.newUnion(); } ret.addAll(os); } return ret; } @Override public boolean hasNonEmptyIntersection(RWSet oth) { if (sets.contains(oth)) { return true; } for (RWSet s : sets) { if (oth.hasNonEmptyIntersection(s)) { return true; } } return false; } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { if (other == null) { return false; } boolean ret = false; if (other.getCallsNative()) { ret = setCallsNative(); } if (other.getFields().isEmpty() && other.getGlobals().isEmpty()) { return ret; } return sets.add(other) | ret; } @Override public boolean addGlobal(SootField global) { throw new RuntimeException("Not implemented; try MethodRWSet"); } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { throw new RuntimeException("Not implemented; try MethodRWSet"); } @Override public boolean isEquivTo(RWSet other) { if (!(other instanceof SiteRWSet)) { return false; } SiteRWSet o = (SiteRWSet) other; if (o.callsNative != this.callsNative) { return false; } return o.sets.equals(this.sets); } }
StringBuilder ret = new StringBuilder("SiteRWSet: "); boolean empty = true; for (RWSet key : sets) { ret.append(key.toString()); empty = false; } if (empty) { ret.append("empty"); } return ret.toString();
936
82
1,018
<methods>public non-sealed void <init>() ,public abstract boolean addFieldRef(soot.PointsToSet, java.lang.Object) ,public abstract boolean addGlobal(soot.SootField) ,public abstract soot.PointsToSet getBaseForField(java.lang.Object) ,public abstract boolean getCallsNative() ,public abstract Set<?> getFields() ,public abstract Set<?> getGlobals() ,public abstract boolean hasNonEmptyIntersection(soot.jimple.toolkits.pointer.RWSet) ,public abstract boolean isEquivTo(soot.jimple.toolkits.pointer.RWSet) ,public abstract boolean setCallsNative() ,public abstract int size() ,public abstract boolean union(soot.jimple.toolkits.pointer.RWSet) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/StmtRWSet.java
StmtRWSet
isEquivTo
class StmtRWSet extends RWSet { protected Object field; protected PointsToSet base; protected boolean callsNative = false; @Override public String toString() { return "[Field: " + field + base + "]\n"; } @Override public int size() { Set globals = getGlobals(); Set fields = getFields(); if (globals == null) { return (fields == null) ? 0 : fields.size(); } else if (fields == null) { return globals.size(); } else { return globals.size() + fields.size(); } } @Override public boolean getCallsNative() { return callsNative; } @Override public boolean setCallsNative() { boolean ret = !callsNative; callsNative = true; return ret; } /** Returns an iterator over any globals read/written. */ @Override public Set<Object> getGlobals() { return (base == null) ? Collections.singleton(field) : Collections.emptySet(); } /** Returns an iterator over any fields read/written. */ @Override public Set<Object> getFields() { return (base != null) ? Collections.singleton(field) : Collections.emptySet(); } /** Returns a set of base objects whose field f is read/written. */ @Override public PointsToSet getBaseForField(Object f) { return field.equals(f) ? base : null; } @Override public boolean hasNonEmptyIntersection(RWSet other) { if (field == null) { return false; } if (other instanceof StmtRWSet) { StmtRWSet o = (StmtRWSet) other; if (!this.field.equals(o.field)) { return false; } else if (this.base == null) { return o.base == null; } else { return Union.hasNonEmptyIntersection(this.base, o.base); } } else if (other instanceof MethodRWSet) { if (this.base == null) { return other.getGlobals().contains(this.field); } else { return Union.hasNonEmptyIntersection(this.base, other.getBaseForField(this.field)); } } else { return other.hasNonEmptyIntersection(this); } } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { throw new RuntimeException("Can't do that"); } @Override public boolean addGlobal(SootField global) { if (field != null || base != null) { throw new RuntimeException("Can't do that"); } field = global; return true; } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { if (this.field != null || base != null) { throw new RuntimeException("Can't do that"); } this.field = field; base = otherBase; return true; } @Override public boolean isEquivTo(RWSet other) {<FILL_FUNCTION_BODY>} }
if (!(other instanceof StmtRWSet)) { return false; } StmtRWSet o = (StmtRWSet) other; if ((this.callsNative != o.callsNative) || !this.field.equals(o.field)) { return false; } if (this.base instanceof FullObjectSet && o.base instanceof FullObjectSet) { return true; } return this.base == o.base;
870
121
991
<methods>public non-sealed void <init>() ,public abstract boolean addFieldRef(soot.PointsToSet, java.lang.Object) ,public abstract boolean addGlobal(soot.SootField) ,public abstract soot.PointsToSet getBaseForField(java.lang.Object) ,public abstract boolean getCallsNative() ,public abstract Set<?> getFields() ,public abstract Set<?> getGlobals() ,public abstract boolean hasNonEmptyIntersection(soot.jimple.toolkits.pointer.RWSet) ,public abstract boolean isEquivTo(soot.jimple.toolkits.pointer.RWSet) ,public abstract boolean setCallsNative() ,public abstract int size() ,public abstract boolean union(soot.jimple.toolkits.pointer.RWSet) <variables>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/StrongLocalMustAliasAnalysis.java
StrongLocalMustAliasAnalysis
mustAlias
class StrongLocalMustAliasAnalysis extends LocalMustAliasAnalysis { protected final Set<Integer> invalidInstanceKeys; public StrongLocalMustAliasAnalysis(UnitGraph g) { super(g); this.invalidInstanceKeys = new HashSet<Integer>(); /* * Find all SCCs, then invalidate all instance keys for variable defined within an SCC. */ StronglyConnectedComponentsFast<Unit> sccAnalysis = new StronglyConnectedComponentsFast<Unit>(g); for (List<Unit> scc : sccAnalysis.getTrueComponents()) { for (Unit unit : scc) { for (ValueBox vb : unit.getDefBoxes()) { Value defValue = vb.getValue(); if (defValue instanceof Local) { Local defLocal = (Local) defValue; if (defLocal.getType() instanceof RefLikeType) { // if key is not already UNKNOWN invalidInstanceKeys.add(getFlowBefore(unit).get(defLocal)); // if key is not already UNKNOWN invalidInstanceKeys.add(getFlowAfter(unit).get(defLocal)); } } } } } } /** * {@inheritDoc} */ @Override public boolean mustAlias(Local l1, Stmt s1, Local l2, Stmt s2) {<FILL_FUNCTION_BODY>} /** * {@inheritDoc} */ @Override public String instanceKeyString(Local l, Stmt s) { return invalidInstanceKeys.contains(getFlowBefore(s).get(l)) ? "UNKNOWN" : super.instanceKeyString(l, s); } }
Integer l1n = getFlowBefore(s1).get(l1); Integer l2n = getFlowBefore(s2).get(l2); return l1n != null && l2n != null && !invalidInstanceKeys.contains(l1n) && !invalidInstanceKeys.contains(l2n) && l1n.equals(l2n);
435
94
529
<methods>public void <init>(soot.toolkits.graph.UnitGraph) ,public void <init>(soot.toolkits.graph.UnitGraph, boolean) ,public boolean hasInfoOn(soot.Local, soot.jimple.Stmt) ,public java.lang.String instanceKeyString(soot.Local, soot.jimple.Stmt) ,public boolean mustAlias(soot.Local, soot.jimple.Stmt, soot.Local, soot.jimple.Stmt) ,public static int parameterRefNumber(soot.jimple.ParameterRef) ,public static int thisRefNumber() <variables>protected soot.SootMethod container,protected Set<soot.Value> localsAndFieldRefs,protected transient Map<soot.Unit,Map<soot.Value,java.lang.Integer>> mergePointToValueToNumber,protected int nextNumber,protected transient Map<soot.Value,java.lang.Integer> rhsToNumber
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/Union.java
Union
hasNonEmptyIntersection
class Union implements PointsToSet { /** * Adds all objects in s into this union of sets, returning true if this union was changed. */ public abstract boolean addAll(PointsToSet s); public static boolean hasNonEmptyIntersection(PointsToSet s1, PointsToSet s2) {<FILL_FUNCTION_BODY>} @Override public Set<String> possibleStringConstants() { return null; } @Override public Set<ClassConstant> possibleClassConstants() { return null; } }
if (s1 == null) { return false; } if (s1 instanceof Union) { return s1.hasNonEmptyIntersection(s2); } if (s2 == null) { return false; } return s2.hasNonEmptyIntersection(s1);
142
82
224
<no_super_class>
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileInputStreamNative.java
JavaIoFileInputStreamNative
simulateMethod
class JavaIoFileInputStreamNative extends NativeMethodClass { public JavaIoFileInputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************ java.io.FileInputStream *****************/ /** * Following methods have NO side effects. * * private native void open(java.lang.String) throws java.io.FileNotFoundException; public native int read() throws * java.io.IOException; private native int readBytes(byte[], int, int) throws java.io.IOException; public native int * available() throws java.io.IOException; public native void close() throws java.io.IOException; private static native * void initIDs(); */ }
String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; }
240
43
283
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileOutputStreamNative.java
JavaIoFileOutputStreamNative
simulateMethod
class JavaIoFileOutputStreamNative extends NativeMethodClass { public JavaIoFileOutputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /*********************** java.io.FileOutputStream *****************/ /** * NO side effects, may throw exceptions. * * private native void open(java.lang.String) throws java.io.FileNotFoundException; private native void * openAppend(java.lang.String) throws java.io.FileNotFoundException; public native void write(int) throws * java.io.IOException; private native void writeBytes(byte[], int, int) throws java.io.IOException; public native void * close() throws java.io.IOException; private static native void initIDs(); */ }
String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; }
254
43
297
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileSystemNative.java
JavaIoFileSystemNative
simulateMethod
class JavaIoFileSystemNative extends NativeMethodClass { public JavaIoFileSystemNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************ java.io.FileSystem ***********************/ /** * Returns a variable pointing to the file system constant * * public static native java.io.FileSystem getFileSystem(); */ public void java_io_FileSystem_getFileSystem(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getFileSystemObject()); } }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.io.FileSystem getFileSystem()")) { java_io_FileSystem_getFileSystem(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
226
94
320
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoObjectOutputStreamNative.java
JavaIoObjectOutputStreamNative
simulateMethod
class JavaIoObjectOutputStreamNative extends NativeMethodClass { public JavaIoObjectOutputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /******************* java.io.ObjectOutputStream *******************/ /** * The object in field is retrieved out by field ID. * * private static native java.lang.Object getObjectFieldValue(java.lang.Object, long); */ public void java_io_ObjectOutputStream_getObjectFieldValue(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Following three native methods have no side effects. * * private static native void floatsToBytes(float[], int, byte[], int, int); private static native void * doublesToBytes(double[], int, byte[], int, int); private static native void getPrimitiveFieldValues(java.lang.Object, * long[], char[], byte[]); * * @see default(...) */ }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object getObjectFieldValue(java.lang.Object,long)")) { java_io_ObjectOutputStream_getObjectFieldValue(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
339
103
442
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoObjectStreamClassNative.java
JavaIoObjectStreamClassNative
simulateMethod
class JavaIoObjectStreamClassNative extends NativeMethodClass { public JavaIoObjectStreamClassNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} }
String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; }
113
43
156
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangClassLoaderNativeLibraryNative.java
JavaLangClassLoaderNativeLibraryNative
simulateMethod
class JavaLangClassLoaderNativeLibraryNative extends NativeMethodClass { public JavaLangClassLoaderNativeLibraryNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************** java.lang.ClassLoader$NativeLibrary ****************/ /** * NO side effects * * native void load(java.lang.String); native long find(java.lang.String); native void unload(); */ }
String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; }
179
43
222
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangFloatNative.java
JavaLangFloatNative
simulateMethod
class JavaLangFloatNative extends NativeMethodClass { public JavaLangFloatNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************** java.lang.Float ***********************/ /** * Following methods have no side effects. public static native int floatToIntBits(float); public static native int * floatToRawIntBits(float); public static native float intBitsToFloat(int); */ }
String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; }
182
43
225
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangPackageNative.java
JavaLangPackageNative
simulateMethod
class JavaLangPackageNative extends NativeMethodClass { public JavaLangPackageNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************** java.lang.Package *************************/ /** * This is an undocumented private native method, it returns the first (without caller) method's package. * * It should be formulated as a string constants. private static native java.lang.String * getSystemPackage0(java.lang.String); */ public void java_lang_Package_getSystemPackage0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * private static native java.lang.String getSystemPackages0()[]; */ public void java_lang_Package_getSystemPackages0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.String getSystemPackage0(java.lang.String)")) { java_lang_Package_getSystemPackage0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.String[] getSystemPackages0()")) { java_lang_Package_getSystemPackages0(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
342
154
496
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectArrayNative.java
JavaLangReflectArrayNative
simulateMethod
class JavaLangReflectArrayNative extends NativeMethodClass { public JavaLangReflectArrayNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************ java.lang.reflect.Array **********************/ /** * Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an * object if it has a primitive type. * * NOTE: @return = @param0[] * * public static native java.lang.Object get(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; */ public void java_lang_reflect_Array_get(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * @param0[] = @param1 * * public static native void set(java.lang.Object, int, java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; */ public void java_lang_reflect_Array_set(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Treat this method as * * @return = new A[]; * * private static native java.lang.Object newArray(java.lang.Class, int) throws * java.lang.NegativeArraySizeException; */ public void java_lang_reflect_Array_newArray(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Treat this method as * * @return = new A[][]; * * private static native java.lang.Object multiNewArray(java.lang.Class, int[]) throws * java.lang.IllegalArgumentException, java.lang.NegativeArraySizeException; */ public void java_lang_reflect_Array_multiNewArray(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Following native methods have no side effects. * * public static native int getLength(java.lang.Object) throws java.lang.IllegalArgumentException; * * public static native boolean getBoolean(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native byte getByte(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native char getChar(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native short getShort(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native int getInt(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native long getLong(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native float getFloat(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native double getDouble(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setBoolean(java.lang.Object, int, boolean) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setByte(java.lang.Object, int, byte) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setChar(java.lang.Object, int, char) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setShort(java.lang.Object, int, short) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setInt(java.lang.Object, int, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setLong(java.lang.Object, int, long) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setFloat(java.lang.Object, int, float) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setDouble(java.lang.Object, int, double) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * @see default(...) */ }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object get(java.lang.Object,int)")) { java_lang_reflect_Array_get(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void set(java.lang.Object,int,java.lang.Object)")) { java_lang_reflect_Array_set(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object newArray(java.lang.Class,int)")) { java_lang_reflect_Array_newArray(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object multiNewArray(java.lang.Class,int[])")) { java_lang_reflect_Array_multiNewArray(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
1,440
272
1,712
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectConstructorNative.java
JavaLangReflectConstructorNative
simulateMethod
class JavaLangReflectConstructorNative extends NativeMethodClass { public JavaLangReflectConstructorNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /********************** java.lang.reflect.Constructor ****************/ /** * Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's * declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to * match primitive formal parameters, and both primitive and reference parameters are subject to method invocation * conversions as necessary. Returns the newly created and initialized object. * * NOTE: @return = new Object; but we lose type information. * * public native java.lang.Object newInstance(java.lang.Object[]) throws java.lang.InstantiationException, * java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.reflect.InvocationTargetException; */ public void java_lang_reflect_Constructor_newInstance(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object newInstance(java.lang.Object[])")) { java_lang_reflect_Constructor_newInstance(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
360
99
459
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectProxyNative.java
JavaLangReflectProxyNative
simulateMethod
class JavaLangReflectProxyNative extends NativeMethodClass { public JavaLangReflectProxyNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /********* java.lang.reflect.Proxy *********************/ /** * We have to assume all possible classes will be returned. But it is still possible to make a new class. * * NOTE: assuming a close world, and this method should not be called. * * private static native java.lang.Class defineClass0(java.lang.ClassLoader, java.lang.String, byte[], int, int); */ public void java_lang_reflect_Proxy_defineClass0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Class defineClass0(java.lang.ClassLoader,java.lang.String,byte[],int,int)")) { java_lang_reflect_Proxy_defineClass0(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
276
114
390
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangRuntimeNative.java
JavaLangRuntimeNative
simulateMethod
class JavaLangRuntimeNative extends NativeMethodClass { public JavaLangRuntimeNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************ java.lang.Runtime *********************/ /** * execInternal is called by all exec method. It return a Process object. * * NOTE: creates a Process object. * * private native java.lang.Process execInternal(java.lang.String[], java.lang.String[], java.lang.String) throws * java.io.IOException; */ public void java_lang_Runtime_execInternal(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getProcessObject()); } /** * Following methods have NO side effects. * * public native long freeMemory(); public native long totalMemory(); public native void gc(); private static native void * runFinalization0(); public native void traceInstructions(boolean); public native void traceMethodCalls(boolean); */ }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Process execInternal(java.lang.String[],java.lang.String[],java.lang.String)")) { java_lang_Runtime_execInternal(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
338
109
447
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangShutdownNative.java
JavaLangShutdownNative
simulateMethod
class JavaLangShutdownNative extends NativeMethodClass { public JavaLangShutdownNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************** java.lang.Shutdown *********************/ /** * Both methods has NO side effects. * * static native void halt(int); private static native void runAllFinalizers(); */ }
String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; }
167
42
209
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangSystemNative.java
JavaLangSystemNative
simulateMethod
class JavaLangSystemNative extends NativeMethodClass { private static final Logger logger = LoggerFactory.getLogger(JavaLangSystemNative.class); public JavaLangSystemNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /********************* java.lang.System *********************/ /** * Copies an array from the specified source array, beginning at the specified position, to the specified position of the * destination array. * * NOTE: If the content of array is reference type, then it is necessary to build a connection between elements of two * arrays * * dst[] = src[] * * public static native void arraycopy(java.lang.Object, int, java.lang.Object, int, int); */ public void java_lang_System_arraycopy(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable srcElm = helper.arrayElementOf(params[0]); ReferenceVariable dstElm = helper.arrayElementOf(params[2]); // never make a[] = b[], it violates the principle of jimple statement. // make a temporary variable. ReferenceVariable tmpVar = helper.tempLocalVariable(method); helper.assign(tmpVar, srcElm); helper.assign(dstElm, tmpVar); } /** * NOTE: this native method is not documented in JDK API. It should have the side effect: System.in = parameter * * private static native void setIn0(java.io.InputStream); */ public void java_lang_System_setIn0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysIn = helper.staticField("java.lang.System", "in"); helper.assign(sysIn, params[0]); } /** * NOTE: the same explanation as setIn0: G.v().out = parameter * * private static native void setOut0(java.io.PrintStream); */ public void java_lang_System_setOut0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysOut = helper.staticField("java.lang.System", "out"); helper.assign(sysOut, params[0]); } /** * NOTE: the same explanation as setIn0: System.err = parameter * * private static native void setErr0(java.io.PrintStream); */ public void java_lang_System_setErr0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysErr = helper.staticField("java.lang.System", "err"); helper.assign(sysErr, params[0]); } /** * NOTE: this method is not documented, it should do following: * * @return = System.props; System.props = parameter; * * private static native java.util.Properties initProperties(java.util.Properties); */ public void java_lang_System_initProperties(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysProps = helper.staticField("java.lang.System", "props"); helper.assign(returnVar, sysProps); helper.assign(sysProps, params[0]); } /** * NOTE: it is platform-dependent, create a new string, needs to be verified. * * public static native java.lang.String mapLibraryName(java.lang.String); */ public void java_lang_System_mapLibraryName(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * Undocumented, used by class loading. * * static native java.lang.Class getCallerClass(); */ public void java_lang_System_getCallerClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Following methods have NO side effects. * * private static native void registerNatives(); public static native long currentTimeMillis(); public static native int * identityHashCode(java.lang.Object); */ }
String subSignature = method.getSubSignature(); if (subSignature.equals("void arraycopy(java.lang.Object,int,java.lang.Object,int,int)")) { java_lang_System_arraycopy(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setIn0(java.io.InputStream)")) { java_lang_System_setIn0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setOut0(java.io.PrintStream)")) { java_lang_System_setOut0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setErr0(java.io.PrintStream)")) { java_lang_System_setErr0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.util.Properties initProperties(java.util.Properties)")) { java_lang_System_initProperties(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.String mapLibraryName(java.lang.String)")) { java_lang_System_mapLibraryName(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class getCallerClass()")) { java_lang_System_getCallerClass(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
1,204
417
1,621
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangThreadNative.java
JavaLangThreadNative
simulateMethod
class JavaLangThreadNative extends NativeMethodClass { public JavaLangThreadNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /*************************** java.lang.Thread **********************/ /** * Returns the single variable pointing to all thread objects. * * This makes our analysis conservative on thread objects. * * public static native java.lang.Thread currentThread(); */ public void java_lang_Thread_currentThread(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getThreadObject()); } /** * Following native methods have no side effects. * * private static native void registerNatives(); public static native void yield(); public static native void sleep(long) * throws java.lang.InterruptedException; public native synchronized void start(); private native boolean * isInterrupted(boolean); public final native boolean isAlive(); public native int countStackFrames(); private native void * setPriority0(int); private native void stop0(java.lang.Object); private native void suspend0(); private native void * resume0(); private native void interrupt0(); */ }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Thread currentThread()")) { java_lang_Thread_currentThread(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
371
90
461
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger
soot-oss_soot
soot/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangThrowableNative.java
JavaLangThrowableNative
simulateMethod
class JavaLangThrowableNative extends NativeMethodClass { public JavaLangThrowableNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) {<FILL_FUNCTION_BODY>} /************************** java.lang.Throwable *******************/ /** * NOTE: this method just fills in the stack state in this throwable object content. * * public native java.lang.Throwable fillInStackTrace(); */ public void java_lang_Throwable_fillInStackTrace(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assign(returnVar, thisVar); } /** * NO side effects. * * private native void printStackTrace0(java.lang.Object); */ }
String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Throwable fillInStackTrace()")) { java_lang_Throwable_fillInStackTrace(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; }
263
96
359
<methods>public void <init>(soot.jimple.toolkits.pointer.util.NativeHelper) ,public static void defaultMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) ,public abstract void simulateMethod(soot.SootMethod, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable, soot.jimple.toolkits.pointer.representations.ReferenceVariable[]) <variables>private static final boolean DEBUG,protected soot.jimple.toolkits.pointer.util.NativeHelper helper,private static final org.slf4j.Logger logger