repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/callgraph/CallGraphTagger.java
|
package soot.jimple.toolkits.annotation.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.MethodOrMethodContext;
import soot.MethodToContexts;
import soot.Scene;
import soot.Singletons;
import soot.SootMethod;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.tagkit.Host;
import soot.tagkit.LinkTag;
public class CallGraphTagger extends BodyTransformer {
public CallGraphTagger(Singletons.Global g) {
}
public static CallGraphTagger v() {
return G.v().soot_jimple_toolkits_annotation_callgraph_CallGraphTagger();
}
private MethodToContexts methodToContexts;
protected void internalTransform(Body b, String phaseName, Map options) {
CallGraph cg = Scene.v().getCallGraph();
if (methodToContexts == null) {
methodToContexts = new MethodToContexts(Scene.v().getReachableMethods().listener());
}
Iterator stmtIt = b.getUnits().iterator();
while (stmtIt.hasNext()) {
Stmt s = (Stmt) stmtIt.next();
Iterator edges = cg.edgesOutOf(s);
while (edges.hasNext()) {
Edge e = (Edge) edges.next();
SootMethod m = e.tgt();
s.addTag(new LinkTag("CallGraph: Type: " + e.kind() + " Target Method/Context: " + e.getTgt().toString(), m,
m.getDeclaringClass().getName(), "Call Graph"));
}
}
SootMethod m = b.getMethod();
for (Iterator momcIt = methodToContexts.get(m).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();
Host src = methodCaller;
if (callEdge.srcUnit() != null) {
src = callEdge.srcUnit();
}
m.addTag(new LinkTag(
"CallGraph: Source Type: " + callEdge.kind() + " Source Method/Context: " + callEdge.getSrc().toString(), src,
methodCaller.getDeclaringClass().getName(), "Call Graph"));
}
}
}
}
| 3,009
| 30.354167
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/callgraph/MethInfo.java
|
package soot.jimple.toolkits.annotation.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Kind;
import soot.SootMethod;
public class MethInfo {
private SootMethod method;
private boolean canExpandCollapse;
private Kind edgeKind;
public MethInfo(SootMethod meth, boolean b, Kind kind) {
method(meth);
canExpandCollapse(b);
edgeKind(kind);
}
public Kind edgeKind() {
return edgeKind;
}
public void edgeKind(Kind kind) {
edgeKind = kind;
}
public boolean canExpandCollapse() {
return canExpandCollapse;
}
public void canExpandCollapse(boolean b) {
canExpandCollapse = b;
}
public SootMethod method() {
return method;
}
public void method(SootMethod m) {
method = m;
}
}
| 1,519
| 23.126984
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/defs/ReachingDefsTagger.java
|
package soot.jimple.toolkits.annotation.defs;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.Singletons;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.tagkit.LinkTag;
import soot.toolkits.scalar.LocalDefs;
public class ReachingDefsTagger extends BodyTransformer {
public ReachingDefsTagger(Singletons.Global g) {
}
public static ReachingDefsTagger v() {
return G.v().soot_jimple_toolkits_annotation_defs_ReachingDefsTagger();
}
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
LocalDefs ld = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(b);
for (Unit s : b.getUnits()) {
// System.out.println("stmt: "+s);
for (ValueBox vbox : s.getUseBoxes()) {
Value v = vbox.getValue();
if (v instanceof Local) {
Local l = (Local) v;
// System.out.println("local: "+l);
for (Unit next : ld.getDefsOfAt(l, s)) {
String info = l + " has reaching def: " + next;
String className = b.getMethod().getDeclaringClass().getName();
s.addTag(new LinkTag(info, next, className, "Reaching Defs"));
}
}
}
}
}
}
| 2,086
| 29.691176
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/fields/UnreachableFieldsTagger.java
|
package soot.jimple.toolkits.annotation.fields;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.G;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Value;
import soot.ValueBox;
import soot.jimple.FieldRef;
import soot.tagkit.ColorTag;
import soot.tagkit.StringTag;
/** A scene transformer that adds tags to unused fields. */
public 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) {
// 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()) {
continue;
}
if (!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);
}
}
}
| 3,809
| 31.564103
| 114
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/j5anno/AnnotationGenerator.java
|
package soot.jimple.toolkits.annotation.j5anno;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2008 Will Benton
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import soot.G;
import soot.Singletons.Global;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.tagkit.AnnotationConstants;
import soot.tagkit.AnnotationElem;
import soot.tagkit.AnnotationTag;
import soot.tagkit.Host;
import soot.tagkit.Tag;
import soot.tagkit.VisibilityAnnotationTag;
/**
* AnnotationGenerator is a singleton class that wraps up Soot's support for Java 5 annotations in a more convenient
* interface. It supplies three <tt>annotate()</tt> methods that take an <tt>Host</tt>, an annotation class, and zero or more
* <tt>AnnotationElem</tt> objects; these methods find the appropriate <tt>Tag</tt> on the given <tt>Host</tt> for the
* appropriate annotation visibility and add an annotation of the given type to it. <b>Note</b> that the first two methods
* expect an annotation class, which the last method expects a class name. If the class is passed, this class has to be on
* Soot's classpath at compile time. It is not enough to add the class to the soo-classpath!<br>
* <br>
*
* One caveat: <tt>annotate()</tt> does not add annotation classes to the Scene, so you will have to manually add any
* annotation classes that were not already in the Scene to the output directory or jar.
*
* @author <a href="mailto:willbenton+javadoc@gmail.com">Will Benton</a>
* @author Eric Bodden
*/
public 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) {
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));
}
}
| 7,536
| 36.311881
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/liveness/LiveVarsTagger.java
|
package soot.jimple.toolkits.annotation.liveness;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Value;
import soot.ValueBox;
import soot.jimple.Stmt;
import soot.tagkit.ColorTag;
import soot.tagkit.StringTag;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.scalar.LiveLocals;
import soot.toolkits.scalar.SimpleLiveLocals;
public 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) {
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"));
}
}
}
}
}
}
| 2,602
| 31.135802
| 101
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/logic/Loop.java
|
package soot.jimple.toolkits.annotation.logic;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2007 Eric Bodden
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import soot.Unit;
import soot.jimple.Stmt;
import soot.toolkits.graph.UnitGraph;
/**
* A (natural) loop in Jimple. A back-edge (t,h) is a control-flow edge for which h dominates t. In this case h is the header
* and the loop consists of all statements s which reach t without passing through h.
*
* @author Eric Bodden
*/
public 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() {
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;
}
/**
* 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) {
return false;
}
if (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;
}
}
| 5,149
| 25.963351
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/logic/LoopFinder.java
|
package soot.jimple.toolkits.annotation.logic;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.BodyTransformer;
import soot.Unit;
import soot.jimple.Stmt;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.MHGDominatorsFinder;
import soot.toolkits.graph.UnitGraph;
public 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) {
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;
}
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;
}
}
| 3,768
| 26.713235
| 97
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/logic/LoopInvariantFinder.java
|
package soot.jimple.toolkits.annotation.logic;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.Singletons;
import soot.Value;
import soot.ValueBox;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.GotoStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NaiveSideEffectTester;
import soot.jimple.NewExpr;
import soot.jimple.Stmt;
import soot.tagkit.ColorTag;
import soot.tagkit.LoopInvariantTag;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.SmartLocalDefs;
import soot.toolkits.scalar.SmartLocalDefsPool;
public class LoopInvariantFinder extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LoopInvariantFinder.class);
private ArrayList constants;
public LoopInvariantFinder(Singletons.Global g) {
}
public static LoopInvariantFinder v() {
return G.v().soot_jimple_toolkits_annotation_logic_LoopInvariantFinder();
}
/**
* this one uses the side effect tester
*/
protected void internalTransform(Body b, String phaseName, Map options) {
SmartLocalDefs sld = SmartLocalDefsPool.v().getSmartLocalDefsFor(b);
UnitGraph g = sld.getGraph();
NaiveSideEffectTester nset = new NaiveSideEffectTester();
Collection<Loop> loops = new LoopFinder().getLoops(b);
constants = new ArrayList();
// no loop invariants if no loops
if (loops.isEmpty()) {
return;
}
Iterator<Loop> lIt = loops.iterator();
while (lIt.hasNext()) {
Loop loop = lIt.next();
Stmt header = loop.getHead();
Collection<Stmt> loopStmts = loop.getLoopStatements();
Iterator<Stmt> bIt = loopStmts.iterator();
while (bIt.hasNext()) {
Stmt tStmt = bIt.next();
// System.out.println("will test stmt: "+tStmt+" for loop header: "+header);
// System.out.println("will test with loop stmts: "+loopStmts);
handleLoopBodyStmt(tStmt, nset, loopStmts);
}
}
}
private void handleLoopBodyStmt(Stmt s, NaiveSideEffectTester nset, Collection<Stmt> loopStmts) {
// need to do some checks for arrays - when there is an multi-dim array
// --> for defs there is a get of one of the dims that claims to be
// loop invariant
// handle constants
if (s instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) s;
if (ds.getLeftOp() instanceof Local && ds.getRightOp() instanceof Constant) {
if (!constants.contains(ds.getLeftOp())) {
constants.add(ds.getLeftOp());
} else {
constants.remove(ds.getLeftOp());
}
}
}
// ignore goto stmts
if (s instanceof GotoStmt) {
return;
}
// ignore invoke stmts
if (s instanceof InvokeStmt) {
return;
}
logger.debug("s : " + s + " use boxes: " + s.getUseBoxes() + " def boxes: " + s.getDefBoxes());
// just use boxes here
Iterator useBoxesIt = s.getUseBoxes().iterator();
boolean result = true;
uses: while (useBoxesIt.hasNext()) {
ValueBox vb = (ValueBox) useBoxesIt.next();
Value v = vb.getValue();
// System.out.println("next vb: "+v+" is a: "+vb.getClass());
// System.out.println("next vb: "+v+" class is a: "+v.getClass());
// new's are not invariant
if (v instanceof NewExpr) {
result = false;
logger.debug("break uses: due to new expr");
break uses;
}
// invokes are not invariant
if (v instanceof InvokeExpr) {
result = false;
logger.debug("break uses: due to invoke expr");
break uses;
}
// side effect tester doesn't handle expr
if (v instanceof Expr) {
continue;
}
logger.debug("test: " + v + " of kind: " + v.getClass());
Iterator loopStmtsIt = loopStmts.iterator();
while (loopStmtsIt.hasNext()) {
Stmt next = (Stmt) loopStmtsIt.next();
if (nset.unitCanWriteTo(next, v)) {
if (!isConstant(next)) {
logger.debug("result = false unit can be written to by: " + next);
result = false;
break uses;
}
}
}
}
Iterator defBoxesIt = s.getDefBoxes().iterator();
defs: while (defBoxesIt.hasNext()) {
ValueBox vb = (ValueBox) defBoxesIt.next();
Value v = vb.getValue();
// new's are not invariant
if (v instanceof NewExpr) {
result = false;
logger.debug("break defs due to new");
break defs;
}
// invokes are not invariant
if (v instanceof InvokeExpr) {
result = false;
logger.debug("break defs due to invoke");
break defs;
}
// side effect tester doesn't handle expr
if (v instanceof Expr) {
continue;
}
logger.debug("test: " + v + " of kind: " + v.getClass());
Iterator loopStmtsIt = loopStmts.iterator();
while (loopStmtsIt.hasNext()) {
Stmt next = (Stmt) loopStmtsIt.next();
if (next.equals(s)) {
continue;
}
if (nset.unitCanWriteTo(next, v)) {
if (!isConstant(next)) {
logger.debug("result false: unit can be written to by: " + next);
result = false;
break defs;
}
}
}
}
logger.debug("stmt: " + s + " result: " + result);
if (result) {
s.addTag(new LoopInvariantTag("is loop invariant"));
s.addTag(new ColorTag(ColorTag.RED, "Loop Invariant Analysis"));
} else {
// if loops are nested it might be invariant in one of them
// so remove tag
// if (s.hasTag(LoopInvariantTag.NAME)) {
// s.removeTag(LoopInvariantTag.NAME);
// }
}
}
private boolean isConstant(Stmt s) {
if (s instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) s;
if (constants.contains(ds.getLeftOp())) {
return true;
}
}
return false;
}
}
| 6,974
| 29.592105
| 99
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/methods/UnreachableMethodsTagger.java
|
package soot.jimple.toolkits.annotation.methods;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import soot.G;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.tagkit.ColorTag;
import soot.tagkit.StringTag;
/** A scene transformer that adds tags to unused methods. */
public class UnreachableMethodsTagger extends SceneTransformer {
public UnreachableMethodsTagger(Singletons.Global g) {
}
public static UnreachableMethodsTagger v() {
return G.v().soot_jimple_toolkits_annotation_methods_UnreachableMethodsTagger();
}
protected void internalTransform(String phaseName, Map options) {
// make list of all unreachable methods
ArrayList<SootMethod> methodList = new ArrayList<SootMethod>();
Iterator getClassesIt = Scene.v().getApplicationClasses().iterator();
while (getClassesIt.hasNext()) {
SootClass appClass = (SootClass) getClassesIt.next();
Iterator getMethodsIt = appClass.getMethods().iterator();
while (getMethodsIt.hasNext()) {
SootMethod method = (SootMethod) getMethodsIt.next();
// System.out.println("adding method: "+method);
if (!Scene.v().getReachableMethods().contains(method)) {
methodList.add(method);
}
}
}
// tag unused methods
Iterator<SootMethod> unusedIt = methodList.iterator();
while (unusedIt.hasNext()) {
SootMethod unusedMethod = unusedIt.next();
unusedMethod.addTag(new StringTag("Method " + unusedMethod.getName() + " is not reachable!", "Unreachable Methods"));
unusedMethod.addTag(new ColorTag(255, 0, 0, true, "Unreachable Methods"));
// System.out.println("tagged method: "+unusedMethod);
}
}
}
| 2,595
| 32.282051
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/BranchedRefVarsAnalysis.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Patrick Lam, Janus
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.ArrayType;
import soot.EquivalentValue;
import soot.Local;
import soot.NullType;
import soot.RefType;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.EqExpr;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.LengthExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.NeExpr;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NullConstant;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThisRef;
import soot.jimple.ThrowStmt;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArrayFlowUniverse;
import soot.toolkits.scalar.ArrayPackedSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardBranchedFlowAnalysis;
/*
README FIRST - IMPORTANT IMPLEMENTATION NOTE
As per the analysis presented in the report, there are four possible
pairs for given reference r:
(r, kBottom)
(r, kNonNull)
(r, kNull)
(r, kTop)
To save space an simplify operations, we implemented those 4 values
with two bits rather than four, namely:
(r, kTop) in a set is represented by having (r, kNull) and (r, kNonNull)
in the set. Ditto, (r, kBottom) is represented by having neither in the set.
Keep this in mind as you read the code, it helps. Honnest :)
-- Janus
*/
/*
BranchedRefVarsAnalysis class
Perform the analysis presented in the report.
KNOWN LIMITATION: there is a problem in the ForwardBranchedFlowAnalysis
or maybe the CompleteUnitGraph that prevent the analysis
(at the ForwardBranchedFlowAnalysis level) to handle properly traps.
We make the analysis conservative in case of exceptions by setting
exceptions handler statements In to TOP.
*/
/**
* @deprecated THIS IS KNOWN TO BE BUGGY. USE {@link NullnessAnalysis} INSTEAD!
*/
@Deprecated
public class BranchedRefVarsAnalysis extends ForwardBranchedFlowAnalysis<FlowSet<RefIntPair>> {
private static final Logger logger = LoggerFactory.getLogger(BranchedRefVarsAnalysis.class);
/*
* COMPILATION OPTIONS
*/
// we don't want the analysis to be conservative?
// i.e. we don't want it to only care for locals
private static final boolean isNotConservative = false;
// do we want the analysis to handle if statements?
private static final boolean isBranched = true;
// do we want the analysis to care that f and g
// could be the same reference?
private static final boolean careForAliases = false;
// do we want the analysis to care that a method
// call could have side effects?
private static final boolean careForMethodCalls = true;
// **** END OF COMPILATION OPTIONS *****
// constants for the analysis
public final static int kBottom = 0;
public final static int kNull = 1;
public final static int kNonNull = 2;
public final static int kTop = 99;
// bottom and top sets
protected final FlowSet<RefIntPair> emptySet;
protected final FlowSet<RefIntPair> fullSet;
// gen and preserve sets (for each statement)
protected final Map<Unit, FlowSet<RefIntPair>> unitToGenerateSet;
protected final Map<Unit, FlowSet<RefIntPair>> unitToPreserveSet;
// sets of variables that need a null pointer check (for each statement)
protected final Map<Unit, HashSet<Value>> unitToAnalyzedChecksSet;
protected final Map<Unit, HashSet<Value>> unitToArrayRefChecksSet;
protected final Map<Unit, HashSet<Value>> unitToInstanceFieldRefChecksSet;
protected final Map<Unit, HashSet<Value>> unitToInstanceInvokeExprChecksSet;
protected final Map<Unit, HashSet<Value>> unitToLengthExprChecksSet;
// keep track of the different kinds of reference types this analysis is working on
protected final List<EquivalentValue> refTypeLocals;
protected final List<EquivalentValue> refTypeInstFields;
protected final List<EquivalentValue> refTypeInstFieldBases;
protected final List<EquivalentValue> refTypeStaticFields;
protected final List<EquivalentValue> refTypeValues; // sum of all the above
// fast conversion from Value -> EquivalentValue
// because used in methods
private final HashMap<Value, EquivalentValue> valueToEquivValue = new HashMap<Value, EquivalentValue>(2293, 0.7f);
// constant (r, v) pairs because used in methods
private final HashMap<EquivalentValue, RefIntPair> kRefBotttomPairs = new HashMap<EquivalentValue, RefIntPair>(2293, 0.7f);
private final HashMap<EquivalentValue, RefIntPair> kRefNonNullPairs = new HashMap<EquivalentValue, RefIntPair>(2293, 0.7f);
private final HashMap<EquivalentValue, RefIntPair> kRefNullPairs = new HashMap<EquivalentValue, RefIntPair>(2293, 0.7f);
private final HashMap<EquivalentValue, RefIntPair> kRefTopPairs = new HashMap<EquivalentValue, RefIntPair>(2293, 0.7f);
// used in flowThrough.
protected FlowSet<RefIntPair> tempFlowSet = null;
/**
* @deprecated THIS IS KNOWN TO BE BUGGY. USE {@link NullnessAnalysis} INSTEAD!
*/
@Deprecated
public BranchedRefVarsAnalysis(UnitGraph g) {
super(g);
// initialize all the refType lists
this.refTypeLocals = new ArrayList<EquivalentValue>();
this.refTypeInstFields = new ArrayList<EquivalentValue>();
this.refTypeInstFieldBases = new ArrayList<EquivalentValue>();
this.refTypeStaticFields = new ArrayList<EquivalentValue>();
this.refTypeValues = new ArrayList<EquivalentValue>();
initRefTypeLists();
// initialize emptySet, fullSet and tempFlowSet
{
final int len = refTypeValues.size();
RefIntPair[] universeArray = new RefIntPair[2 * len];
for (int i = 0; i < len; i++) {
int j = i * 2;
EquivalentValue r = refTypeValues.get(i);
universeArray[j] = getKRefIntPair(r, kNull);
universeArray[j + 1] = getKRefIntPair(r, kNonNull);
}
ArrayPackedSet<RefIntPair> temp = new ArrayPackedSet<RefIntPair>(new ArrayFlowUniverse<RefIntPair>(universeArray));
this.emptySet = temp;
this.fullSet = temp.clone();
temp.complement(fullSet);
this.tempFlowSet = newInitialFlow();
}
// initialize unitTo...Sets
// perform preservation and generation
{
final int cap = graph.size() * 2 + 1;
this.unitToGenerateSet = new HashMap<Unit, FlowSet<RefIntPair>>(cap, 0.7f);
this.unitToPreserveSet = new HashMap<Unit, FlowSet<RefIntPair>>(cap, 0.7f);
this.unitToAnalyzedChecksSet = new HashMap<Unit, HashSet<Value>>(cap, 0.7f);
this.unitToArrayRefChecksSet = new HashMap<Unit, HashSet<Value>>(cap, 0.7f);
this.unitToInstanceFieldRefChecksSet = new HashMap<Unit, HashSet<Value>>(cap, 0.7f);
this.unitToInstanceInvokeExprChecksSet = new HashMap<Unit, HashSet<Value>>(cap, 0.7f);
this.unitToLengthExprChecksSet = new HashMap<Unit, HashSet<Value>>(cap, 0.7f);
}
initUnitSets();
doAnalysis();
} // end constructor
public EquivalentValue getEquivalentValue(Value v) {
if (valueToEquivValue.containsKey(v)) {
return valueToEquivValue.get(v);
} else {
EquivalentValue ev = new EquivalentValue(v);
valueToEquivValue.put(v, ev);
return ev;
}
} // end getEquivalentValue
// make that (r, v) pairs are constants
// i.e. the same r and v values always generate the same (r, v) object
public RefIntPair getKRefIntPair(EquivalentValue r, int v) {
HashMap<EquivalentValue, RefIntPair> pairsMap;
switch (v) {
case kNonNull:
pairsMap = kRefNonNullPairs;
break;
case kNull:
pairsMap = kRefNullPairs;
break;
case kTop:
pairsMap = kRefTopPairs;
break;
case kBottom:
pairsMap = kRefBotttomPairs;
break;
default:
throw new RuntimeException("invalid constant (" + v + ")");
}
if (pairsMap.containsKey(r)) {
return pairsMap.get(r);
} else {
RefIntPair pair = new RefIntPair(r, v, this);
pairsMap.put(r, pair);
return pair;
}
} // end getKRefIntPair
/*
* Utility methods.
*
* They are used all over the place. Most of them are declared "private static" so they can be inlined with javac -O.
*/
// isAlwaysNull returns true if the reference r is known to be always null
private static boolean isAlwaysNull(Value r) {
return (r instanceof NullConstant) || (r.getType() instanceof NullType);
} // end isAlwaysNull
// isAlwaysTop returns true if the reference r is known to be always top for this analysis
// i.e. its value is undecidable by this analysis
private static boolean isAlwaysTop(Value r) {
if (isNotConservative) {
return false;
} else {
return r instanceof InstanceFieldRef || r instanceof StaticFieldRef;
}
} // end isAlwaysTop
private static boolean isAlwaysNonNull(Value ro) {
return (ro instanceof NewExpr) || (ro instanceof NewArrayExpr) || (ro instanceof NewMultiArrayExpr)
|| (ro instanceof ThisRef) || (ro instanceof CaughtExceptionRef) || (ro instanceof StringConstant);
}
// isAnalyzedRef returns true if the reference r is to be analyzed by this analysis
// i.e. its value is not always known (or undecidable)
private static boolean isAnalyzedRef(Value r) {
if (isAlwaysNull(r) || isAlwaysTop(r)) {
return false;
} else if (r instanceof Local || r instanceof InstanceFieldRef || r instanceof StaticFieldRef) {
Type rType = r.getType();
return (rType instanceof RefType || rType instanceof ArrayType);
} else {
return false;
}
} // end isAnalyzedRef
// refInfo is a helper method to tranform our two bit representation back to the four constants
// For a given reference and a flow set, tell us if r is bottom, top, null or non-null
// Note: this method will fail if r is not in the flow set
protected final int refInfo(EquivalentValue r, FlowSet<RefIntPair> fs) {
boolean isNull = fs.contains(getKRefIntPair(r, kNull));
boolean isNonNull = fs.contains(getKRefIntPair(r, kNonNull));
if (isNull && isNonNull) {
return kTop;
} else if (isNull) {
return kNull;
} else if (isNonNull) {
return kNonNull;
} else {
return kBottom;
}
} // end refInfo
private int refInfo(Value r, FlowSet<RefIntPair> fs) {
return refInfo(getEquivalentValue(r), fs);
} // end refInfo
// Like refInfo, but the reference doesn't have to be in the flow set
// note: it still need to be a reference, i.e. ArrayType or RefType
public final int anyRefInfo(Value r, FlowSet<RefIntPair> f) {
if (isAlwaysNull(r)) {
return kNull;
} else if (isAlwaysTop(r)) {
return kTop;
} else if (isAlwaysNonNull(r)) {
return kNonNull;
} else {
return refInfo(r, f);
}
} // end anyRefInfo
/*
* methods: uAddTopToFlowSet uAddInfoToFlowSet uListAddTopToFlowSet
*
* Adding a pair (r, v) to a set is always a two steps process: a) remove all pairs (r, *) b) add the pair (r, v)
*
* The methods above handle that.
*
* Most of them come in two flavors: to act on one set or two act on separate generate and preserve sets.
*
*/
// method to add (r, kTop) to the gen set (and remove it from the pre set)
private void uAddTopToFlowSet(EquivalentValue r, FlowSet<RefIntPair> genFS, FlowSet<RefIntPair> preFS) {
RefIntPair nullPair = getKRefIntPair(r, kNull);
RefIntPair nullNonPair = getKRefIntPair(r, kNonNull);
if (genFS != preFS) {
preFS.remove(nullPair, preFS);
preFS.remove(nullNonPair, preFS);
}
genFS.add(nullPair, genFS);
genFS.add(nullNonPair, genFS);
} // end uAddTopToFlowSet
private void uAddTopToFlowSet(Value r, FlowSet<RefIntPair> genFS, FlowSet<RefIntPair> preFS) {
uAddTopToFlowSet(getEquivalentValue(r), genFS, preFS);
} // end uAddTopToFlowSet
// method to add (r, kTop) to a set
private void uAddTopToFlowSet(Value r, FlowSet<RefIntPair> fs) {
uAddTopToFlowSet(getEquivalentValue(r), fs, fs);
} // end uAddTopToFlowSet
// method to add (r, kTop) to a set
private void uAddTopToFlowSet(EquivalentValue r, FlowSet<RefIntPair> fs) {
uAddTopToFlowSet(r, fs, fs);
} // end uAddTopToFlowSet
// method to add (r, kNonNull) or (r, kNull) to the gen set (and remove it from the pre set)
private void uAddInfoToFlowSet(EquivalentValue r, int v, FlowSet<RefIntPair> genFS, FlowSet<RefIntPair> preFS) {
int kill;
switch (v) {
case kNull:
kill = kNonNull;
break;
case kNonNull:
kill = kNull;
break;
default:
throw new RuntimeException("invalid info");
}
if (genFS != preFS) {
preFS.remove(getKRefIntPair(r, kill), preFS);
}
genFS.remove(getKRefIntPair(r, kill), genFS);
genFS.add(getKRefIntPair(r, v), genFS);
} // end uAddInfoToFlowSet
private void uAddInfoToFlowSet(Value r, int v, FlowSet<RefIntPair> genF, FlowSet<RefIntPair> preF) {
uAddInfoToFlowSet(getEquivalentValue(r), v, genF, preF);
} // end uAddInfoToFlowSet
// method to add (r, kNonNull) or (r, kNull) to a set
private void uAddInfoToFlowSet(Value r, int v, FlowSet<RefIntPair> fs) {
uAddInfoToFlowSet(getEquivalentValue(r), v, fs, fs);
} // end uAddInfoToFlowSet
// method to add (r, kNonNull) or (r, kNull) to a set
private void uAddInfoToFlowSet(EquivalentValue r, int v, FlowSet<RefIntPair> fs) {
uAddInfoToFlowSet(r, v, fs, fs);
} // end uAddInfoToFlowSet
// method to apply uAddTopToFlowSet to a whole list of references
private void uListAddTopToFlowSet(List<EquivalentValue> refs, FlowSet<RefIntPair> genFS, FlowSet<RefIntPair> preFS) {
for (EquivalentValue ev : refs) {
uAddTopToFlowSet(ev, genFS, preFS);
}
} // end uListAddTopToFlowSet
/********** end of utility methods *********/
// method to initialize refTypeLocals, refTypeInstFields, refTypeInstFieldBases
// refTypeStaticFields, and refTypeValues
// those lists contains fields that can/need to be analyzed
private void initRefTypeLists() {
// build list of locals
for (Local l : ((UnitGraph) graph).getBody().getLocals()) {
Type type = l.getType();
if (type instanceof RefType || type instanceof ArrayType) {
refTypeLocals.add(getEquivalentValue(l));
}
}
if (isNotConservative) {
// build list of fields
// if the analysis is not conservative (if it is then we will only work on locals)
for (Unit s : graph) {
for (ValueBox next : s.getUseBoxes()) {
initRefTypeLists(next);
}
for (ValueBox next : s.getDefBoxes()) {
initRefTypeLists(next);
}
}
} // end build list of fields
refTypeValues.addAll(refTypeLocals);
refTypeValues.addAll(refTypeInstFields);
refTypeValues.addAll(refTypeStaticFields);
// logger.debug("Analyzed references: " + refTypeValues);
} // end initRefTypeLists
private void initRefTypeLists(ValueBox box) {
Type opType;
Value val = box.getValue();
if (val instanceof InstanceFieldRef) {
InstanceFieldRef ir = (InstanceFieldRef) val;
opType = ir.getType();
if (opType instanceof RefType || opType instanceof ArrayType) {
EquivalentValue eir = getEquivalentValue(ir);
if (!refTypeInstFields.contains(eir)) {
refTypeInstFields.add(eir);
EquivalentValue eirbase = getEquivalentValue(ir.getBase());
if (!refTypeInstFieldBases.contains(eirbase)) {
refTypeInstFieldBases.add(eirbase);
}
}
}
} else if (val instanceof StaticFieldRef) {
StaticFieldRef sr = (StaticFieldRef) val;
opType = sr.getType();
if (opType instanceof RefType || opType instanceof ArrayType) {
EquivalentValue esr = getEquivalentValue(sr);
if (!refTypeStaticFields.contains(esr)) {
refTypeStaticFields.add(esr);
}
}
}
}
private void initUnitSets() {
for (Unit s : graph) {
FlowSet<RefIntPair> genSet = emptySet.clone();
FlowSet<RefIntPair> preSet = fullSet.clone();
// *** KILL PHASE ***
// naivity here. kill all the fields after an invoke, i.e. promote them to top
if (careForMethodCalls && ((Stmt) s).containsInvokeExpr()) {
uListAddTopToFlowSet(refTypeInstFields, genSet, preSet);
uListAddTopToFlowSet(refTypeStaticFields, genSet, preSet);
}
if (careForAliases && (s instanceof AssignStmt)) {
Value lhs = ((AssignStmt) s).getLeftOp();
if (refTypeInstFieldBases.contains(getEquivalentValue(lhs))) {
// we have a write to a local 'f' and there is a reference to f.x.
// The LHS will certainly be a local. here, we kill "f.*".
for (EquivalentValue eifr : refTypeInstFields) {
InstanceFieldRef ifr = (InstanceFieldRef) eifr.getValue();
if (ifr.getBase() == lhs) {
uAddTopToFlowSet(eifr, genSet, preSet);
}
}
}
if (lhs instanceof InstanceFieldRef) {
// we have a write to 'f.x', so we'd better kill 'g.x' for all g.
final String lhsName = ((InstanceFieldRef) lhs).getField().getName();
for (EquivalentValue eifr : refTypeInstFields) {
InstanceFieldRef ifr = (InstanceFieldRef) eifr.getValue();
String name = ifr.getField().getName();
if (lhsName.equals(name)) {
uAddTopToFlowSet(eifr, genSet, preSet);
}
}
}
} // end if (s instanceof AssignStmt)
// kill rhs of defs
for (ValueBox box : s.getDefBoxes()) {
Value val = box.getValue();
if (isAnalyzedRef(val)) {
uAddTopToFlowSet(val, genSet, preSet);
}
}
// GENERATION PHASE
if (s instanceof DefinitionStmt) {
DefinitionStmt as = (DefinitionStmt) s;
Value ro = as.getRightOp();
// take out the cast from "x = (type) y;"
if (ro instanceof CastExpr) {
ro = ((CastExpr) ro).getOp();
}
Value lo = as.getLeftOp();
if (isAnalyzedRef(lo)) {
if (isAlwaysNonNull(ro)) {
uAddInfoToFlowSet(lo, kNonNull, genSet, preSet);
} else if (isAlwaysNull(ro)) {
uAddInfoToFlowSet(lo, kNull, genSet, preSet);
} else if (isAlwaysTop(ro)) {
uAddTopToFlowSet(lo, genSet, preSet);
}
}
} // end DefinitionStmt gen case
HashSet<Value> analyzedChecksSet = new HashSet<Value>(5, 0.7f);
HashSet<Value> arrayRefChecksSet = new HashSet<Value>(5, 0.7f);
HashSet<Value> instanceFieldRefChecksSet = new HashSet<Value>(5, 0.7f);
HashSet<Value> instanceInvokeExprChecksSet = new HashSet<Value>(5, 0.7f);
HashSet<Value> lengthExprChecksSet = new HashSet<Value>(5, 0.7f);
// check use and def boxes for dereferencing operations
// since those operations cause a null pointer check
// after the statement we know the involved references are non-null
{
for (ValueBox next : s.getUseBoxes()) {
Value base = null;
Value boxValue = next.getValue();
if (boxValue instanceof InstanceFieldRef) {
base = ((InstanceFieldRef) boxValue).getBase();
instanceFieldRefChecksSet.add(base);
} else if (boxValue instanceof ArrayRef) {
base = ((ArrayRef) boxValue).getBase();
arrayRefChecksSet.add(base);
} else if (boxValue instanceof InstanceInvokeExpr) {
base = ((InstanceInvokeExpr) boxValue).getBase();
instanceInvokeExprChecksSet.add(base);
} else if (boxValue instanceof LengthExpr) {
base = ((LengthExpr) boxValue).getOp();
lengthExprChecksSet.add(base);
} else if (s instanceof ThrowStmt) {
base = ((ThrowStmt) s).getOp();
} else if (s instanceof MonitorStmt) {
base = ((MonitorStmt) s).getOp();
}
if (base != null && isAnalyzedRef(base)) {
uAddInfoToFlowSet(base, kNonNull, genSet, preSet);
analyzedChecksSet.add(base);
}
}
for (ValueBox name : s.getDefBoxes()) {
Value base = null;
Value boxValue = name.getValue();
if (boxValue instanceof InstanceFieldRef) {
base = ((InstanceFieldRef) boxValue).getBase();
instanceFieldRefChecksSet.add(base);
} else if (boxValue instanceof ArrayRef) {
base = ((ArrayRef) boxValue).getBase();
arrayRefChecksSet.add(base);
} else if (boxValue instanceof InstanceInvokeExpr) {
base = ((InstanceInvokeExpr) boxValue).getBase();
instanceInvokeExprChecksSet.add(base);
} else if (boxValue instanceof LengthExpr) {
base = ((LengthExpr) boxValue).getOp();
lengthExprChecksSet.add(base);
} else if (s instanceof ThrowStmt) {
base = ((ThrowStmt) s).getOp();
} else if (s instanceof MonitorStmt) {
base = ((MonitorStmt) s).getOp();
}
if (base != null && isAnalyzedRef(base)) {
uAddInfoToFlowSet(base, kNonNull, genSet, preSet);
analyzedChecksSet.add(base);
}
}
} // done check use and def boxes
unitToGenerateSet.put(s, genSet);
unitToPreserveSet.put(s, preSet);
unitToAnalyzedChecksSet.put(s, analyzedChecksSet);
unitToArrayRefChecksSet.put(s, arrayRefChecksSet);
unitToInstanceFieldRefChecksSet.put(s, instanceFieldRefChecksSet);
unitToInstanceInvokeExprChecksSet.put(s, instanceInvokeExprChecksSet);
unitToLengthExprChecksSet.put(s, lengthExprChecksSet);
}
} // initUnitSets
@Override
protected void flowThrough(FlowSet<RefIntPair> in, Unit stmt, List<FlowSet<RefIntPair>> outFall,
List<FlowSet<RefIntPair>> outBranch) {
FlowSet<RefIntPair> out = tempFlowSet;
FlowSet<RefIntPair> pre = unitToPreserveSet.get(stmt);
FlowSet<RefIntPair> gen = unitToGenerateSet.get(stmt);
// Perform perservation
in.intersection(pre, out);
// Perform generation
out.union(gen, out);
// Manually add any x = y; when x and y are both analyzed references
// these are not sets.
if (stmt instanceof AssignStmt) {
AssignStmt as = (AssignStmt) stmt;
Value rightOp = as.getRightOp();
// take out the cast from "x = (type) y;"
if (rightOp instanceof CastExpr) {
rightOp = ((CastExpr) rightOp).getOp();
}
Value leftOp = as.getLeftOp();
if (isAnalyzedRef(leftOp) && isAnalyzedRef(rightOp)) {
int roInfo = refInfo(rightOp, in);
if (roInfo == kTop) {
uAddTopToFlowSet(leftOp, out);
} else if (roInfo != kBottom) {
uAddInfoToFlowSet(leftOp, roInfo, out);
}
}
}
// Copy the out value to all branch boxes.
for (FlowSet<RefIntPair> fs : outBranch) {
copy(out, fs);
}
// Copy the out value to the fallthrough box (don't need iterator)
for (FlowSet<RefIntPair> fs : outFall) {
copy(out, fs);
}
if (isBranched && (stmt instanceof IfStmt)) {
Value cond = ((IfStmt) stmt).getCondition();
Value op1 = ((BinopExpr) cond).getOp1();
Value op2 = ((BinopExpr) cond).getOp2();
// make sure at least one of the op is a reference being analyzed
// and that none is a reference that is always Top
if ((!(isAlwaysTop(op1) || isAlwaysTop(op2))) && (isAnalyzedRef(op1) || isAnalyzedRef(op2))) {
Value toGen = null;
int toGenInfo = kBottom;
{
final int op1Info = anyRefInfo(op1, in);
final int op2Info = anyRefInfo(op2, in);
final boolean op2isKnown = (op2Info == kNull || op2Info == kNonNull);
if (op1Info == kNull || op1Info == kNonNull) {
if (!op2isKnown) {
toGen = op2;
toGenInfo = op1Info;
}
} else if (op2isKnown) {
toGen = op1;
toGenInfo = op2Info;
}
}
// only generate info for analyzed references that are top or bottom
if ((toGen != null) && isAnalyzedRef(toGen)) {
int fInfo = kBottom;
int bInfo = kBottom;
if (cond instanceof EqExpr) {
// branching mean op1 == op2
bInfo = toGenInfo;
if (toGenInfo == kNull) {
// falling through mean toGen != null
fInfo = kNonNull;
}
} else if (cond instanceof NeExpr) {
// if we don't branch that mean op1 == op2
fInfo = toGenInfo;
if (toGenInfo == kNull) {
// branching through mean toGen != null
bInfo = kNonNull;
}
} else {
throw new RuntimeException("invalid condition");
}
if (fInfo != kBottom) {
for (FlowSet<RefIntPair> fs : outFall) {
copy(out, fs);
uAddInfoToFlowSet(toGen, fInfo, fs);
}
}
if (bInfo != kBottom) {
for (FlowSet<RefIntPair> fs : outBranch) {
copy(out, fs);
uAddInfoToFlowSet(toGen, bInfo, fs);
}
}
}
}
}
} // end flowThrough
@Override
protected void merge(FlowSet<RefIntPair> in1, FlowSet<RefIntPair> in2, FlowSet<RefIntPair> out) {
// we do that in case out is in1 or in2
FlowSet<RefIntPair> inSet1Copy = in1.clone();
FlowSet<RefIntPair> inSet2Copy = in2.clone();
// first step, set out to the intersection of in1 & in2
in1.intersection(in2, out);
// but we are not over, the intersection doesn't handle the top & bottom cases
for (EquivalentValue r : refTypeValues) {
int refInfoIn1 = refInfo(r, inSet1Copy);
int refInfoIn2 = refInfo(r, inSet2Copy);
if (refInfoIn1 != refInfoIn2) {
// only process if they are not equal, otherwise the intersection has done its job
if ((refInfoIn1 == kTop) || (refInfoIn2 == kTop)) {
// ok, r is top in one of the sets but not the other, make it top in the outSet
uAddTopToFlowSet(r, out);
} else if (refInfoIn1 == kBottom) {
// r is bottom in set1 but not set2, promote to the value in set2
uAddInfoToFlowSet(r, refInfoIn2, out);
} else if (refInfoIn2 == kBottom) {
// r is bottom in set2 but not set1, promote to the value in set1
uAddInfoToFlowSet(r, refInfoIn1, out);
} else {
// r is known in both set, but it's a different value in each set, make it top
uAddTopToFlowSet(r, out);
}
}
}
} // end merge
@Override
protected void copy(FlowSet<RefIntPair> source, FlowSet<RefIntPair> dest) {
source.copy(dest);
} // end copy
@Override
protected FlowSet<RefIntPair> newInitialFlow() {
return emptySet.clone();
} // end newInitialFlow
@Override
protected FlowSet<RefIntPair> entryInitialFlow() {
return fullSet.clone();
}
// try to workaround exception limitation of ForwardBranchedFlowAnalysis
// this will make for a very conservative analysys when exception handling
// statements are in the code :-(
@Override
public boolean treatTrapHandlersAsEntries() {
return true;
}
} // end class BranchedRefVarsAnalysis
| 28,837
| 35.3657
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/LocalRefVarsAnalysisWrapper.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Janus
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import soot.EquivalentValue;
import soot.Unit;
import soot.Value;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.scalar.FlowSet;
/**
* @deprecated uses deprecated type {@link BranchedRefVarsAnalysis} and seems of no use for Soot so marked for future
* deletion, unless clients object
*/
@Deprecated
public 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) {
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;
} // 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
} // end class LocalRefVarsAnalysisWrapper
| 6,704
| 38.441176
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullCheckEliminator.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Ganesh Sittampalam
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Immediate;
import soot.Unit;
import soot.Value;
import soot.jimple.BinopExpr;
import soot.jimple.EqExpr;
import soot.jimple.IfStmt;
import soot.jimple.Jimple;
import soot.jimple.NeExpr;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.UnitGraph;
import soot.util.Chain;
public class NullCheckEliminator extends BodyTransformer {
public static class AnalysisFactory {
public NullnessAnalysis newAnalysis(UnitGraph g) {
return new NullnessAnalysis(g);
}
}
private AnalysisFactory analysisFactory;
public NullCheckEliminator() {
this(new AnalysisFactory());
}
public NullCheckEliminator(AnalysisFactory f) {
this.analysisFactory = f;
}
@Override
public void internalTransform(Body body, String phaseName, Map<String, String> options) {
// really, the analysis should be able to use its own results to determine
// that some branches are dead, but since it doesn't we just iterate.
boolean changed;
do {
changed = false;
final NullnessAnalysis analysis
= analysisFactory.newAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body));
final Chain<Unit> units = body.getUnits();
for (Unit u = units.getFirst(); u != null; u = units.getSuccOf(u)) {
if (u instanceof IfStmt) {
final IfStmt is = (IfStmt) u;
final Value c = is.getCondition();
if (!(c instanceof EqExpr || c instanceof NeExpr)) {
continue;
}
final BinopExpr e = (BinopExpr) c;
final Immediate i;
if (e.getOp2() instanceof NullConstant) {
i = (Immediate) e.getOp1();
} else if (e.getOp1() instanceof NullConstant) {
i = (Immediate) e.getOp2();
} else {
i = null;
}
if (i != null) {
int elim = 0; // -1 => condition is false, 1 => condition is true
if (analysis.isAlwaysNonNullBefore(u, i)) {
elim = c instanceof EqExpr ? -1 : 1;
}
if (analysis.isAlwaysNullBefore(u, i)) {
elim = c instanceof EqExpr ? 1 : -1;
}
Stmt newstmt;
switch (elim) {
case -1:
newstmt = Jimple.v().newNopStmt();
break;
case 1:
newstmt = Jimple.v().newGotoStmt(is.getTarget());
break;
default:
continue;
}
assert (newstmt != null);
units.swapWith(u, newstmt);
u = newstmt;
changed = true;
}
}
}
} while (changed);
}
}
| 3,673
| 30.672414
| 102
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullPointerChecker.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.PhaseOptions;
import soot.Scene;
import soot.Singletons;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.LengthExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.toolkits.annotation.tags.NullCheckTag;
import soot.options.Options;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.util.Chain;
/*
ArrayRef
GetField
PutField
InvokeVirtual
InvokeSpecial
InvokeInterface
ArrayLength
- AThrow
- MonitorEnter
- MonitorExit
*/
public 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) {
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.");
}
}
}
| 5,422
| 31.866667
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullPointerColorer.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.RefLikeType;
import soot.Singletons;
import soot.SootClass;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.toolkits.annotation.tags.NullCheckTag;
import soot.tagkit.ColorTag;
import soot.tagkit.KeyTag;
import soot.tagkit.StringTag;
import soot.tagkit.Tag;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.scalar.FlowSet;
public class NullPointerColorer extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(NullPointerColorer.class);
public NullPointerColorer(Singletons.Global g) {
}
public static NullPointerColorer v() {
return G.v().soot_jimple_toolkits_annotation_nullcheck_NullPointerColorer();
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
BranchedRefVarsAnalysis analysis
= new BranchedRefVarsAnalysis(ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b));
for (Unit s : b.getUnits()) {
FlowSet<RefIntPair> beforeSet = analysis.getFlowBefore(s);
for (ValueBox vBox : s.getUseBoxes()) {
addColorTags(vBox, beforeSet, s, analysis);
}
FlowSet<RefIntPair> afterSet = analysis.getFallFlowAfter(s);
for (ValueBox vBox : s.getDefBoxes()) {
addColorTags(vBox, afterSet, s, analysis);
}
}
boolean keysAdded = false;
final SootClass declaringClass = b.getMethod().getDeclaringClass();
for (Tag next : declaringClass.getTags()) {
if (next instanceof KeyTag) {
if (NullCheckTag.NAME.equals(((KeyTag) next).analysisType())) {
keysAdded = true;
}
}
}
if (!keysAdded) {
declaringClass.addTag(new KeyTag(ColorTag.RED, "Nullness: Null", NullCheckTag.NAME));
declaringClass.addTag(new KeyTag(ColorTag.GREEN, "Nullness: Not Null", NullCheckTag.NAME));
declaringClass.addTag(new KeyTag(ColorTag.BLUE, "Nullness: Nullness Unknown", NullCheckTag.NAME));
}
}
private void addColorTags(ValueBox vBox, FlowSet<RefIntPair> set, Unit u, BranchedRefVarsAnalysis analysis) {
Value val = vBox.getValue();
if (val.getType() instanceof RefLikeType) {
// logger.debug(""+val+": "+val.getClass().toString());
switch (analysis.anyRefInfo(val, set)) {
case BranchedRefVarsAnalysis.kNull: {
// analysis.kNull
u.addTag(new StringTag(val + ": Null", NullCheckTag.NAME));
vBox.addTag(new ColorTag(ColorTag.RED, NullCheckTag.NAME));
break;
}
case BranchedRefVarsAnalysis.kNonNull: {
u.addTag(new StringTag(val + ": NonNull", NullCheckTag.NAME));
vBox.addTag(new ColorTag(ColorTag.GREEN, NullCheckTag.NAME));
break;
}
case BranchedRefVarsAnalysis.kTop: {
u.addTag(new StringTag(val + ": Nullness Unknown", NullCheckTag.NAME));
vBox.addTag(new ColorTag(ColorTag.BLUE, NullCheckTag.NAME));
break;
}
case BranchedRefVarsAnalysis.kBottom: {
u.addTag(new StringTag(val + ": Nullness Unknown", NullCheckTag.NAME));
vBox.addTag(new ColorTag(ColorTag.BLUE, NullCheckTag.NAME));
break;
}
}
}
}
}
| 4,220
| 34.470588
| 111
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullnessAnalysis.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Eric Bodden
* Copyright (C) 2007 Julian Tibble
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import soot.Immediate;
import soot.Local;
import soot.RefLikeType;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.ClassConstant;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.ThisRef;
import soot.jimple.internal.AbstractBinopExpr;
import soot.jimple.internal.JCastExpr;
import soot.jimple.internal.JEqExpr;
import soot.jimple.internal.JIfStmt;
import soot.jimple.internal.JInstanceOfExpr;
import soot.jimple.internal.JNeExpr;
import soot.shimple.PhiExpr;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ForwardBranchedFlowAnalysis;
/**
* An intraprocedural nullness analysis that computes for each location and each value in a method if the value is (before or
* after that location) definitely null, definitely non-null or neither. This class replaces {@link BranchedRefVarsAnalysis}
* which is known to have bugs.
*
* @author Eric Bodden
* @author Julian Tibble
*/
public class NullnessAnalysis extends ForwardBranchedFlowAnalysis<NullnessAnalysis.AnalysisInfo> {
/**
* The analysis info is a simple mapping of type {@link Value} to any of the constants BOTTOM, NON_NULL, NULL or TOP. This
* class returns BOTTOM by default.
*
* @author Julian Tibble
*/
protected 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 neet 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 sublasses 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) {
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);
}
}
private void handleEqualityOrNonEqualityCheck(AbstractBinopExpr eqExpr, AnalysisInfo in, AnalysisInfo out,
AnalysisInfo outBranch) {
Value left = eqExpr.getOp1();
Value right = eqExpr.getOp2();
Value val = null;
if (left == NullConstant.v()) {
if (right != NullConstant.v()) {
val = right;
}
} else if (right == NullConstant.v()) {
if (left != NullConstant.v()) {
val = left;
}
}
// if we compare a local with null then process further...
if (val != null && val instanceof Local) {
if (eqExpr instanceof JEqExpr) {
// a==null
handleEquality(val, out, outBranch);
} else if (eqExpr instanceof JNeExpr) {
// a!=null
handleNonEquality(val, out, outBranch);
} else {
throw new IllegalStateException("unexpected condition: " + eqExpr.getClass());
}
}
}
private void handleNonEquality(Value val, AnalysisInfo out, AnalysisInfo outBranch) {
out.put(val, NULL);
outBranch.put(val, NON_NULL);
}
private void handleEquality(Value val, AnalysisInfo out, AnalysisInfo outBranch) {
out.put(val, NON_NULL);
outBranch.put(val, NULL);
}
private void handleInstanceOfExpression(JInstanceOfExpr expr, AnalysisInfo in, AnalysisInfo out, AnalysisInfo outBranch) {
Value op = expr.getOp();
// if instanceof succeeds, we have a non-null value
outBranch.put(op, NON_NULL);
}
private void handleArrayRef(ArrayRef arrayRef, AnalysisInfo out) {
Value array = arrayRef.getBase();
// here we know that the array must point to an object
out.put(array, NON_NULL);
}
private void handleFieldRef(FieldRef fieldRef, AnalysisInfo out) {
if (fieldRef instanceof InstanceFieldRef) {
InstanceFieldRef instanceFieldRef = (InstanceFieldRef) fieldRef;
// here we know that the receiver must point to an object
out.put(instanceFieldRef.getBase(), NON_NULL);
}
}
private void handleInvokeExpr(InvokeExpr invokeExpr, AnalysisInfo out) {
if (invokeExpr instanceof InstanceInvokeExpr) {
InstanceInvokeExpr instanceInvokeExpr = (InstanceInvokeExpr) invokeExpr;
// here we know that the receiver must point to an object
out.put(instanceInvokeExpr.getBase(), NON_NULL);
}
}
private void handleRefTypeAssignment(DefinitionStmt assignStmt, AnalysisInfo out) {
Value right = assignStmt.getRightOp();
// unbox casted value
if (right instanceof JCastExpr) {
right = ((JCastExpr) right).getOp();
}
Value left = assignStmt.getLeftOp();
// if we have a definition (assignment) statement to a ref-like type, handle it,
if (isAlwaysNonNull(right) || right instanceof NewExpr || right instanceof NewArrayExpr
|| right instanceof NewMultiArrayExpr || right instanceof ThisRef || right instanceof StringConstant
|| right instanceof ClassConstant || right instanceof CaughtExceptionRef) {
// if we assign new... or @this, the result is non-null
out.put(left, NON_NULL);
} else if (right == NullConstant.v()) {
// if we assign null, well, it's null
out.put(left, NULL);
} else if (left instanceof Local && right instanceof Local) {
out.put(left, out.get(right));
} else if (left instanceof Local && right instanceof PhiExpr) {
handlePhiExpr(out, left, (PhiExpr) right);
} else {
out.put(left, TOP);
}
}
private void handlePhiExpr(AnalysisInfo out, Value left, PhiExpr right) {
int curr = BOTTOM;
for (Value v : right.getValues()) {
switch (out.get(v)) {
case BOTTOM:
continue;
case TOP:
out.put(left, TOP);
return;
case NULL:
if (curr == BOTTOM) {
curr = NULL;
} else if (curr != NULL) {
out.put(left, TOP);
return;
}
break;
case NON_NULL:
if (curr == BOTTOM) {
curr = NON_NULL;
} else if (curr != NON_NULL) {
out.put(left, TOP);
return;
}
break;
default:
break;
}
}
out.put(left, curr);
}
/**
* {@inheritDoc}
*/
@Override
protected void copy(AnalysisInfo s, AnalysisInfo d) {
d.clear();
d.or(s);
}
/**
* {@inheritDoc}
*/
@Override
protected void merge(AnalysisInfo in1, AnalysisInfo in2, AnalysisInfo out) {
out.clear();
out.or(in1);
out.or(in2);
}
/**
* {@inheritDoc}
*/
@Override
protected AnalysisInfo newInitialFlow() {
return new AnalysisInfo();
}
/**
* Returns <code>true</code> if the analysis could determine that i is always null before the statement s.
*
* @param s
* a statement of the respective body
* @param i
* a local or constant of that body
* @return true if i is always null right before this statement
*/
public boolean isAlwaysNullBefore(Unit s, Immediate i) {
return getFlowBefore(s).get(i) == NULL;
}
/**
* Returns <code>true</code> if the analysis could determine that i is always non-null before the statement s.
*
* @param s
* a statement of the respective body
* @param i
* a local of that body
* @return true if i is always non-null right before this statement
*/
public boolean isAlwaysNonNullBefore(Unit s, Immediate i) {
return getFlowBefore(s).get(i) == NON_NULL;
}
}
| 12,164
| 30.515544
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/NullnessAssumptionAnalysis.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Richard L. Halpert
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import soot.Immediate;
import soot.Local;
import soot.RefLikeType;
import soot.Unit;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.Stmt;
import soot.jimple.internal.JCastExpr;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.BackwardFlowAnalysis;
/**
* An intraprocedural nullness assumption analysis that computes for each location and each value in a method if the value
* (before or after that location) is treated as definitely null, definitely non-null or neither. This information could be
* useful in deciding whether or not to insert code that accesses a potentially null object. If the original program assumes
* a value is non-null, then adding a use of that value will not introduce any NEW nullness errors into the program. This
* code may be buggy, or just plain wrong. It has not been checked.
*
* @author Richard L. Halpert Adapted from Eric Bodden's NullnessAnalysis
*/
public class NullnessAssumptionAnalysis extends BackwardFlowAnalysis<Unit, NullnessAssumptionAnalysis.AnalysisInfo> {
protected final static Object BOTTOM = new Object() {
@Override
public String toString() {
return "bottom";
}
};
protected final static Object NULL = new Object() {
@Override
public String toString() {
return "null";
}
};
protected final static Object NON_NULL = new Object() {
@Override
public String toString() {
return "non-null";
}
};
// TOP IS MEANINGLESS FOR THIS ANALYSIS: YOU CAN'T ASSUME A VALUE IS NULL AND NON_NULL. BOTTOM IS USED FOR THAT CASE
protected final static Object TOP = new Object() {
@Override
public String toString() {
return "top";
}
};
/**
* Creates a new analysis for the given graph/
*
* @param graph
* any unit graph
*/
public NullnessAssumptionAnalysis(UnitGraph graph) {
super(graph);
doAnalysis();
}
/**
* {@inheritDoc}
*/
@Override
protected void flowThrough(AnalysisInfo in, Unit unit, AnalysisInfo outValue) {
AnalysisInfo out = new AnalysisInfo(in);
Stmt s = (Stmt) unit;
// in case of an if statement, we neet 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) {
// JIfStmt ifStmt = (JIfStmt) s;
// handleIfStmt(ifStmt, in, out, outBranch);
// }
// in case of a monitor statement, we know that the programmer assumes we have a non-null value
if (s instanceof MonitorStmt) {
out.put(((MonitorStmt) s).getOp(), NON_NULL);
}
// if we have an array ref, set the info for this ref to TOP,
// cause we need to be conservative here
if (s.containsArrayRef()) {
handleArrayRef(s.getArrayRef(), out);
}
// same for field refs, but also set the receiver object to non-null, if there is one
if (s.containsFieldRef()) {
handleFieldRef(s.getFieldRef(), out);
}
// same for invoke expr., also set the receiver object to non-null, if there is one
if (s.containsInvokeExpr()) {
handleInvokeExpr(s.getInvokeExpr(), out);
}
// allow sublasses to define certain values as always-non-null
for (Map.Entry<Value, Object> entry : out.entrySet()) {
if (isAlwaysNonNull(entry.getKey())) {
entry.setValue(NON_NULL);
}
}
// if we have a definition (assignment) statement to a ref-like type, handle it,
if (s instanceof DefinitionStmt) {
// need to copy the current out set because we need to assign under this assumption;
// so this copy becomes the in-set to handleRefTypeAssignment
DefinitionStmt defStmt = (DefinitionStmt) s;
if (defStmt.getLeftOp().getType() instanceof RefLikeType) {
handleRefTypeAssignment(defStmt, new AnalysisInfo(out), out);
}
}
// save memory by only retaining information about locals
for (Iterator<Value> outIter = out.keySet().iterator(); outIter.hasNext();) {
Value v = outIter.next();
if (!(v instanceof Local)) {
outIter.remove();
}
}
// now copy the computed info to out
copy(out, outValue);
}
/**
* This can be overridden by sublasses 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 handleArrayRef(ArrayRef arrayRef, AnalysisInfo out) {
// here we know that the array must point to an object, but the array value might be anything
out.put(arrayRef.getBase(), NON_NULL);
}
private void handleFieldRef(FieldRef fieldRef, AnalysisInfo out) {
if (fieldRef instanceof InstanceFieldRef) {
InstanceFieldRef instanceFieldRef = (InstanceFieldRef) fieldRef;
// here we know that the receiver must point to an object
out.put(instanceFieldRef.getBase(), NON_NULL);
}
}
private void handleInvokeExpr(InvokeExpr invokeExpr, AnalysisInfo out) {
if (invokeExpr instanceof InstanceInvokeExpr) {
InstanceInvokeExpr instanceInvokeExpr = (InstanceInvokeExpr) invokeExpr;
// here we know that the receiver must point to an object
out.put(instanceInvokeExpr.getBase(), NON_NULL);
}
}
private void handleRefTypeAssignment(DefinitionStmt assignStmt, AnalysisInfo rhsInfo, AnalysisInfo out) {
Value right = assignStmt.getRightOp();
// unbox casted value
if (right instanceof JCastExpr) {
right = ((JCastExpr) right).getOp();
}
// An assignment invalidates any assumptions of null/non-null for lhs
// We COULD be more accurate by assigning those assumptions to the rhs prior to this statement
rhsInfo.put(right, BOTTOM);
// assign from rhs to lhs
out.put(assignStmt.getLeftOp(), rhsInfo.get(right));
}
/**
* {@inheritDoc}
*/
@Override
protected void copy(AnalysisInfo source, AnalysisInfo dest) {
dest.clear();
dest.putAll(source);
}
/**
* {@inheritDoc}
*/
@Override
protected AnalysisInfo entryInitialFlow() {
return new AnalysisInfo();
}
/**
* {@inheritDoc}
*/
@Override
protected void merge(AnalysisInfo in1, AnalysisInfo in2, AnalysisInfo out) {
HashSet<Value> values = new HashSet<Value>();
values.addAll(in1.keySet());
values.addAll(in2.keySet());
out.clear();
for (Value v : values) {
HashSet<Object> leftAndRight = new HashSet<Object>();
leftAndRight.add(in1.get(v));
leftAndRight.add(in2.get(v));
Object result;
// This needs to be corrected for assumption *** TODO
// TOP stays TOP
if (leftAndRight.contains(BOTTOM)) {
// if on either side we know nothing... then together we know nothing for sure
result = BOTTOM;
} else if (leftAndRight.contains(NON_NULL)) {
if (leftAndRight.contains(NULL)) {
// NULL and NON_NULL merges to BOTTOM
result = BOTTOM;
} else {
// NON_NULL and NON_NULL stays NON_NULL
result = NON_NULL;
}
} else if (leftAndRight.contains(NULL)) {
// NULL and NULL stays NULL
result = NULL;
} else {
// only BOTTOM remains
result = BOTTOM;
}
out.put(v, result);
}
}
/**
* {@inheritDoc}
*/
@Override
protected AnalysisInfo newInitialFlow() {
return new AnalysisInfo();
}
/**
* Returns <code>true</code> if the analysis could determine that i is always treated as null after and including the
* statement s.
*
* @param s
* a statement of the respective body
* @param i
* a local or constant of that body
* @return true if i is always null right before this statement
*/
public boolean isAssumedNullBefore(Unit s, Immediate i) {
return getFlowBefore(s).get(i) == NULL;
}
/**
* Returns <code>true</code> if the analysis could determine that i is always treated as non-null after and including the
* statement s.
*
* @param s
* a statement of the respective body
* @param i
* a local of that body
* @return true if i is always non-null right before this statement
*/
public boolean isAssumedNonNullBefore(Unit s, Immediate i) {
return getFlowBefore(s).get(i) == NON_NULL;
}
/**
* The analysis info is a simple mapping of type {@link Value} to any of the constants BOTTOM, NON_NULL, NULL or TOP. This
* class returns BOTTOM by default.
*
* @author Eric Bodden
*/
protected static class AnalysisInfo extends HashMap<Value, Object> {
public AnalysisInfo() {
super();
}
public AnalysisInfo(Map<Value, Object> m) {
super(m);
}
@Override
public Object get(Object key) {
Object object = super.get(key);
if (object == null) {
return BOTTOM;
}
return object;
}
}
}
| 10,206
| 29.743976
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/nullcheck/RefIntPair.java
|
package soot.jimple.toolkits.annotation.nullcheck;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Janus
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.EquivalentValue;
/**
* @deprecated only used by deprecated type {@link BranchedRefVarsAnalysis}; flagged for future deletion
*/
@Deprecated
public 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() {
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 + ")";
}
}
}
| 1,888
| 27.19403
| 104
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/parity/ParityAnalysis.java
|
package soot.jimple.toolkits.annotation.parity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import static soot.jimple.toolkits.annotation.parity.ParityAnalysis.Parity.BOTTOM;
import static soot.jimple.toolkits.annotation.parity.ParityAnalysis.Parity.EVEN;
import static soot.jimple.toolkits.annotation.parity.ParityAnalysis.Parity.ODD;
import static soot.jimple.toolkits.annotation.parity.ParityAnalysis.Parity.TOP;
import static soot.jimple.toolkits.annotation.parity.ParityAnalysis.Parity.valueOf;
import java.util.HashMap;
import java.util.Map;
import soot.Body;
import soot.IntegerType;
import soot.Local;
import soot.LongType;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AddExpr;
import soot.jimple.ArithmeticConstant;
import soot.jimple.BinopExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.MulExpr;
import soot.jimple.SubExpr;
import soot.options.Options;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
import soot.toolkits.scalar.LiveLocals;
// STEP 1: What are we computing?
// SETS OF PAIRS of form (X, T) => Use ArraySparseSet.
//
// STEP 2: Precisely define what we are computing.
// For each statement compute the parity of all variables
// in the program.
//
// STEP 3: Decide whether it is a backwards or forwards analysis.
// FORWARDS
//
public class ParityAnalysis extends ForwardFlowAnalysis<Unit, Map<Value, ParityAnalysis.Parity>> {
public enum Parity {
TOP, BOTTOM, EVEN, ODD;
static Parity valueOf(int v) {
return (v % 2) == 0 ? EVEN : ODD;
}
static Parity valueOf(long v) {
return (v % 2) == 0 ? EVEN : ODD;
}
}
private final Body body;
private final LiveLocals filter;
public ParityAnalysis(UnitGraph g, LiveLocals filter) {
super(g);
this.body = g.getBody();
this.filter = filter;
filterUnitToBeforeFlow = new HashMap<Unit, Map<Value, Parity>>();
filterUnitToAfterFlow = new HashMap<Unit, Map<Value, Parity>>();
buildBeforeFilterMap();
doAnalysis();
}
public ParityAnalysis(UnitGraph g) {
super(g);
this.body = g.getBody();
this.filter = null;
doAnalysis();
}
private void buildBeforeFilterMap() {
for (Unit s : body.getUnits()) {
// if (!(s instanceof DefinitionStmt)) continue;
// Value left = ((DefinitionStmt)s).getLeftOp();
// if (!(left instanceof Local)) continue;
// if (!((left.getType() instanceof IntegerType) || (left.getType() instanceof LongType))) continue;
Map<Value, Parity> map = new HashMap<Value, Parity>();
for (Local l : filter.getLiveLocalsBefore(s)) {
map.put(l, BOTTOM);
}
filterUnitToBeforeFlow.put(s, map);
}
// System.out.println("init filtBeforeMap: "+filterUnitToBeforeFlow);
}
// STEP 4: Is the merge operator union or intersection?
//
// merge | bottom | even | odd | top
// -------+--------+--------+-------+--------
// bottom | bottom | even | odd | top
// -------+--------+--------+-------+--------
// even | even | even | top | top
// -------+--------+--------+-------+--------
// odd | odd | top | odd | top
// -------+--------+--------+-------+--------
// top | top | top | top | top
//
@Override
protected void merge(Map<Value, Parity> inMap1, Map<Value, Parity> inMap2, Map<Value, Parity> outMap) {
for (Value var1 : inMap1.keySet()) {
// System.out.println(var1);
Parity inVal1 = inMap1.get(var1);
// System.out.println(inVal1);
Parity inVal2 = inMap2.get(var1);
// System.out.println(inVal2);
// System.out.println("before out "+outMap.get(var1));
if (inVal2 == null) {
outMap.put(var1, inVal1);
} else if (BOTTOM.equals(inVal1)) {
outMap.put(var1, inVal2);
} else if (BOTTOM.equals(inVal2)) {
outMap.put(var1, inVal1);
} else if (EVEN.equals(inVal1) && EVEN.equals(inVal2)) {
outMap.put(var1, EVEN);
} else if (ODD.equals(inVal1) && ODD.equals(inVal2)) {
outMap.put(var1, ODD);
} else {
outMap.put(var1, TOP);
}
}
}
// STEP 5: Define flow equations.
// in(s) = ( out(s) minus defs(s) ) union uses(s)
//
@Override
protected void copy(Map<Value, Parity> sourceIn, Map<Value, Parity> destOut) {
destOut.clear();
destOut.putAll(sourceIn);
}
// Parity Tests: even + even = even
// even + odd = odd
// odd + odd = even
//
// even * even = even
// even * odd = even
// odd * odd = odd
//
// constants are tested mod 2
//
private Parity getParity(Map<Value, Parity> in, Value val) {
// System.out.println("get Parity in: "+in);
if ((val instanceof AddExpr) | (val instanceof SubExpr)) {
Parity resVal1 = getParity(in, ((BinopExpr) val).getOp1());
Parity resVal2 = getParity(in, ((BinopExpr) val).getOp2());
if (TOP.equals(resVal1) | TOP.equals(resVal2)) {
return TOP;
} else if (BOTTOM.equals(resVal1) | BOTTOM.equals(resVal2)) {
return BOTTOM;
} else if (resVal1.equals(resVal2)) {
return EVEN;
} else {
return ODD;
}
} else if (val instanceof MulExpr) {
Parity resVal1 = getParity(in, ((BinopExpr) val).getOp1());
Parity resVal2 = getParity(in, ((BinopExpr) val).getOp2());
if (TOP.equals(resVal1) | TOP.equals(resVal2)) {
return TOP;
} else if (BOTTOM.equals(resVal1) | BOTTOM.equals(resVal2)) {
return BOTTOM;
} else if (resVal1.equals(resVal2)) {
return resVal1;
} else {
return EVEN;
}
} else if (val instanceof IntConstant) {
int value = ((IntConstant) val).value;
return valueOf(value);
} else if (val instanceof LongConstant) {
long value = ((LongConstant) val).value;
return valueOf(value);
} else {
Parity p = in.get(val);
return (p != null) ? p : TOP;
}
}
@Override
protected void flowThrough(Map<Value, Parity> in, Unit s, Map<Value, Parity> out) {
// copy in to out
out.putAll(in);
// for each stmt where leftOp is defintionStmt find the parity
// of rightOp and update parity to EVEN, ODD or TOP
// boolean useS = false;
if (s instanceof DefinitionStmt) {
DefinitionStmt sDefStmt = (DefinitionStmt) s;
Value left = sDefStmt.getLeftOp();
if (left instanceof Local) {
Type leftType = left.getType();
if ((leftType instanceof IntegerType) || (leftType instanceof LongType)) {
// useS = true;
out.put(left, getParity(out, sDefStmt.getRightOp()));
}
}
}
// get all use and def boxes of s
// if use or def is int or long constant add their parity
for (ValueBox next : s.getUseAndDefBoxes()) {
Value val = next.getValue();
// System.out.println("val: "+val.getClass());
if (val instanceof ArithmeticConstant) {
out.put(val, getParity(out, val));
// System.out.println("out map: "+out);
}
}
// if (useS){
if (Options.v().interactive_mode()) {
buildAfterFilterMap(s);
updateAfterFilterMap(s);
}
// }
}
private void buildAfterFilterMap(Unit s) {
Map<Value, Parity> map = new HashMap<Value, Parity>();
for (Local local : filter.getLiveLocalsAfter(s)) {
map.put(local, BOTTOM);
}
filterUnitToAfterFlow.put(s, map);
// System.out.println("built afterflow filter map: "+filterUnitToAfterFlow);
}
// STEP 6: Determine value for start/end node, and
// initial approximation.
//
// start node: locals with BOTTOM
// initial approximation: locals with BOTTOM
@Override
protected Map<Value, Parity> entryInitialFlow() {
/*
* HashMap initMap = new HashMap();
*
* Chain locals = body.getLocals(); Iterator it = locals.iterator(); while (it.hasNext()) { initMap.put(it.next(),
* BOTTOM); } return initMap;
*/
return newInitialFlow();
}
private void updateBeforeFilterMap() {
for (Unit s : filterUnitToBeforeFlow.keySet()) {
Map<Value, Parity> allData = getFlowBefore(s);
Map<Value, Parity> filterData = filterUnitToBeforeFlow.get(s);
filterUnitToBeforeFlow.put(s, updateFilter(allData, filterData));
}
}
private void updateAfterFilterMap(Unit s) {
Map<Value, Parity> allData = getFlowAfter(s);
Map<Value, Parity> filterData = filterUnitToAfterFlow.get(s);
filterUnitToAfterFlow.put(s, updateFilter(allData, filterData));
}
private Map<Value, Parity> updateFilter(Map<Value, Parity> allData, Map<Value, Parity> filterData) {
if (allData != null) {
for (Value v : filterData.keySet()) {
Parity d = allData.get(v);
if (d == null) {
filterData.remove(v);
} else {
filterData.put(v, d);
}
}
}
return filterData;
}
@Override
protected Map<Value, Parity> newInitialFlow() {
Map<Value, Parity> initMap = new HashMap<Value, Parity>();
for (Local l : body.getLocals()) {
Type t = l.getType();
// System.out.println("next local: "+next);
if ((t instanceof IntegerType) || (t instanceof LongType)) {
initMap.put(l, BOTTOM);
}
}
for (ValueBox vb : body.getUseAndDefBoxes()) {
Value val = vb.getValue();
if (val instanceof ArithmeticConstant) {
initMap.put(val, getParity(initMap, val));
}
}
if (Options.v().interactive_mode()) {
updateBeforeFilterMap();
}
return initMap;
}
}
| 10,356
| 29.732938
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/parity/ParityTagger.java
|
package soot.jimple.toolkits.annotation.parity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Value;
import soot.ValueBox;
import soot.jimple.IntConstant;
import soot.jimple.LongConstant;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.tagkit.ColorTag;
import soot.tagkit.KeyTag;
import soot.tagkit.StringTag;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.scalar.LiveLocals;
import soot.toolkits.scalar.SimpleLiveLocals;
/**
* A body transformer that records parity analysis information in tags.
*/
public 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) {
// 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"));
}
}
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"));
}
}
}
| 5,278
| 31.58642
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/profiling/ProfilingGenerator.java
|
package soot.jimple.toolkits.annotation.profiling;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.options.ProfilingOptions;
import soot.util.Chain;
public 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 = "void main(java.lang.String[])";
// private String mainSignature = "long runBenchmark(java.lang.String[])";
protected void internalTransform(Body body, String phaseName, Map opts) {
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);
}
}
}
}
}
| 3,293
| 31.94
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/AbstractInterproceduralAnalysis.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.SourceLocator;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.PseudoTopologicalOrderer;
import soot.util.dot.DotGraph;
import soot.util.dot.DotGraphEdge;
import soot.util.dot.DotGraphNode;
/**
* Inter-procedural iterator skeleton for summary-based analysis
*
* A "summary" is an abstract element associated to each method that fully models the effect of calling the method. In a
* summary-based analysis, the summary of a method can be computed using solely the summary of all methods it calls: the
* summary does not depend upon the context in which a method is called. The inter-procedural analysis interacts with a
* intra-procedural analysis that is able to compute the summary of one method, given the summary of all the method it calls.
* The inter-procedural analysis calls the intra-procedural analysis in a reverse topological order of method dependencies to
* resolve unknown summaries. It iterates over recursively dependant methods.
*
* Generally, the intra-procedural works by maintaining an abstract value that represent the effect of the method from its
* entry point and up to the current point. At the entry point, this value is empty. The summary of the method is then the
* merge of the abstract values at all its return points.
*
* You can provide off-the-shelf summaries for methods you do not which to analyse. Any method using these "filtered-out"
* methods will use the off-the-shelf summary instead of performing an intra-procedural analysis. This is useful for native
* methods, incremental analysis, or when you hand-made summary. Methods that are called solely by filtered-out ones will
* never be analysed, effectively trimming the call-graph dependencies.
*
* This class tries to use the same abstract methods and data management policy as regular FlowAnalysis classes.
*
* @param <S>
*/
public abstract class AbstractInterproceduralAnalysis<S> {
private static final Logger logger = LoggerFactory.getLogger(AbstractInterproceduralAnalysis.class);
public static final boolean doCheck = false;
protected final CallGraph cg; // analysed call-graph
protected final DirectedGraph<SootMethod> dg; // filtered trimed call-graph
protected final Map<SootMethod, S> data; // SootMethod -> summary
protected final Map<SootMethod, Integer> order; // SootMethod -> topo order
protected final Map<SootMethod, S> unanalysed; // SootMethod -> summary
/**
* The constructor performs some preprocessing, but you have to call doAnalysis to preform the real stuff.
*
* @param cg
* @param filter
* @param verbose
* @param heads
*/
public AbstractInterproceduralAnalysis(CallGraph cg, SootMethodFilter filter, Iterator<SootMethod> heads,
boolean verbose) {
this.cg = cg;
this.dg = new DirectedCallGraph(cg, filter, heads, verbose);
this.data = new HashMap<SootMethod, S>();
this.unanalysed = new HashMap<SootMethod, S>();
// construct reverse pseudo topological order on filtered methods
this.order = new HashMap<SootMethod, Integer>();
int i = 0;
for (SootMethod m : new PseudoTopologicalOrderer<SootMethod>().newList(dg, true)) {
this.order.put(m, i);
i++;
}
}
/**
* Initial summary value for analysed functions.
*
* @return
*/
protected abstract S newInitialSummary();
/**
* Whenever the analyse requires the summary of a method you filtered-out, this function is called instead of
* analyseMethod.
*
* <p>
* Note: This function is called at most once per filtered-out method. It is the equivalent of entryInitialFlow!
*
* @param method
*
* @return
*/
protected abstract S summaryOfUnanalysedMethod(SootMethod method);
/**
* Compute the summary for a method by analysing its body.
*
* Will be called only on methods not filtered-out.
*
* @param method
* is the method to be analysed
* @param dst
* is where to put the computed method summary
*/
protected abstract void analyseMethod(SootMethod method, S dst);
/**
* Interprocedural analysis will call applySummary repeatedly as a consequence to
* {@link #analyseCall(Object, Stmt, Object)}, once for each possible target method of the {@code callStmt}, provided with
* its summary.
*
* @param src
* summary valid before the call statement
* @param callStmt
* a statement containing a InvokeStmt or InvokeExpr
* @param summary
* summary of the possible target of callStmt considered here
* @param dst
* where to put the result
*
* @see analyseCall
*/
protected abstract void applySummary(S src, Stmt callStmt, S summary, S dst);
/**
* Merge in1 and in2 into out.
*
* Note: in1 or in2 can be aliased to out (e.g., analyseCall).
*
* @param in1
* @param in2
* @param out
*/
protected abstract void merge(S in1, S in2, S out);
/**
* Copy src into dst.
*
* @param sr
* @param dst
*/
protected abstract void copy(S sr, S dst);
/**
* Called by drawAsOneDot to fill dot subgraph out with the contents of summary o.
*
* @param prefix
* gives you a unique string to prefix your node names and avoid name-clash
* @param o
* @param out
*/
protected void fillDotGraph(String prefix, S o, DotGraph out) {
throw new Error("abstract function AbstractInterproceduralAnalysis.fillDotGraph called but not implemented.");
}
/**
* Analyse the call {@code callStmt} in the context {@code src}, and put the result into {@code dst}. For each possible
* target of the call, this will get the summary for the target method (possibly
* {@link #summaryOfUnanalysedMethod(SootMethod)}) and {@link #applySummary(Object, Stmt, Object, Object)}, then merge the
* results into {@code dst} using {@link #merge(Object, Object, Object)}.
*
* @param src
* @param dst
* @param callStmt
*
* @see #summaryOfUnanalysedMethod(SootMethod)
* @see #applySummary(Object, Stmt, Object, Object)
*/
public void analyseCall(S src, Stmt callStmt, S dst) {
S accum = newInitialSummary();
copy(accum, dst);
// System.out.println("Edges out of " + callStmt + "...");
for (Iterator<Edge> it = cg.edgesOutOf(callStmt); it.hasNext();) {
Edge edge = it.next();
SootMethod m = edge.tgt();
// System.out.println("\t-> " + m.getSignature());
S elem;
if (data.containsKey(m)) {
// analysed method
elem = data.get(m);
} else {
// unanalysed method
if (!unanalysed.containsKey(m)) {
unanalysed.put(m, summaryOfUnanalysedMethod(m));
}
elem = unanalysed.get(m);
}
applySummary(src, callStmt, elem, accum);
merge(dst, accum, dst);
}
}
/**
* Dump the interprocedural analysis result as a graph. One node / subgraph for each analysed method that contains the
* method summary, and call-to edges.
*
* Note: this graph does not show filtered-out methods for which a conservative summary was asked via
* summaryOfUnanalysedMethod.
*
* @param name
* output filename
*
* @see fillDotGraph
*/
public void drawAsOneDot(String name) {
DotGraph dot = new DotGraph(name);
dot.setGraphLabel(name);
dot.setGraphAttribute("compound", "true");
// dot.setGraphAttribute("rankdir","LR");
int id = 0;
Map<SootMethod, Integer> idmap = new HashMap<SootMethod, Integer>();
// draw sub-graph cluster
// draw sub-graph cluster
for (SootMethod m : dg) {
DotGraph sub = dot.createSubGraph("cluster" + id);
DotGraphNode label = sub.drawNode("head" + id);
idmap.put(m, id);
sub.setGraphLabel("");
label.setLabel("(" + order.get(m) + ") " + m.toString());
label.setAttribute("fontsize", "18");
label.setShape("box");
if (data.containsKey(m)) {
fillDotGraph("X" + id, data.get(m), sub);
}
id++;
}
// connect edges
for (SootMethod m : dg) {
for (SootMethod mm : dg.getSuccsOf(m)) {
DotGraphEdge edge = dot.drawEdge("head" + idmap.get(m), "head" + idmap.get(mm));
edge.setAttribute("ltail", "cluster" + idmap.get(m));
edge.setAttribute("lhead", "cluster" + idmap.get(mm));
}
}
File f = new File(SourceLocator.v().getOutputDir(), name + DotGraph.DOT_EXTENSION);
dot.plot(f.getPath());
}
/**
* Dump the each summary computed by the interprocedural analysis as a separate graph.
*
* @param prefix
* is prepended before method name in output filename
* @param drawUnanalysed
* do you also want info for the unanalysed methods required by the analysis via summaryOfUnanalysedMethod ?
*
* @see fillDotGraph
*/
public void drawAsManyDot(String prefix, boolean drawUnanalysed) {
for (SootMethod m : data.keySet()) {
DotGraph dot = new DotGraph(m.toString());
dot.setGraphLabel(m.toString());
fillDotGraph("X", data.get(m), dot);
File f = new File(SourceLocator.v().getOutputDir(), prefix + m.toString() + DotGraph.DOT_EXTENSION);
dot.plot(f.getPath());
}
if (drawUnanalysed) {
for (SootMethod m : unanalysed.keySet()) {
DotGraph dot = new DotGraph(m.toString());
dot.setGraphLabel(m.toString() + " (unanalysed)");
fillDotGraph("X", unanalysed.get(m), dot);
File f = new File(SourceLocator.v().getOutputDir(), prefix + m.toString() + "_u" + DotGraph.DOT_EXTENSION);
dot.plot(f.getPath());
}
}
}
/**
* Query the analysis result.
*
* @param m
*
* @return
*/
public S getSummaryFor(SootMethod m) {
if (data.containsKey(m)) {
return data.get(m);
}
if (unanalysed.containsKey(m)) {
return unanalysed.get(m);
}
return newInitialSummary();
}
/**
* Get an iterator over the list of SootMethod with an associated summary. (Does not contain filtered-out or native
* methods.)
*
* @return
*/
public Iterator<SootMethod> getAnalysedMethods() {
return data.keySet().iterator();
}
/**
* Carry out the analysis.
*
* Call this from your InterproceduralAnalysis constructor, just after super(cg). Then , you will be able to call
* drawAsDot, for instance.
*
* @param verbose
*/
protected void doAnalysis(boolean verbose) {
// queue class
class IntComparator implements Comparator<SootMethod> {
@Override
public int compare(SootMethod o1, SootMethod o2) {
return order.get(o1) - order.get(o2);
}
}
SortedSet<SootMethod> queue = new TreeSet<SootMethod>(new IntComparator());
// init
for (SootMethod o : order.keySet()) {
data.put(o, newInitialSummary());
queue.add(o);
}
Map<SootMethod, Integer> nb = new HashMap<SootMethod, Integer>(); // only for debug pretty-printing
// fixpoint iterations
while (!queue.isEmpty()) {
SootMethod m = queue.first();
queue.remove(m);
S newSummary = newInitialSummary();
S oldSummary = data.get(m);
if (nb.containsKey(m)) {
nb.put(m, nb.get(m) + 1);
} else {
nb.put(m, 1);
}
if (verbose) {
logger.debug(" |- processing " + m.toString() + " (" + nb.get(m) + "-st time)");
}
analyseMethod(m, newSummary);
if (!oldSummary.equals(newSummary)) {
// summary for m changed!
data.put(m, newSummary);
queue.addAll(dg.getPredsOf(m));
}
}
// fixpoint verification
if (doCheck) {
for (SootMethod m : order.keySet()) {
S newSummary = newInitialSummary();
S oldSummary = data.get(m);
analyseMethod(m, newSummary);
if (!oldSummary.equals(newSummary)) {
logger.debug("inter-procedural fixpoint not reached for method " + m.toString());
DotGraph gm = new DotGraph("false_fixpoint");
DotGraph gmm = new DotGraph("next_iterate");
gm.setGraphLabel("false fixpoint: " + m.toString());
gmm.setGraphLabel("fixpoint next iterate: " + m.toString());
fillDotGraph("", oldSummary, gm);
fillDotGraph("", newSummary, gmm);
gm.plot(m.toString() + "_false_fixpoint.dot");
gmm.plot(m.toString() + "_false_fixpoint_next.dot");
throw new Error("AbstractInterproceduralAnalysis sanity check failed!!!");
}
}
}
}
}
| 13,735
| 32.916049
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/DirectedCallGraph.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.SootMethod;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.toolkits.graph.DirectedGraph;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
/**
* Builds a DirectedGraph from a CallGraph and SootMethodFilter.
*
* This is used in AbstractInterproceduralAnalysis to construct a reverse pseudo topological order on which to iterate. You
* can specify a SootMethodFilter to trim the graph by cutting call edges.
*
* Methods filtered-out by the SootMethodFilter will not appear in the DirectedGraph!
*/
public class DirectedCallGraph implements DirectedGraph<SootMethod> {
private static final Logger logger = LoggerFactory.getLogger(DirectedCallGraph.class);
protected Set<SootMethod> nodes;
protected Map<SootMethod, List<SootMethod>> succ;
protected Map<SootMethod, List<SootMethod>> pred;
protected List<SootMethod> heads;
protected List<SootMethod> tails;
protected int size;
/**
* The constructor does all the work here. After constructed, you can safely use all interface methods. Moreover, these
* methods should perform very fast...
*
* The DirectedGraph will only contain methods in call paths from a method in head and comprising only methods wanted by
* filter. Moreover, only concrete methods are put in the graph...
*
* @param cg
* @param filter
* @param heads
* is a List of SootMethod
* @param verbose
*/
public DirectedCallGraph(CallGraph cg, SootMethodFilter filter, Iterator<SootMethod> heads, boolean verbose) {
// filter heads by filter
List<SootMethod> filteredHeads = new LinkedList<SootMethod>();
while (heads.hasNext()) {
SootMethod m = heads.next();
if (m.isConcrete() && filter.want(m)) {
filteredHeads.add(m);
}
}
this.nodes = new HashSet<SootMethod>(filteredHeads);
MultiMap<SootMethod, SootMethod> s = new HashMultiMap<SootMethod, SootMethod>();
MultiMap<SootMethod, SootMethod> p = new HashMultiMap<SootMethod, SootMethod>();
if (verbose) {
logger.debug("[AM] dumping method dependencies");
}
// simple breadth-first visit
int nb = 0;
Set<SootMethod> remain = new HashSet<SootMethod>(filteredHeads);
while (!remain.isEmpty()) {
Set<SootMethod> newRemain = new HashSet<SootMethod>();
for (SootMethod m : remain) {
if (verbose) {
logger.debug(" |- " + m.toString() + " calls");
}
for (Iterator<Edge> itt = cg.edgesOutOf(m); itt.hasNext();) {
Edge edge = itt.next();
SootMethod mm = edge.tgt();
boolean keep = mm.isConcrete() && filter.want(mm);
if (verbose) {
logger.debug(" | |- " + mm.toString() + (keep ? "" : " (filtered out)"));
}
if (keep) {
if (this.nodes.add(mm)) {
newRemain.add(mm);
}
s.put(m, mm);
p.put(mm, m);
}
}
nb++;
}
remain = newRemain;
}
logger.debug("[AM] number of methods to be analysed: " + nb);
// MultiMap -> Map of List
this.succ = new HashMap<SootMethod, List<SootMethod>>();
this.pred = new HashMap<SootMethod, List<SootMethod>>();
this.tails = new LinkedList<SootMethod>();
this.heads = new LinkedList<SootMethod>();
for (SootMethod x : this.nodes) {
Set<SootMethod> ss = s.get(x);
Set<SootMethod> pp = p.get(x);
this.succ.put(x, new LinkedList<SootMethod>(ss));
this.pred.put(x, new LinkedList<SootMethod>(pp));
if (ss.isEmpty()) {
this.tails.add(x);
}
if (pp.isEmpty()) {
this.heads.add(x);
}
}
this.size = this.nodes.size();
}
/**
* You get a List of SootMethod.
*
* @return
*/
@Override
public List<SootMethod> getHeads() {
return heads;
}
/**
* You get a List of SootMethod.
*
* @return
*/
@Override
public List<SootMethod> getTails() {
return tails;
}
/**
* You get an Iterator on SootMethod.
*
* @return
*/
@Override
public Iterator<SootMethod> iterator() {
return nodes.iterator();
}
/**
*
* @return
*/
@Override
public int size() {
return size;
}
/**
* You get a List of SootMethod.
*
* @param s
*
* @return
*/
@Override
public List<SootMethod> getSuccsOf(SootMethod s) {
return succ.get(s);
}
/**
* You get a List of SootMethod.
*
* @param s
*
* @return
*/
@Override
public List<SootMethod> getPredsOf(SootMethod s) {
return pred.get(s);
}
}
| 5,708
| 26.57971
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityAnalysis.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.options.PurityOptions;
/**
* Purity analysis phase.
*
* TODO: - test, test, and test (and correct the potentially infinite bugs) - optimise PurityGraph, especially methodCall) -
* find a better abstraction for exceptions (throw & catch) - output nicer graphs (especially clusters!)
*/
public 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) {
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);
}
}
| 1,983
| 30.492063
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityEdge.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* An edge in a purity graph. Each edge has a source PurityNode, a target PurityNode, and a field label (we use a String
* here). To represent an array element, the convention is to use the [] field label. Edges are immutable and hashable. They
* compare equal only if they link equal nodes and have equal labels.
*/
public class PurityEdge {
private final String field;
private final PurityNode source;
private final PurityNode target;
private final boolean inside;
PurityEdge(PurityNode source, String field, PurityNode target, boolean inside) {
this.source = source;
this.field = field;
this.target = target;
this.inside = inside;
}
public String getField() {
return field;
}
public PurityNode getTarget() {
return target;
}
public PurityNode getSource() {
return source;
}
public boolean isInside() {
return inside;
}
@Override
public int hashCode() {
return field.hashCode() + target.hashCode() + source.hashCode() + (inside ? 69 : 0);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PurityEdge)) {
return false;
}
PurityEdge e = (PurityEdge) o;
return source.equals(e.source) && field.equals(e.field) && target.equals(e.target) && inside == e.inside;
}
@Override
public String toString() {
if (inside) {
return source.toString() + " = " + field + " => " + target.toString();
} else {
return source.toString() + " - " + field + " -> " + target.toString();
}
}
}
| 2,374
| 27.614458
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityGlobalNode.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* The GBL node.
*/
public class PurityGlobalNode implements PurityNode {
public static final PurityGlobalNode node = new PurityGlobalNode();
private PurityGlobalNode() {
}
@Override
public String toString() {
return "GBL";
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object o) {
return o instanceof PurityGlobalNode;
}
@Override
public boolean isInside() {
return false;
}
@Override
public boolean isLoad() {
return false;
}
@Override
public boolean isParam() {
return false;
}
}
| 1,442
| 21.2
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityGraph.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Local;
import soot.RefLikeType;
import soot.SootMethod;
import soot.Type;
import soot.Value;
import soot.jimple.Stmt;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
import soot.util.dot.DotGraph;
import soot.util.dot.DotGraphEdge;
import soot.util.dot.DotGraphNode;
/**
* Purity graphs are mutable structures that are updated in-place. You can safely hash graphs. Equality comparison means
* isomorphism (equal nodes, equal edges).
*
* Modifications with respect to the article:
*
* - "unanalizable call" are treated by first constructing a conservative callee graph where all parameters escape globally
* and return points to the global node, and then applying the standard analysable call construction
*
* - unanalysable calls add a mutation on the global node; the "field" is named "outside-world" and models the mutation of
* any static field, but also side-effects by native methods, such as I/O, that make methods impure (see below).
*
* - Whenever a method mutates the global node, it is marked as "impure" (this can be due to a side-effect or static field
* mutation), even if the global node is not reachable from parameter nodes through outside edges. It seems to me it was a
* defect from the article ? TODO: see if we must take the global node into account also when stating whether a parameter is
* read-only or safe.
*
* - "simplifyXXX" functions are experimental... they may be unsound, and thus, not used now.
*
* NOTE: A lot of precision degradation comes from sequences of the form this.field = y; z = this.field in initialisers: the
* second statement creates a load node because, as a parameter, this may have escaped and this.field may be externally
* modified in-between the two instructions. I am not sure this can actually happen in an initialiser... in a a function
* called directly and only by initialisers.
*
* For the moment, summary of unanalised methods are either pure, completely impure (modify args & side-effects) or partially
* impure (modify args but not the global node). We should really be able to specify more precisely which arguments are r/o
* or safe within this methods. E.g., the analysis java.lang.String: void getChars(int,int,char [],int) imprecisely finds
* that this is not safe (because of the internal call to System.arraycopy that, in general, may introduce aliases) => it
* pollutes many things (e.g., StringBuffer append(String), and thus, exception constructors, etc.)
*
*/
public class PurityGraph {
private static final Logger logger = LoggerFactory.getLogger(PurityGraph.class);
public static final boolean doCheck = false;
// Caching: this seems to actually improve both speed and memory consumption!
private static final Map<PurityNode, PurityNode> nodeCache = new HashMap<PurityNode, PurityNode>();
private static final Map<PurityEdge, PurityEdge> edgeCache = new HashMap<PurityEdge, PurityEdge>();
// A parameter (or this) can be: - read and write - read only - safe (read only & no externally visible alias is created)
static final int PARAM_RW = 0;
static final int PARAM_RO = 1;
static final int PARAM_SAFE = 2;
// Simple statistics on maximal graph sizes.
private static int maxInsideNodes = 0;
private static int maxLoadNodes = 0;
private static int maxInsideEdges = 0;
private static int maxOutsideEdges = 0;
private static int maxMutated = 0;
protected Set<PurityNode> nodes; // all nodes
protected Set<PurityNode> paramNodes; // only parameter & this nodes
protected MultiMap<PurityNode, PurityEdge> edges; // source node -> edges
protected MultiMap<Local, PurityNode> locals; // local -> nodes
protected Set<PurityNode> ret; // return -> nodes
protected Set<PurityNode> globEscape; // nodes escaping globally
protected MultiMap<PurityNode, PurityEdge> backEdges; // target node -> edges
protected MultiMap<PurityNode, Local> backLocals; // target node -> local node sources
protected MultiMap<PurityNode, String> mutated; // node -> field such that (node,field) is mutated
/**
* Initially empty graph.
*/
PurityGraph() {
// nodes & paramNodes are added lazily
this.nodes = new HashSet<PurityNode>();
this.paramNodes = new HashSet<PurityNode>();
this.edges = new HashMultiMap<PurityNode, PurityEdge>();
this.locals = new HashMultiMap<Local, PurityNode>();
this.ret = new HashSet<PurityNode>();
this.globEscape = new HashSet<PurityNode>();
this.backEdges = new HashMultiMap<PurityNode, PurityEdge>();
this.backLocals = new HashMultiMap<PurityNode, Local>();
this.mutated = new HashMultiMap<PurityNode, String>();
if (doCheck) {
sanityCheck();
}
}
/**
* Copy constructor.
*/
PurityGraph(PurityGraph x) {
this.nodes = new HashSet<PurityNode>(x.nodes);
this.paramNodes = new HashSet<PurityNode>(x.paramNodes);
this.edges = new HashMultiMap<PurityNode, PurityEdge>(x.edges);
this.locals = new HashMultiMap<Local, PurityNode>(x.locals);
this.ret = new HashSet<PurityNode>(x.ret);
this.globEscape = new HashSet<PurityNode>(x.globEscape);
this.backEdges = new HashMultiMap<PurityNode, PurityEdge>(x.backEdges);
this.backLocals = new HashMultiMap<PurityNode, Local>(x.backLocals);
this.mutated = new HashMultiMap<PurityNode, String>(x.mutated);
if (doCheck) {
sanityCheck();
}
}
@Override
public int hashCode() {
return nodes.hashCode()
// + paramNodes.hashCode() // redundant info
+ edges.hashCode() + locals.hashCode() + ret.hashCode() + globEscape.hashCode()
// + backEdges.hashCode() // redundant info
// + backLocals.hashCode() // redundant info
+ mutated.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PurityGraph)) {
return false;
}
PurityGraph g = (PurityGraph) o;
return nodes.equals(g.nodes)
// && paramNodes.equals(g.paramNodes) // redundant info
&& edges.equals(g.edges) && locals.equals(g.locals) && ret.equals(g.ret) && globEscape.equals(g.globEscape)
// && backEdges.equals(g.backEdges) // redundant info
// && backLocals.equals(g.backLocals) // redundant info
&& mutated.equals(g.mutated);
}
private static PurityNode cacheNode(PurityNode p) {
if (!nodeCache.containsKey(p)) {
nodeCache.put(p, p);
}
return nodeCache.get(p);
}
private static PurityEdge cacheEdge(PurityEdge e) {
if (!edgeCache.containsKey(e)) {
edgeCache.put(e, e);
}
return edgeCache.get(e);
}
/**
* Conservative constructor for unanalysable calls.
*
* <p>
* Note: this gives a valid summary for all native methods, including Thread.start().
*
* @param withEffect
* add a mutated abstract field for the global node to account for side-effects in the environment (I/O, etc.).
*/
public static PurityGraph conservativeGraph(SootMethod m, boolean withEffect) {
PurityGraph g = new PurityGraph();
PurityNode glob = PurityGlobalNode.node;
g.nodes.add(glob);
// parameters & this escape globally
int i = 0;
for (Type next : m.getParameterTypes()) {
if (next instanceof RefLikeType) {
PurityNode n = cacheNode(new PurityParamNode(i));
g.globEscape.add(n);
g.nodes.add(n);
g.paramNodes.add(n);
}
i++;
}
// return value escapes globally
if (m.getReturnType() instanceof RefLikeType) {
g.ret.add(glob);
}
// add a side-effect on the environment
// added by [AM]
if (withEffect) {
g.mutated.put(glob, "outside-world");
}
if (doCheck) {
g.sanityCheck();
}
return g;
}
/**
* Special constructor for "pure" methods returning a fresh object. (or simply pure if returns void or primitive).
*/
public static PurityGraph freshGraph(SootMethod m) {
PurityGraph g = new PurityGraph();
if (m.getReturnType() instanceof RefLikeType) {
PurityNode n = cacheNode(new PurityMethodNode(m));
g.ret.add(n);
g.nodes.add(n);
}
if (doCheck) {
g.sanityCheck();
}
return g;
}
/**
* Replace the current graph with its union with arg. arg is not modified.
*/
void union(PurityGraph arg) {
this.nodes.addAll(arg.nodes);
this.paramNodes.addAll(arg.paramNodes);
this.edges.putAll(arg.edges);
this.locals.putAll(arg.locals);
this.ret.addAll(arg.ret);
this.globEscape.addAll(arg.globEscape);
this.backEdges.putAll(arg.backEdges);
this.backLocals.putAll(arg.backLocals);
this.mutated.putAll(arg.mutated);
if (doCheck) {
sanityCheck();
}
}
/**
* Sanity check. Used internally for debugging!
*/
protected void sanityCheck() {
boolean err = false;
for (PurityNode src : edges.keySet()) {
for (PurityEdge e : edges.get(src)) {
if (!src.equals(e.getSource())) {
logger.debug("invalid edge source " + e + ", should be " + src);
err = true;
}
if (!nodes.contains(e.getSource())) {
logger.debug("nodes does not contain edge source " + e);
err = true;
}
if (!nodes.contains(e.getTarget())) {
logger.debug("nodes does not contain edge target " + e);
err = true;
}
if (!backEdges.get(e.getTarget()).contains(e)) {
logger.debug("backEdges does not contain edge " + e);
err = true;
}
if (!e.isInside() && !e.getTarget().isLoad()) {
logger.debug("target of outside edge is not a load node " + e);
err = true;
}
}
}
for (PurityNode dst : backEdges.keySet()) {
for (PurityEdge e : backEdges.get(dst)) {
if (!dst.equals(e.getTarget())) {
logger.debug("invalid backEdge dest " + e + ", should be " + dst);
err = true;
}
if (!edges.get(e.getSource()).contains(e)) {
logger.debug("backEdge not in edges " + e);
err = true;
}
}
}
for (PurityNode n : nodes) {
if (n.isParam() && !paramNodes.contains(n)) {
logger.debug("paramNode not in paramNodes " + n);
err = true;
}
}
for (PurityNode n : paramNodes) {
if (!n.isParam()) {
logger.debug("paramNode contains a non-param node " + n);
err = true;
}
if (!nodes.contains(n)) {
logger.debug("paramNode not in nodes " + n);
err = true;
}
}
for (PurityNode n : globEscape) {
if (!nodes.contains(n)) {
logger.debug("globEscape not in nodes " + n);
err = true;
}
}
for (Local l : locals.keySet()) {
for (PurityNode n : locals.get(l)) {
if (!nodes.contains(n)) {
logger.debug("target of local node in nodes " + l + " / " + n);
err = true;
}
if (!backLocals.get(n).contains(l)) {
logger.debug("backLocals does contain local " + l + " / " + n);
err = true;
}
}
}
for (PurityNode n : backLocals.keySet()) {
for (Local l : backLocals.get(n)) {
if (!nodes.contains(n)) {
logger.debug("backLocal node not in in nodes " + l + " / " + n);
err = true;
}
if (!locals.get(l).contains(n)) {
logger.debug("locals does contain backLocal " + l + " / " + n);
err = true;
}
}
}
for (PurityNode n : ret) {
if (!nodes.contains(n)) {
logger.debug("target of ret not in nodes " + n);
err = true;
}
}
for (PurityNode n : mutated.keySet()) {
if (!nodes.contains(n)) {
logger.debug("mutated node not in nodes " + n);
err = true;
}
}
if (err) {
dump();
DotGraph dot = new DotGraph("sanityCheckFailure");
fillDotGraph("chk", dot);
dot.plot("sanityCheckFailure.dot");
throw new Error("PurityGraph sanity check failed!!!");
}
}
////////////////////////
// ESCAPE INFORMATION //
////////////////////////
protected void internalPassEdges(Set<PurityEdge> toColor, Set<PurityNode> dest, boolean consider_inside) {
for (PurityEdge edge : toColor) {
if (consider_inside || !edge.isInside()) {
PurityNode node = edge.getTarget();
if (!dest.contains(node)) {
dest.add(node);
internalPassEdges(edges.get(node), dest, consider_inside);
}
}
}
}
protected void internalPassNode(PurityNode node, Set<PurityNode> dest, boolean consider_inside) {
if (!dest.contains(node)) {
dest.add(node);
internalPassEdges(edges.get(node), dest, consider_inside);
}
}
protected void internalPassNodes(Set<PurityNode> toColor, Set<PurityNode> dest, boolean consider_inside) {
for (PurityNode n : toColor) {
internalPassNode(n, dest, consider_inside);
}
}
protected Set<PurityNode> getEscaping() {
Set<PurityNode> escaping = new HashSet<PurityNode>();
internalPassNodes(ret, escaping, true);
internalPassNodes(globEscape, escaping, true);
internalPassNode(PurityGlobalNode.node, escaping, true);
internalPassNodes(paramNodes, escaping, true);
return escaping;
}
/**
* Call this on the merge of graphs at all return points of a method to know whether the method is pure.
*/
public boolean isPure() {
if (!mutated.get(PurityGlobalNode.node).isEmpty()) {
return false;
}
Set<PurityNode> A = new HashSet<PurityNode>();
Set<PurityNode> B = new HashSet<PurityNode>();
internalPassNodes(paramNodes, A, false);
internalPassNodes(globEscape, B, true);
internalPassNode(PurityGlobalNode.node, B, true);
for (PurityNode n : A) {
if (B.contains(n) || !mutated.get(n).isEmpty()) {
return false;
}
}
return true;
}
/**
* We use a less restrictive notion of purity for constructors: pure constructors can mutate fields of this.
*
* @see isPure
*/
public boolean isPureConstructor() {
if (!mutated.get(PurityGlobalNode.node).isEmpty()) {
return false;
}
Set<PurityNode> A = new HashSet<PurityNode>();
Set<PurityNode> B = new HashSet<PurityNode>();
internalPassNodes(paramNodes, A, false);
internalPassNodes(globEscape, B, true);
internalPassNode(PurityGlobalNode.node, B, true);
PurityNode th = PurityThisNode.node;
for (PurityNode n : A) {
if (B.contains(n) || (!n.equals(th) && !mutated.get(n).isEmpty())) {
return false;
}
}
return true;
}
protected int internalParamStatus(PurityNode p) {
if (!paramNodes.contains(p)) {
return PARAM_RW;
}
Set<PurityNode> S1 = new HashSet<PurityNode>();
internalPassNode(p, S1, false);
for (PurityNode n : S1) {
if (n.isLoad() || n.equals(p)) {
if (!mutated.get(n).isEmpty() || globEscape.contains(n)) {
return PARAM_RW;
}
}
}
Set<PurityNode> S2 = new HashSet<PurityNode>();
internalPassNodes(ret, S2, true);
internalPassNodes(paramNodes, S2, true);
for (PurityNode n : S2) {
for (PurityEdge e : edges.get(n)) {
if (e.isInside() && S1.contains(e.getTarget())) {
return PARAM_RO;
}
}
}
return PARAM_SAFE;
}
/**
* Call this on the merge of graphs at all return points of a method to know whether an object passed as method parameter
* is read only (PARAM_RO), read write (PARAM_RW), or safe (PARAM_SAFE). Returns PARAM_RW for primitive-type parameters.
*/
public int paramStatus(int param) {
return internalParamStatus(cacheNode(new PurityParamNode(param)));
}
/**
* @see isParamReadOnly
*/
public int thisStatus() {
return internalParamStatus(PurityThisNode.node);
}
/////////////////////////
// GRAPH MANUPULATIONS //
/////////////////////////
@Override
public Object clone() {
return new PurityGraph(this);
}
// utility functions to update local / backLocals constitently
protected final boolean localsRemove(Local local) {
for (PurityNode node : locals.get(local)) {
backLocals.remove(node, local);
}
return locals.remove(local);
}
protected final boolean localsPut(Local local, PurityNode node) {
backLocals.put(node, local);
return locals.put(local, node);
}
protected final boolean localsPutAll(Local local, Set<PurityNode> nodes) {
for (PurityNode node : nodes) {
backLocals.put(node, local);
}
return locals.putAll(local, nodes);
}
/** Utility function to remove a node & all adjacent edges */
protected final void removeNode(PurityNode n) {
for (PurityEdge e : edges.get(n)) {
backEdges.remove(e.getTarget(), e);
}
for (PurityEdge e : backEdges.get(n)) {
edges.remove(e.getSource(), e);
}
for (Local l : backLocals.get(n)) {
locals.remove(l, n);
}
ret.remove(n);
edges.remove(n);
backEdges.remove(n);
backLocals.remove(n);
nodes.remove(n);
paramNodes.remove(n);
globEscape.remove(n);
mutated.remove(n);
}
/** Utility function to merge node src into dst; src is removed */
protected final void mergeNodes(PurityNode src, PurityNode dst) {
for (PurityEdge e : new ArrayList<PurityEdge>(edges.get(src))) {
PurityNode n = e.getTarget();
if (n.equals(src)) {
n = dst;
}
PurityEdge ee = cacheEdge(new PurityEdge(dst, e.getField(), n, e.isInside()));
edges.remove(src, e);
edges.put(dst, ee);
backEdges.remove(n, e);
backEdges.put(n, ee);
}
for (PurityEdge e : new ArrayList<PurityEdge>(backEdges.get(src))) {
PurityNode n = e.getSource();
if (n.equals(src)) {
n = dst;
}
PurityEdge ee = cacheEdge(new PurityEdge(n, e.getField(), dst, e.isInside()));
edges.remove(n, e);
edges.put(n, ee);
backEdges.remove(src, e);
backEdges.put(dst, ee);
}
for (Local l : new ArrayList<Local>(backLocals.get(src))) {
locals.remove(l, src);
backLocals.remove(src, l);
locals.put(l, dst);
backLocals.put(dst, l);
}
{
Set<String> m = mutated.get(src);
mutated.remove(src);
mutated.putAll(dst, m);
}
if (ret.contains(src)) {
ret.remove(src);
ret.add(dst);
}
if (globEscape.contains(src)) {
globEscape.remove(src);
globEscape.add(dst);
}
nodes.remove(src);
nodes.add(dst);
paramNodes.remove(src);
if (dst.isParam()) {
paramNodes.add(dst);
}
}
/** Experimental simplification: merge redundant load nodes. */
void simplifyLoad() {
for (PurityNode p : new ArrayList<PurityNode>(nodes)) {
Map<String, PurityNode> fmap = new HashMap<String, PurityNode>();
for (PurityEdge e : new ArrayList<PurityEdge>(edges.get(p))) {
PurityNode tgt = e.getTarget();
if (!e.isInside() && !tgt.equals(p)) {
String f = e.getField();
if (fmap.containsKey(f) && nodes.contains(fmap.get(f))) {
mergeNodes(tgt, fmap.get(f));
} else {
fmap.put(f, tgt);
}
}
}
}
if (doCheck) {
sanityCheck();
}
}
/**
* Experimental simplification: remove inside nodes not reachable from escaping nodes (params, ret, globEscape) or load
* nodes.
*/
void simplifyInside() {
Set<PurityNode> r = new HashSet<PurityNode>();
internalPassNodes(paramNodes, r, true);
internalPassNodes(ret, r, true);
internalPassNodes(globEscape, r, true);
internalPassNode(PurityGlobalNode.node, r, true);
for (PurityNode n : nodes) {
if (n.isLoad()) {
internalPassNode(n, r, true);
}
}
for (PurityNode n : new ArrayList<PurityNode>(nodes)) {
if (n.isInside() && !r.contains(n)) {
removeNode(n);
}
}
if (doCheck) {
sanityCheck();
}
}
/**
* Remove all local bindings (except ret). This info is indeed superfluous on summary purity graphs representing the effect
* of a method. This saves a little memory, but also, simplify summary graph drawings a lot!
*
* DO NOT USE DURING INTRA-PROCEDURAL ANALYSIS!
*/
void removeLocals() {
this.locals = new HashMultiMap<Local, PurityNode>();
this.backLocals = new HashMultiMap<PurityNode, Local>();
}
/** Copy assignment left = right. */
void assignParamToLocal(int right, Local left) {
// strong update on local
PurityNode node = cacheNode(new PurityParamNode(right));
localsRemove(left);
localsPut(left, node);
nodes.add(node);
paramNodes.add(node);
if (doCheck) {
sanityCheck();
}
}
/** Copy assignment left = this. */
void assignThisToLocal(Local left) {
// strong update on local
PurityNode node = PurityThisNode.node;
localsRemove(left);
localsPut(left, node);
nodes.add(node);
paramNodes.add(node);
if (doCheck) {
sanityCheck();
}
}
/** Copy assignment left = right. */
void assignLocalToLocal(Local right, Local left) {
// strong update on local
localsRemove(left);
localsPutAll(left, locals.get(right));
if (doCheck) {
sanityCheck();
}
}
/** return right statement . */
void returnLocal(Local right) {
// strong update on ret
ret.clear();
ret.addAll(locals.get(right));
if (doCheck) {
sanityCheck();
}
}
/**
* Load non-static: left = right.field, or left = right[?] if field is [].
*/
void assignFieldToLocal(Stmt stmt, Local right, String field, Local left) {
Set<PurityNode> esc = new HashSet<PurityNode>();
Set<PurityNode> escaping = getEscaping();
// strong update on local
localsRemove(left);
for (PurityNode nodeRight : locals.get(right)) {
for (PurityEdge edge : edges.get(nodeRight)) {
if (edge.isInside() && edge.getField().equals(field)) {
localsPut(left, edge.getTarget());
}
}
if (escaping.contains(nodeRight)) {
esc.add(nodeRight);
}
}
if (!esc.isEmpty()) {
// right can escape
// we add a label load node & outside edges
PurityNode loadNode = cacheNode(new PurityStmtNode(stmt, false));
nodes.add(loadNode);
for (PurityNode node : esc) {
PurityEdge edge = cacheEdge(new PurityEdge(node, field, loadNode, false));
if (edges.put(node, edge)) {
backEdges.put(loadNode, edge);
}
}
localsPut(left, loadNode);
}
if (doCheck) {
sanityCheck();
}
}
/**
* Store non-static: left.field = right, or left[?] = right if field is [].
*/
void assignLocalToField(Local right, Local left, String field) {
for (PurityNode nodeLeft : locals.get(left)) {
for (PurityNode nodeRight : locals.get(right)) {
PurityEdge edge = cacheEdge(new PurityEdge(nodeLeft, field, nodeRight, true));
if (edges.put(nodeLeft, edge)) {
backEdges.put(nodeRight, edge);
}
}
if (!nodeLeft.isInside()) {
mutated.put(nodeLeft, field);
}
}
// weak update on inside edges
if (doCheck) {
sanityCheck();
}
}
/** Allocation: left = new or left = new[?]. */
void assignNewToLocal(Stmt stmt, Local left) {
// strong update on local
// we add a label inside node
PurityNode node = cacheNode(new PurityStmtNode(stmt, true));
localsRemove(left);
localsPut(left, node);
nodes.add(node);
if (doCheck) {
sanityCheck();
}
}
/** A local variable is used in an unknown construct. */
void localEscapes(Local l) {
// nodes escape globally
globEscape.addAll(locals.get(l));
if (doCheck) {
sanityCheck();
}
}
/** A local variable is assigned to some outside value. */
void localIsUnknown(Local l) {
// strong update on local
PurityNode node = PurityGlobalNode.node;
localsRemove(l);
localsPut(l, node);
nodes.add(node);
if (doCheck) {
sanityCheck();
}
}
/**
* Store static: C.field = right.
*/
void assignLocalToStaticField(Local right, String field) {
PurityNode node = PurityGlobalNode.node;
localEscapes(right);
mutated.put(node, field);
nodes.add(node);
if (doCheck) {
sanityCheck();
}
}
/**
* Store a primitive type into a non-static field left.field = v
*/
void mutateField(Local left, String field) {
for (PurityNode n : locals.get(left)) {
if (!n.isInside()) {
mutated.put(n, field);
}
}
if (doCheck) {
sanityCheck();
}
}
/**
* Store a primitive type into a static field left.field = v
*/
void mutateStaticField(String field) {
PurityNode node = PurityGlobalNode.node;
mutated.put(node, field);
nodes.add(node);
if (doCheck) {
sanityCheck();
}
}
/**
* Method call left = right.method(args).
*
* @param g
* is method's summary PurityGraph
* @param left
* can be null (no return value)
* @param right
* can be null (static call)
* @param args
* is a list of Value
*/
void methodCall(PurityGraph g, Local right, List<Value> args, Local left) {
MultiMap<PurityNode, PurityNode> mu = new HashMultiMap<PurityNode, PurityNode>();
// compute mapping relation g -> this
/////////////////////////////////////
// (1) rule
int nb = 0;
for (Value arg : args) {
if (arg instanceof Local) {
Local loc = (Local) arg;
if (loc.getType() instanceof RefLikeType) {
mu.putAll(cacheNode(new PurityParamNode(nb)), locals.get(loc));
}
}
nb++;
}
if (right != null) {
mu.putAll(PurityThisNode.node, locals.get(right));
}
// COULD BE OPTIMIZED!
// many times, we need to copy sets cause we mutate them within iterators
for (boolean hasChanged = true; hasChanged;) { // (2) & (3) rules fixpoint
hasChanged = false;
// (2)
for (PurityNode n1 : new ArrayList<PurityNode>(mu.keySet())) {
for (PurityNode n3 : new ArrayList<PurityNode>(mu.get(n1))) {
for (PurityEdge e12 : g.edges.get(n1)) {
if (!e12.isInside()) {
for (PurityEdge e34 : edges.get(n3)) {
if (e34.isInside() && e12.getField().equals(e34.getField())) {
if (mu.put(e12.getTarget(), e34.getTarget())) {
hasChanged = true;
}
}
}
}
}
}
}
// (3)
for (PurityNode n1 : g.edges.keySet()) {
for (PurityNode n3 : g.edges.keySet()) {
// ((mu(n1) U {n1}) inter (mu(n3) U {n3})) not empty
Set<PurityNode> mu1 = mu.get(n1);
Set<PurityNode> mu3 = mu.get(n3);
boolean cond = n1.equals(n3) || mu1.contains(n3) || mu3.contains(n1);
if (!cond) {
for (PurityNode next : mu1) {
cond |= mu3.contains(next);
if (cond) {
break;
}
}
}
// add (mu(n4) U ({n4} inter PNodes)) to mu(n2)
if (cond && (!n1.equals(n3) || n1.isLoad())) {
for (PurityEdge e12 : g.edges.get(n1)) {
if (!e12.isInside()) {
for (PurityEdge e34 : g.edges.get(n3)) {
if (e34.isInside()) {
if (e12.getField().equals(e34.getField())) {
PurityNode n2 = e12.getTarget();
PurityNode n4 = e34.getTarget();
// add n4 (if not param node) to mu(n2)
if (!n4.isParam() && mu.put(n2, n4)) {
hasChanged = true;
}
// add mu(n4) to mu(n2)
if (mu.putAll(n2, mu.get(n4))) {
hasChanged = true;
}
}
}
}
}
}
}
}
}
}
// extend mu into mu'
for (PurityNode n : g.nodes) {
if (!n.isParam()) {
mu.put(n, n);
nodes.add(n);
}
}
// combine g into this
//////////////////////
// project edges
for (PurityNode n1 : g.edges.keySet()) {
for (PurityEdge e12 : g.edges.get(n1)) {
String f = e12.getField();
PurityNode n2 = e12.getTarget();
for (PurityNode mu1 : mu.get(n1)) {
if (e12.isInside()) {
for (PurityNode mu2 : mu.get(n2)) {
PurityEdge edge = cacheEdge(new PurityEdge(mu1, f, mu2, true));
edges.put(mu1, edge);
backEdges.put(mu2, edge);
}
} else {
PurityEdge edge = cacheEdge(new PurityEdge(mu1, f, n2, false));
edges.put(mu1, edge);
backEdges.put(n2, edge);
}
}
}
}
// return value
if (left != null) {
// strong update on locals
localsRemove(left);
for (PurityNode next : g.ret) {
localsPutAll(left, mu.get(next));
}
}
// global escape
for (PurityNode next : g.globEscape) {
globEscape.addAll(mu.get(next));
}
if (doCheck) {
sanityCheck();
}
// simplification
/////////////////
Set<PurityNode> escaping = getEscaping();
for (PurityNode n : new ArrayList<PurityNode>(nodes)) {
if (!escaping.contains(n)) {
if (n.isLoad()) {
// remove captured load nodes
removeNode(n);
} else {
// ... and outside edges from captured nodes
for (PurityEdge e : new ArrayList<PurityEdge>(edges.get(n))) {
if (!e.isInside()) {
edges.remove(n, e);
backEdges.remove(e.getTarget(), e);
}
}
}
}
}
// update mutated
/////////////////
for (PurityNode n : g.mutated.keySet()) {
for (PurityNode nn : mu.get(n)) {
if (nodes.contains(nn) && !nn.isInside()) {
for (String next : g.mutated.get(n)) {
mutated.put(nn, next);
}
}
}
}
if (doCheck) {
sanityCheck();
}
}
/////////////
// DRAWING //
/////////////
/**
* Fills a dot graph or subgraph with the graphical representation of the purity graph.
*
* @param prefix
* is used to prefix all dot node and edge names. Use it to avoid collision when several subgraphs are laid in the
* same dot file!
*
* @param out
* is a newly created dot graph or subgraph where to put the result.
*
* <p>
* Note: outside edges, param and load nodes are gray dashed, while inside edges and nodes are solid black.
* Globally escaping nodes have a red label.
*/
void fillDotGraph(String prefix, DotGraph out) {
Map<PurityNode, String> nodeId = new HashMap<PurityNode, String>();
int id = 0;
// add nodes
for (PurityNode n : nodes) {
String label = "N" + prefix + "_" + id;
DotGraphNode node = out.drawNode(label);
node.setLabel(n.toString());
if (!n.isInside()) {
node.setStyle("dashed");
node.setAttribute("color", "gray50");
}
if (globEscape.contains(n)) {
node.setAttribute("fontcolor", "red");
}
nodeId.put(n, label);
id++;
}
// add edges
for (PurityNode src : edges.keySet()) {
for (PurityEdge e : edges.get(src)) {
DotGraphEdge edge = out.drawEdge(nodeId.get(e.getSource()), nodeId.get(e.getTarget()));
edge.setLabel(e.getField());
if (!e.isInside()) {
edge.setStyle("dashed");
edge.setAttribute("color", "gray50");
edge.setAttribute("fontcolor", "gray40");
}
}
}
// add locals
for (Local local : locals.keySet()) {
if (!locals.get(local).isEmpty()) {
String label = "L" + prefix + "_" + id;
DotGraphNode node = out.drawNode(label);
node.setLabel(local.toString());
node.setShape("plaintext");
for (PurityNode dst : locals.get(local)) {
out.drawEdge(label, nodeId.get(dst));
}
id++;
}
}
// ret
if (!ret.isEmpty()) {
DotGraphNode node = out.drawNode("ret_" + prefix);
node.setLabel("ret");
node.setShape("plaintext");
for (PurityNode dst : ret) {
out.drawEdge("ret_" + prefix, nodeId.get(dst));
}
}
// add mutated
for (PurityNode n : mutated.keySet()) {
for (String next : mutated.get(n)) {
String label = "M" + prefix + "_" + id;
DotGraphNode node = out.drawNode(label);
node.setLabel("");
node.setShape("plaintext");
DotGraphEdge edge = out.drawEdge(nodeId.get(n), label);
edge.setLabel(next);
id++;
}
}
}
/** Debugging... */
private static void dumpSet(String name, Set<PurityNode> s) {
logger.debug(name);
for (PurityNode next : s) {
logger.debug(" " + next);
}
}
private static <A, B> void dumpMultiMap(String name, MultiMap<A, B> s) {
logger.debug(name);
for (A key : s.keySet()) {
logger.debug(" " + key);
for (B value : s.get(key)) {
logger.debug(" " + value);
}
}
}
void dump() {
dumpSet("nodes Set:", nodes);
dumpSet("paramNodes Set:", paramNodes);
dumpMultiMap("edges MultiMap:", edges);
dumpMultiMap("locals MultiMap:", locals);
dumpSet("ret Set:", ret);
dumpSet("globEscape Set:", globEscape);
dumpMultiMap("backEdges MultiMap:", backEdges);
dumpMultiMap("backLocals MultiMap:", backLocals);
dumpMultiMap("mutated MultiMap:", mutated);
logger.debug("");
}
static void dumpStat() {
logger.debug("Stat: " + maxInsideNodes + " inNodes, " + maxLoadNodes + " loadNodes, " + maxInsideEdges + " inEdges, "
+ maxOutsideEdges + " outEdges, " + maxMutated + " mutated.");
}
void updateStat() {
int insideNodes = 0;
int loadNodes = 0;
for (PurityNode n : nodes) {
if (n.isInside()) {
insideNodes++;
} else if (n.isLoad()) {
loadNodes++;
}
}
int insideEdges = 0;
int outsideEdges = 0;
for (PurityNode next : edges.keySet()) {
for (PurityEdge e : edges.get(next)) {
if (e.isInside()) {
insideEdges++;
} else {
outsideEdges++;
}
}
}
int mutatedFields = 0;
for (PurityNode next : mutated.keySet()) {
mutatedFields += mutated.get(next).size();
}
boolean changed = false;
if (insideNodes > maxInsideNodes) {
maxInsideNodes = insideNodes;
changed = true;
}
if (loadNodes > maxLoadNodes) {
maxLoadNodes = loadNodes;
changed = true;
}
if (insideEdges > maxInsideEdges) {
maxInsideEdges = insideEdges;
changed = true;
}
if (outsideEdges > maxOutsideEdges) {
maxOutsideEdges = outsideEdges;
changed = true;
}
if (mutatedFields > maxMutated) {
maxMutated = mutatedFields;
changed = true;
}
if (changed) {
dumpStat();
}
}
}
| 36,356
| 29.34808
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityGraphBox.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Simple box class that encapsulates a reference to a PurityGraph.
*/
public class PurityGraphBox {
public PurityGraph g;
PurityGraphBox() {
this.g = new PurityGraph();
}
@Override
public int hashCode() {
return g.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof PurityGraphBox) {
PurityGraphBox oo = (PurityGraphBox) o;
return this.g.equals(oo.g);
} else {
return false;
}
}
}
| 1,316
| 24.823529
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityInterproceduralAnalysis.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Date;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Local;
import soot.RefLikeType;
import soot.SootMethod;
import soot.Type;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.options.PurityOptions;
import soot.tagkit.GenericAttribute;
import soot.tagkit.StringTag;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.util.dot.DotGraph;
public class PurityInterproceduralAnalysis extends AbstractInterproceduralAnalysis<PurityGraphBox> {
private static final Logger logger = LoggerFactory.getLogger(PurityInterproceduralAnalysis.class);
// Note: these method lists are adapted to JDK-1.4.2.06 and may
// not work for other versions
//
// unanalysed methods assumed pure (& return a new obj)
// class name prefix / method name
private static final String[][] pureMethods = { { "java.lang.", "valueOf" }, { "java.", "equals" }, { "javax.", "equals" },
{ "sun.", "equals" }, { "java.", "compare" }, { "javax.", "compare" }, { "sun.", "compare" }, { "java.", "getClass" },
{ "javax.", "getClass" }, { "sun.", "getClass" }, { "java.", "hashCode" }, { "javax.", "hashCode" },
{ "sun.", "hashCode" }, { "java.", "toString" }, { "javax.", "toString" }, { "sun.", "toString" },
{ "java.", "valueOf" }, { "javax.", "valueOf" }, { "sun.", "valueOf" }, { "java.", "compareTo" },
{ "javax.", "compareTo" }, { "sun.", "compareTo" }, { "java.lang.System", "identityHashCode" },
// we assume that all standard class initialisers are pure!!!
{ "java.", "<clinit>" }, { "javax.", "<clinit>" }, { "sun.", "<clinit>" },
// if we define these as pure, the analysis will find them impure as
// they call static native functions that could, in theory,
// change the whole program state under our feets
{ "java.lang.Math", "abs" }, { "java.lang.Math", "acos" }, { "java.lang.Math", "asin" }, { "java.lang.Math", "atan" },
{ "java.lang.Math", "atan2" }, { "java.lang.Math", "ceil" }, { "java.lang.Math", "cos" }, { "java.lang.Math", "exp" },
{ "java.lang.Math", "floor" }, { "java.lang.Math", "IEEEremainder" }, { "java.lang.Math", "log" },
{ "java.lang.Math", "max" }, { "java.lang.Math", "min" }, { "java.lang.Math", "pow" }, { "java.lang.Math", "rint" },
{ "java.lang.Math", "round" }, { "java.lang.Math", "sin" }, { "java.lang.Math", "sqrt" }, { "java.lang.Math", "tan" },
// TODO: put StrictMath as well ?
{ "java.lang.Throwable", "<init>" },
// to break the cycle exception -> getCharsAt -> exception
{ "java.lang.StringIndexOutOfBoundsException", "<init>" } };
// unanalysed methods that modify the whole environment
private static final String[][] impureMethods = { { "java.io.", "<init>" }, { "java.io.", "close" },
{ "java.io.", "read" }, { "java.io.", "write" }, { "java.io.", "flush" }, { "java.io.", "flushBuffer" },
{ "java.io.", "print" }, { "java.io.", "println" }, { "java.lang.Runtime",
"exit" }, /*
* // for soot... {"java.io.","skip"}, {"java.io.","ensureOpen"}, {"java.io.","fill"},
* {"java.io.","readLine"}, {"java.io.","available"}, {"java.io.","mark"}, {"java.io.","reset"},
* {"java.io.","toByteArray"}, {"java.io.","size"}, {"java.io.","writeTo"}, {"java.io.","readBoolean"},
* {"java.io.","readChar"}, {"java.io.","readDouble"}, {"java.io.","readFloat"}, {"java.io.","readByte"},
* {"java.io.","readShort"}, {"java.io.","readInt"}, {"java.io.","readLong"},
* {"java.io.","readUnsignedByte"}, {"java.io.","readUnsignedShort"}, {"java.io.","readUTF"},
* {"java.io.","readFully"}, {"java.io.","writeBoolean"}, {"java.io.","writeChar"},
* {"java.io.","writeChars"}, {"java.io.","writeDouble"}, {"java.io.","writeFloat"},
* {"java.io.","writeByte"}, {"java.io.","writeBytes"}, {"java.io.","writeShort"},
* {"java.io.","writeInt"}, {"java.io.","writeLong"}, {"java.io.","writeUTF"}, {"java.io.","canRead"},
* {"java.io.","delete"}, {"java.io.","exists"}, {"java.io.","isDirectory"}, {"java.io.","isFile"},
* {"java.io.","mkdir"}, {"java.io.","mkdirs"}, {"java.io.","getAbsoluteFile"},
* {"java.io.","getCanonicalFile"}, {"java.io.","getParentFile"}, {"java.io.","listFiles"},
* {"java.io.","getAbsolutePath"}, {"java.io.","getCanonicalPath"}, {"java.io.","getName"},
* {"java.io.","getParent"}, {"java.io.","getPath"}, {"java.io.","list"}, {"java.io.","toURI"},
* {"java.io.","lastModified"}, {"java.io.","length"}, {"java.io.","implies"},
* {"java.io.","newPermissionCollection"}, {"java.io.","getLineNumber"},
* {"java.io.","enableResolveObject"}, {"java.io.","readClassDescriptor"}, {"java.io.","readFields"},
* {"java.io.","readObject"}, {"java.io.","readUnshared"}, {"java.io.","defaultReadObject"},
* {"java.io.","defaultWriteObject"}, {"java.io.","putFields"}, {"java.io.","writeFields"},
* {"java.io.","writeObject"}, {"java.io.","writeUnshared"}, {"java.io.","unread"},
* {"java.io.","lineno"}, {"java.io.","nextToken"}, {"java.io.","commentChar"},
* {"java.io.","lowerCaseMode"}, {"java.io.","ordinaryChar"}, {"java.io.","quoteChar"},
* {"java.io.","resetSyntax"}, {"java.io.","slashSlashComments"}, {"java.io.","slashSltarComments"},
* {"java.io.","whitespaceChars"}, {"java.io.","wordChars"}, {"java.io.","markSupported"},
* {"java.","getCause"}, {"java.","getMessage"}, {"java.","getReason"},
*/ };
// unanalysed methods that alter its arguments, but have no side effect
private static final String[][] alterMethods = { { "java.lang.System", "arraycopy" },
// these are really huge methods used internally by StringBuffer
// printing => put here to speed-up the analysis
{ "java.lang.FloatingDecimal", "dtoa" }, { "java.lang.FloatingDecimal", "developLongDigits" },
{ "java.lang.FloatingDecimal", "big5pow" }, { "java.lang.FloatingDecimal", "getChars" },
{ "java.lang.FloatingDecimal", "roundup" } };
/**
* Filter out some method.
*/
private static 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) {
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;
}
/**
* @param stmt
* any statement containing an InvokeExpr
*
* @see PurityGraph.methodCall
*/
@Override
protected void applySummary(PurityGraphBox src, Stmt stmt, PurityGraphBox summary, PurityGraphBox dst) {
// extract call info
Local ret = null;
if (stmt instanceof AssignStmt) {
Local v = (Local) ((AssignStmt) stmt).getLeftOp();
if (v.getType() instanceof RefLikeType) {
ret = v;
}
}
Local obj = null;
InvokeExpr e = stmt.getInvokeExpr();
if (!(e instanceof StaticInvokeExpr)) {
obj = (Local) ((InstanceInvokeExpr) e).getBase();
}
// call methoCall on the PurityGraph
PurityGraph g = new PurityGraph(src.g);
g.methodCall(summary.g, obj, e.getArgs(), ret);
dst.g = g;
}
@Override
protected void fillDotGraph(String prefix, PurityGraphBox o, DotGraph out) {
o.g.fillDotGraph(prefix, out);
}
}
| 14,875
| 40.553073
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityIntraproceduralAnalysis.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Local;
import soot.RefLikeType;
import soot.SourceLocator;
import soot.Unit;
import soot.Value;
import soot.jimple.AnyNewExpr;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.BinopExpr;
import soot.jimple.BreakpointStmt;
import soot.jimple.CastExpr;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.Constant;
import soot.jimple.GotoStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.IfStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceOfExpr;
import soot.jimple.LookupSwitchStmt;
import soot.jimple.MonitorStmt;
import soot.jimple.NopStmt;
import soot.jimple.ParameterRef;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.jimple.TableSwitchStmt;
import soot.jimple.ThisRef;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
import soot.util.dot.DotGraph;
import soot.util.dot.DotGraphEdge;
import soot.util.dot.DotGraphNode;
/**
* Intra-procedural purity-graph analysis.
*
* You must pass an {@link AbstractInterproceduralAnalysis} object so that the intraprocedural part can resolve the effect of
* method calls.
*/
public class PurityIntraproceduralAnalysis extends ForwardFlowAnalysis<Unit, PurityGraphBox> {
private static final Logger logger = LoggerFactory.getLogger(PurityIntraproceduralAnalysis.class);
private final AbstractInterproceduralAnalysis<PurityGraphBox> inter;
/**
* Perform purity analysis on the Jimple unit graph g, as part of a larger interprocedural analysis. Once constructed, you
* may call copyResult and drawAsOneDot to query the analysis result.
*/
PurityIntraproceduralAnalysis(UnitGraph g, AbstractInterproceduralAnalysis<PurityGraphBox> inter) {
super(g);
this.inter = inter;
doAnalysis();
}
@Override
protected PurityGraphBox newInitialFlow() {
return new PurityGraphBox();
}
@Override
protected PurityGraphBox entryInitialFlow() {
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 flowThrough(PurityGraphBox inValue, Unit unit, PurityGraphBox outValue) {
Stmt stmt = (Stmt) unit;
outValue.g = new PurityGraph(inValue.g);
// ********************
// BIG PATTERN MATCHING
// ********************
// I throw much "match failure" Errors to ease debugging...
// => we could optimize the pattern matching a little bit
// logger.debug(" | |- exec "+stmt);
if (stmt.containsInvokeExpr()) {
///////////
// Calls //
///////////
inter.analyseCall(inValue, stmt, outValue);
} else if (stmt instanceof AssignStmt) {
/////////////
// AssignStmt
/////////////
Value leftOp = ((AssignStmt) stmt).getLeftOp();
Value rightOp = ((AssignStmt) stmt).getRightOp();
// v = ...
if (leftOp instanceof Local) {
// remove optional cast
if (rightOp instanceof CastExpr) {
rightOp = ((CastExpr) rightOp).getOp();
}
Local left = (Local) leftOp;
// ignore primitive types
if (!(left.getType() instanceof RefLikeType)) {
} else if (rightOp instanceof Local) {
// v = v
Local right = (Local) rightOp;
outValue.g.assignLocalToLocal(right, left);
} else if (rightOp instanceof ArrayRef) {
// v = v[i]
Local right = (Local) ((ArrayRef) rightOp).getBase();
outValue.g.assignFieldToLocal(stmt, right, "[]", left);
} else if (rightOp instanceof InstanceFieldRef) {
// v = v.f
Local right = (Local) ((InstanceFieldRef) rightOp).getBase();
String field = ((InstanceFieldRef) rightOp).getField().getName();
outValue.g.assignFieldToLocal(stmt, right, field, left);
} else if (rightOp instanceof StaticFieldRef) {
// v = C.f
outValue.g.localIsUnknown(left);
} else if (rightOp instanceof Constant) {
// v = cst
// do nothing...
} else if (rightOp instanceof AnyNewExpr) {
// v = new / newarray / newmultiarray
outValue.g.assignNewToLocal(stmt, left);
} else if (rightOp instanceof BinopExpr || rightOp instanceof UnopExpr || rightOp instanceof InstanceOfExpr) {
// v = binary or unary operator
// do nothing...
} else {
throw new Error("AssignStmt match failure (rightOp)" + stmt);
}
}
// v[i] = ...
else if (leftOp instanceof ArrayRef) {
Local left = (Local) ((ArrayRef) leftOp).getBase();
if (rightOp instanceof Local) {
// v[i] = v
Local right = (Local) rightOp;
if (right.getType() instanceof RefLikeType) {
outValue.g.assignLocalToField(right, left, "[]");
} else {
outValue.g.mutateField(left, "[]");
}
} else if (rightOp instanceof Constant) {
// v[i] = cst
outValue.g.mutateField(left, "[]");
} else {
throw new Error("AssignStmt match failure (rightOp)" + stmt);
}
} else if (leftOp instanceof InstanceFieldRef) {
// v.f = ...
Local left = (Local) ((InstanceFieldRef) leftOp).getBase();
String field = ((InstanceFieldRef) leftOp).getField().getName();
if (rightOp instanceof Local) {
// v.f = v
Local right = (Local) rightOp;
// ignore primitive types
if (right.getType() instanceof RefLikeType) {
outValue.g.assignLocalToField(right, left, field);
} else {
outValue.g.mutateField(left, field);
}
} else if (rightOp instanceof Constant) {
// v.f = cst
outValue.g.mutateField(left, field);
} else {
throw new Error("AssignStmt match failure (rightOp) " + stmt);
}
} else if (leftOp instanceof StaticFieldRef) {
// C.f = ...
String field = ((StaticFieldRef) leftOp).getField().getName();
// C.f = v
if (rightOp instanceof Local) {
Local right = (Local) rightOp;
if (right.getType() instanceof RefLikeType) {
outValue.g.assignLocalToStaticField(right, field);
} else {
outValue.g.mutateStaticField(field);
}
} else if (rightOp instanceof Constant) {
// C.f = cst
outValue.g.mutateStaticField(field);
} else {
throw new Error("AssignStmt match failure (rightOp) " + stmt);
}
} else {
throw new Error("AssignStmt match failure (leftOp) " + stmt);
}
} else if (stmt instanceof IdentityStmt) {
///////////////
// IdentityStmt
///////////////
Local left = (Local) ((IdentityStmt) stmt).getLeftOp();
Value rightOp = ((IdentityStmt) stmt).getRightOp();
if (rightOp instanceof ThisRef) {
outValue.g.assignThisToLocal(left);
} else if (rightOp instanceof ParameterRef) {
ParameterRef p = (ParameterRef) rightOp;
// ignore primitive types
if (p.getType() instanceof RefLikeType) {
outValue.g.assignParamToLocal(p.getIndex(), left);
}
} else if (rightOp instanceof CaughtExceptionRef) {
// local = exception
outValue.g.localIsUnknown(left);
} else {
throw new Error("IdentityStmt match failure (rightOp) " + stmt);
}
} else if (stmt instanceof ThrowStmt) {
////////////
// ThrowStmt
////////////
Value op = ((ThrowStmt) stmt).getOp();
if (op instanceof Local) {
Local v = (Local) op;
outValue.g.localEscapes(v);
} else if (op instanceof Constant) {
// do nothing...
} else {
throw new Error("ThrowStmt match failure " + stmt);
}
} else if (stmt instanceof ReturnVoidStmt) {
/////////////
// ReturnStmt
/////////////
// do nothing...
} else if (stmt instanceof ReturnStmt) {
Value v = ((ReturnStmt) stmt).getOp();
if (v instanceof Local) {
// ignore primitive types
if (v.getType() instanceof RefLikeType) {
outValue.g.returnLocal((Local) v);
}
} else if (v instanceof Constant) {
// do nothing...
} else {
throw new Error("ReturnStmt match failure " + stmt);
}
} else if (stmt instanceof IfStmt || stmt instanceof GotoStmt || stmt instanceof LookupSwitchStmt
|| stmt instanceof TableSwitchStmt || stmt instanceof MonitorStmt || stmt instanceof BreakpointStmt
|| stmt instanceof NopStmt) {
//////////
// ignored
//////////
// do nothing...
} else {
throw new Error("Stmt match faliure " + stmt);
}
// outValue.g.updateStat();
}
/**
* Draw the result of the intra-procedural analysis as one big dot file, named className.methodName.dot, containing one
* purity graph for each statement in the method.
*
* @param prefix
* @param name
*/
public void drawAsOneDot(String prefix, String name) {
DotGraph dot = new DotGraph(name);
dot.setGraphLabel(name);
dot.setGraphAttribute("compound", "true");
dot.setGraphAttribute("rankdir", "LR");
Map<Unit, Integer> node = new HashMap<Unit, Integer>();
int id = 0;
for (Unit stmt : graph) {
DotGraph sub = dot.createSubGraph("cluster" + id);
DotGraphNode label = sub.drawNode("head" + id);
String lbl = stmt.toString();
if (lbl.startsWith("lookupswitch")) {
lbl = "lookupswitch...";
} else if (lbl.startsWith("tableswitch")) {
lbl = "tableswitch...";
}
sub.setGraphLabel(" ");
label.setLabel(lbl);
label.setAttribute("fontsize", "18");
label.setShape("box");
getFlowAfter(stmt).g.fillDotGraph("X" + id, sub);
node.put(stmt, id);
id++;
}
for (Unit src : graph) {
for (Unit dst : graph.getSuccsOf(src)) {
DotGraphEdge edge = dot.drawEdge("head" + node.get(src), "head" + node.get(dst));
edge.setAttribute("ltail", "cluster" + node.get(src));
edge.setAttribute("lhead", "cluster" + node.get(dst));
}
}
File f = new File(SourceLocator.v().getOutputDir(), prefix + name + DotGraph.DOT_EXTENSION);
dot.plot(f.getPath());
}
/**
* Put into dst the purity graph obtained by merging all purity graphs at the method return. It is a valid summary that can
* be used in methodCall if you do interprocedural analysis.
*
* @param dst
*/
public void copyResult(PurityGraphBox dst) {
PurityGraph r = new PurityGraph();
for (Unit u : graph.getTails()) {
r.union(getFlowAfter(u).g);
}
r.removeLocals();
// r.simplifyLoad();
// r.simplifyInside();
// r.updateStat();
dst.g = r;
}
}
| 12,225
| 32.404372
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityMethodNode.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import soot.SootMethod;
/**
* Kind of Stmt inside node, but global to the method. Used for synthetic summary of analysed methods returning a fresh
* object.
*/
public 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) {
if (o instanceof PurityMethodNode) {
PurityMethodNode oo = (PurityMethodNode) o;
return this.id.equals(oo.id);
} else {
return false;
}
}
@Override
public boolean isInside() {
return true;
}
@Override
public boolean isLoad() {
return false;
}
@Override
public boolean isParam() {
return false;
}
}
| 2,045
| 22.790698
| 119
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityNode.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Interface shared by all kinds of nodes in a PurityGraph. Such nodes are immutable. They are hashable and two nodes are
* equal only if they have the same kind and were constructed using the same arguments (structural equality).
*/
public interface PurityNode {
/** Is it an inside node ? */
public boolean isInside();
/** Is it a load node ? */
public boolean isLoad();
/** Is it a parameter or this node ? */
public boolean isParam();
}
| 1,308
| 31.725
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityParamNode.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A node representing a method parameter. Each method parameter has a number, starting from 0.
*/
public 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) {
if (o instanceof PurityParamNode) {
return this.id == ((PurityParamNode) o).id;
} else {
return false;
}
}
@Override
public boolean isInside() {
return false;
}
@Override
public boolean isLoad() {
return false;
}
@Override
public boolean isParam() {
return true;
}
}
| 1,580
| 21.585714
| 95
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityStmtNode.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import soot.jimple.Stmt;
/**
* A node created dynamically and attached to a statement Stmt. Can be either an inside or a load node. Two such nodes are
* equal if and only if they have the same inside / load flag and are attached to the same statement (we use Stmt.equal
* here).
*/
public 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) {
if (o instanceof PurityStmtNode) {
PurityStmtNode oo = (PurityStmtNode) o;
return this.id.equals(oo.id) && this.inside == oo.inside;
} else {
return false;
}
}
@Override
public boolean isInside() {
return inside;
}
@Override
public boolean isLoad() {
return !inside;
}
@Override
public boolean isParam() {
return false;
}
}
| 2,340
| 24.725275
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/PurityThisNode.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A node representing the this parameter.
*/
public class PurityThisNode extends PurityParamNode {
public static PurityThisNode node = new PurityThisNode();
private PurityThisNode() {
super(-1);
}
@Override
public String toString() {
return "this";
}
@Override
public boolean isInside() {
return false;
}
@Override
public boolean isLoad() {
return false;
}
@Override
public boolean isParam() {
return true;
}
}
| 1,319
| 22.571429
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/purity/SootMethodFilter.java
|
package soot.jimple.toolkits.annotation.purity;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Antoine Mine
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
/**
* Allows specifying which SootMethod you want to analyse in a AbstractInterproceduralAnalysis.
*
* You will need a way to provide a summary for unanalysed methods that are used by analysed code!
*/
public interface SootMethodFilter {
public boolean want(SootMethod m);
}
| 1,154
| 30.216216
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/qualifiers/TightestQualifiersTagger.java
|
package soot.jimple.toolkits.annotation.qualifiers;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.G;
import soot.MethodOrMethodContext;
import soot.MethodToContexts;
import soot.Modifier;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Value;
import soot.ValueBox;
import soot.jimple.FieldRef;
import soot.jimple.toolkits.callgraph.CallGraph;
import soot.jimple.toolkits.callgraph.Edge;
import soot.tagkit.ColorTag;
import soot.tagkit.StringTag;
/**
* a scene transformer that add tags to indicate the tightest qualifies possible for fields and methods (ie: private,
* protected or public)
*/
public class TightestQualifiersTagger extends SceneTransformer {
public TightestQualifiersTagger(Singletons.Global g) {
}
public static TightestQualifiersTagger v() {
return G.v().soot_jimple_toolkits_annotation_qualifiers_TightestQualifiersTagger();
}
public final static int RESULT_PUBLIC = 0;
public final static int RESULT_PACKAGE = 1;
public final static int RESULT_PROTECTED = 2;
public final static int RESULT_PRIVATE = 3;
private final HashMap<SootMethod, Integer> methodResultsMap = new HashMap<SootMethod, Integer>();
private final HashMap<SootField, Integer> fieldResultsMap = new HashMap<SootField, Integer>();
private MethodToContexts methodToContexts;
protected void internalTransform(String phaseName, Map options) {
handleMethods();
handleFields();
}
private void handleMethods() {
Iterator classesIt = Scene.v().getApplicationClasses().iterator();
while (classesIt.hasNext()) {
SootClass appClass = (SootClass) classesIt.next();
Iterator methsIt = appClass.getMethods().iterator();
while (methsIt.hasNext()) {
SootMethod sm = (SootMethod) methsIt.next();
// for now if its unreachable do nothing
if (!Scene.v().getReachableMethods().contains(sm)) {
continue;
}
analyzeMethod(sm);
}
}
Iterator<SootMethod> methStatIt = methodResultsMap.keySet().iterator();
while (methStatIt.hasNext()) {
SootMethod meth = methStatIt.next();
int result = methodResultsMap.get(meth).intValue();
String sRes = "Public";
if (result == RESULT_PUBLIC) {
sRes = "Public";
} else if (result == RESULT_PROTECTED) {
sRes = "Protected";
} else if (result == RESULT_PACKAGE) {
sRes = "Package";
} else if (result == RESULT_PRIVATE) {
sRes = "Private";
}
String actual = null;
if (Modifier.isPublic(meth.getModifiers())) {
actual = "Public";
} else if (Modifier.isProtected(meth.getModifiers())) {
actual = "Protected";
} else if (Modifier.isPrivate(meth.getModifiers())) {
actual = "Private";
} else {
actual = "Package";
}
// System.out.println("Method: "+meth.getName()+" has "+actual+" level access, can have: "+sRes+" level access.");
if (!sRes.equals(actual)) {
if (meth.getName().equals("<init>")) {
meth.addTag(new StringTag("Constructor: " + meth.getDeclaringClass().getName() + " has " + actual
+ " level access, can have: " + sRes + " level access.", "Tightest Qualifiers"));
} else {
meth.addTag(new StringTag(
"Method: " + meth.getName() + " has " + actual + " level access, can have: " + sRes + " level access.",
"Tightest Qualifiers"));
}
meth.addTag(new ColorTag(255, 10, 0, true, "Tightest Qualifiers"));
}
}
}
private void analyzeMethod(SootMethod sm) {
CallGraph cg = Scene.v().getCallGraph();
// Iterator eIt = Scene.v().getEntryPoints().iterator();
// while (eIt.hasNext()){
// System.out.println(eIt.next());
// }
if (methodToContexts == null) {
methodToContexts = new MethodToContexts(Scene.v().getReachableMethods().listener());
}
for (Iterator momcIt = methodToContexts.get(sm).iterator(); momcIt.hasNext();) {
final MethodOrMethodContext momc = (MethodOrMethodContext) momcIt.next();
Iterator callerEdges = cg.edgesInto(momc);
while (callerEdges.hasNext()) {
Edge callEdge = (Edge) callerEdges.next();
if (!callEdge.isExplicit()) {
continue;
}
SootMethod methodCaller = callEdge.src();
// System.out.println("Caller edge type: "+Edge.kindToString(callEdge.kind()));
SootClass callingClass = methodCaller.getDeclaringClass();
// public methods
if (Modifier.isPublic(sm.getModifiers())) {
analyzePublicMethod(sm, callingClass);
}
// protected methods
else if (Modifier.isProtected(sm.getModifiers())) {
analyzeProtectedMethod(sm, callingClass);
}
// private methods - do nothing
else if (Modifier.isPrivate(sm.getModifiers())) {
}
// package level methods
else {
analyzePackageMethod(sm, callingClass);
}
}
}
}
private boolean analyzeProtectedMethod(SootMethod sm, SootClass callingClass) {
SootClass methodClass = sm.getDeclaringClass();
// System.out.println("protected method: "+sm.getName()+" in class: "+methodClass.getName()+" calling class:
// "+callingClass.getName());
boolean insidePackageAccess = isCallSamePackage(callingClass, methodClass);
boolean subClassAccess = isCallClassSubClass(callingClass, methodClass);
boolean sameClassAccess = isCallClassMethodClass(callingClass, methodClass);
if (!insidePackageAccess && subClassAccess) {
methodResultsMap.put(sm, new Integer(RESULT_PROTECTED));
return true;
} else if (insidePackageAccess && !sameClassAccess) {
updateToPackage(sm);
return false;
} else {
updateToPrivate(sm);
return false;
}
}
private boolean analyzePackageMethod(SootMethod sm, SootClass callingClass) {
SootClass methodClass = sm.getDeclaringClass();
// System.out.println("package method: "+sm.getName()+" in class: "+methodClass.getName()+" calling class:
// "+callingClass.getName());
boolean insidePackageAccess = isCallSamePackage(callingClass, methodClass);
boolean subClassAccess = isCallClassSubClass(callingClass, methodClass);
boolean sameClassAccess = isCallClassMethodClass(callingClass, methodClass);
if (insidePackageAccess && !sameClassAccess) {
updateToPackage(sm);
return true;
} else {
updateToPrivate(sm);
return false;
}
}
private boolean analyzePublicMethod(SootMethod sm, SootClass callingClass) {
SootClass methodClass = sm.getDeclaringClass();
// System.out.println("public method: "+sm.getName()+" in class: "+methodClass.getName()+" calling class:
// "+callingClass.getName());
boolean insidePackageAccess = isCallSamePackage(callingClass, methodClass);
boolean subClassAccess = isCallClassSubClass(callingClass, methodClass);
boolean sameClassAccess = isCallClassMethodClass(callingClass, methodClass);
if (!insidePackageAccess && !subClassAccess) {
methodResultsMap.put(sm, new Integer(RESULT_PUBLIC));
return true;
} else if (!insidePackageAccess && subClassAccess) {
updateToProtected(sm);
return false;
} else if (insidePackageAccess && !sameClassAccess) {
updateToPackage(sm);
return false;
} else {
updateToPrivate(sm);
return false;
}
}
private void updateToProtected(SootMethod sm) {
if (!methodResultsMap.containsKey(sm)) {
methodResultsMap.put(sm, new Integer(RESULT_PROTECTED));
} else {
if (methodResultsMap.get(sm).intValue() != RESULT_PUBLIC) {
methodResultsMap.put(sm, new Integer(RESULT_PROTECTED));
}
}
}
private void updateToPackage(SootMethod sm) {
if (!methodResultsMap.containsKey(sm)) {
methodResultsMap.put(sm, new Integer(RESULT_PACKAGE));
} else {
if (methodResultsMap.get(sm).intValue() == RESULT_PRIVATE) {
methodResultsMap.put(sm, new Integer(RESULT_PACKAGE));
}
}
}
private void updateToPrivate(SootMethod sm) {
if (!methodResultsMap.containsKey(sm)) {
methodResultsMap.put(sm, new Integer(RESULT_PRIVATE));
}
}
private boolean isCallClassMethodClass(SootClass call, SootClass check) {
if (call.equals(check)) {
return true;
}
return false;
}
private boolean isCallClassSubClass(SootClass call, SootClass check) {
if (!call.hasSuperclass()) {
return false;
}
if (call.getSuperclass().equals(check)) {
return true;
}
return false;
}
private boolean isCallSamePackage(SootClass call, SootClass check) {
if (call.getPackageName().equals(check.getPackageName())) {
return true;
}
return false;
}
private void handleFields() {
Iterator classesIt = Scene.v().getApplicationClasses().iterator();
while (classesIt.hasNext()) {
SootClass appClass = (SootClass) classesIt.next();
Iterator fieldsIt = appClass.getFields().iterator();
while (fieldsIt.hasNext()) {
SootField sf = (SootField) fieldsIt.next();
analyzeField(sf);
}
}
Iterator<SootField> fieldStatIt = fieldResultsMap.keySet().iterator();
while (fieldStatIt.hasNext()) {
SootField f = fieldStatIt.next();
int result = fieldResultsMap.get(f).intValue();
String sRes = "Public";
if (result == RESULT_PUBLIC) {
sRes = "Public";
} else if (result == RESULT_PROTECTED) {
sRes = "Protected";
} else if (result == RESULT_PACKAGE) {
sRes = "Package";
} else if (result == RESULT_PRIVATE) {
sRes = "Private";
}
String actual = null;
if (Modifier.isPublic(f.getModifiers())) {
// System.out.println("Field: "+f.getName()+" is public");
actual = "Public";
} else if (Modifier.isProtected(f.getModifiers())) {
actual = "Protected";
} else if (Modifier.isPrivate(f.getModifiers())) {
actual = "Private";
} else {
actual = "Package";
}
// System.out.println("Field: "+f.getName()+" has "+actual+" level access, can have: "+sRes+" level access.");
if (!sRes.equals(actual)) {
f.addTag(
new StringTag("Field: " + f.getName() + " has " + actual + " level access, can have: " + sRes + " level access.",
"Tightest Qualifiers"));
f.addTag(new ColorTag(255, 10, 0, true, "Tightest Qualifiers"));
}
}
}
private void analyzeField(SootField sf) {
// from all bodies get all use boxes and eliminate used fields
Iterator classesIt = Scene.v().getApplicationClasses().iterator();
while (classesIt.hasNext()) {
SootClass appClass = (SootClass) classesIt.next();
Iterator mIt = appClass.getMethods().iterator();
while (mIt.hasNext()) {
SootMethod sm = (SootMethod) mIt.next();
if (!sm.hasActiveBody()) {
continue;
}
if (!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 (f.equals(sf)) {
if (Modifier.isPublic(sf.getModifiers())) {
if (analyzePublicField(sf, appClass)) {
return;
}
} else if (Modifier.isProtected(sf.getModifiers())) {
analyzeProtectedField(sf, appClass);
} else if (Modifier.isPrivate(sf.getModifiers())) {
} else {
analyzePackageField(sf, appClass);
}
}
}
}
}
}
}
private boolean analyzePublicField(SootField sf, SootClass callingClass) {
SootClass fieldClass = sf.getDeclaringClass();
boolean insidePackageAccess = isCallSamePackage(callingClass, fieldClass);
boolean subClassAccess = isCallClassSubClass(callingClass, fieldClass);
boolean sameClassAccess = isCallClassMethodClass(callingClass, fieldClass);
if (!insidePackageAccess && !subClassAccess) {
fieldResultsMap.put(sf, new Integer(RESULT_PUBLIC));
return true;
} else if (!insidePackageAccess && subClassAccess) {
updateToProtected(sf);
return false;
} else if (insidePackageAccess && !sameClassAccess) {
updateToPackage(sf);
return false;
} else {
updateToPrivate(sf);
return false;
}
}
private boolean analyzeProtectedField(SootField sf, SootClass callingClass) {
SootClass fieldClass = sf.getDeclaringClass();
boolean insidePackageAccess = isCallSamePackage(callingClass, fieldClass);
boolean subClassAccess = isCallClassSubClass(callingClass, fieldClass);
boolean sameClassAccess = isCallClassMethodClass(callingClass, fieldClass);
if (!insidePackageAccess && subClassAccess) {
fieldResultsMap.put(sf, new Integer(RESULT_PROTECTED));
return true;
} else if (insidePackageAccess && !sameClassAccess) {
updateToPackage(sf);
return false;
} else {
updateToPrivate(sf);
return false;
}
}
private boolean analyzePackageField(SootField sf, SootClass callingClass) {
SootClass fieldClass = sf.getDeclaringClass();
boolean insidePackageAccess = isCallSamePackage(callingClass, fieldClass);
boolean subClassAccess = isCallClassSubClass(callingClass, fieldClass);
boolean sameClassAccess = isCallClassMethodClass(callingClass, fieldClass);
if (insidePackageAccess && !sameClassAccess) {
updateToPackage(sf);
return true;
} else {
updateToPrivate(sf);
return false;
}
}
private void updateToProtected(SootField sf) {
if (!fieldResultsMap.containsKey(sf)) {
fieldResultsMap.put(sf, new Integer(RESULT_PROTECTED));
} else {
if (fieldResultsMap.get(sf).intValue() != RESULT_PUBLIC) {
fieldResultsMap.put(sf, new Integer(RESULT_PROTECTED));
}
}
}
private void updateToPackage(SootField sf) {
if (!fieldResultsMap.containsKey(sf)) {
fieldResultsMap.put(sf, new Integer(RESULT_PACKAGE));
} else {
if (fieldResultsMap.get(sf).intValue() == RESULT_PRIVATE) {
fieldResultsMap.put(sf, new Integer(RESULT_PACKAGE));
}
}
}
private void updateToPrivate(SootField sf) {
if (!fieldResultsMap.containsKey(sf)) {
fieldResultsMap.put(sf, new Integer(RESULT_PRIVATE));
}
}
}
| 15,710
| 32.42766
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/tags/ArrayCheckTag.java
|
package soot.jimple.toolkits.annotation.tags;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* Implementation of the Tag interface for array bounds checks.
*/
public class ArrayCheckTag implements OneByteCodeTag {
public static final String NAME = "ArrayCheckTag";
private final boolean lowerCheck;
private final boolean upperCheck;
/**
* A tag represents two bounds checks of an array reference. The value 'true' indicates check needed.
*/
public ArrayCheckTag(boolean lower, boolean upper) {
lowerCheck = lower;
upperCheck = upper;
}
/**
* Returns back the check information in binary form, which will be written into the class file.
*/
@Override
public byte[] getValue() {
byte b = 0;
if (lowerCheck) {
b |= 0x01;
}
if (upperCheck) {
b |= 0x02;
}
return new byte[] { b };
}
/**
* Needs upper bound check?
*/
public boolean isCheckUpper() {
return upperCheck;
}
/**
* Needs lower bound check?
*/
public boolean isCheckLower() {
return lowerCheck;
}
@Override
public String getName() {
return NAME;
}
@Override
public String toString() {
return (lowerCheck ? "[potentially unsafe lower bound]" : "[safe lower bound]") + ""
+ (upperCheck ? "[potentially unsafe upper bound]" : "[safe upper bound]");
}
}
| 2,102
| 24.337349
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/tags/ArrayNullCheckTag.java
|
package soot.jimple.toolkits.annotation.tags;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* ArrayNullCheckTag combines ArrayCheckTag and NullCheckTag into one tag. It uses bits of one byte value to represent the
* check information. The right-most two bits stand for the array bounds checks, and the right third bit represents the null
* check.
* <p>
*
* For array references, the right three bits are meaningful; for other object refrences, only null check bit should be used.
*
* @see ArrayCheckTag
* @see NullCheckTag
*/
public class ArrayNullCheckTag implements OneByteCodeTag {
public static final String NAME = "ArrayNullCheckTag";
private byte value;
public ArrayNullCheckTag() {
this.value = 0;
}
public ArrayNullCheckTag(byte v) {
this.value = v;
}
@Override
public String getName() {
return NAME;
}
@Override
public byte[] getValue() {
return new byte[] { value };
}
@Override
public String toString() {
return Byte.toString(value);
}
/** Accumulates another byte value by OR. */
public byte accumulate(byte other) {
byte oldv = value;
value |= other;
return oldv;
}
}
| 1,920
| 25.680556
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/tags/ArrayNullTagAggregator.java
|
package soot.jimple.toolkits.annotation.tags;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.LinkedList;
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.baf.Inst;
import soot.tagkit.Tag;
import soot.tagkit.TagAggregator;
/** The aggregator for ArrayNullCheckAttribute. */
public 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) {
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]);
}
public String aggregatedName() {
return "ArrayNullCheckAttribute";
}
}
| 1,979
| 27.695652
| 88
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/tags/NullCheckTag.java
|
package soot.jimple.toolkits.annotation.tags;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* NullCheckTag contains the null pointer check information. The right third bit of a byte is used to represent whether the
* null check is needed.
*/
public 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() {
return (value == 0) ? "[not null]" : "[unknown]";
}
}
| 1,573
| 24.387097
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/annotation/tags/OneByteCodeTag.java
|
package soot.jimple.toolkits.annotation.tags;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2000 Feng Qian
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.tagkit.Tag;
/**
* A tag which is guaranteed to contain no more than 1 byte of information.
*/
public interface OneByteCodeTag extends Tag {
}
| 998
| 30.21875
| 75
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/Aggregator.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Local;
import soot.PhaseOptions;
import soot.Singletons;
import soot.Timers;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.FieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.MonitorStmt;
import soot.jimple.Stmt;
import soot.jimple.StmtBody;
import soot.options.Options;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.toolkits.graph.PseudoTopologicalOrderer;
import soot.toolkits.scalar.LocalDefs;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
public class Aggregator extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(Aggregator.class);
public Aggregator(Singletons.Global g) {
}
public static Aggregator v() {
return G.v().soot_jimple_toolkits_base_Aggregator();
}
/**
* Traverse the statements in the given body, looking for aggregation possibilities; that is, given a def d and a use u, d
* has no other uses, u has no other defs, collapse d and u.
*
* option: only-stack-locals; if this is true, only aggregate variables starting with $
*/
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
StmtBody body = (StmtBody) b;
final boolean time = Options.v().time();
if (time) {
Timers.v().aggregationTimer.start();
}
Map<ValueBox, Zone> boxToZone = new HashMap<ValueBox, Zone>(body.getUnits().size() * 2 + 1, 0.7f);
// Determine the zone of every box
{
Zonation zonation = new Zonation(body);
for (Unit u : body.getUnits()) {
Zone zone = zonation.getZoneOf(u);
for (ValueBox box : u.getUseAndDefBoxes()) {
boxToZone.put(box, zone);
}
}
}
boolean onlyStackVars = PhaseOptions.getBoolean(options, "only-stack-locals");
int aggregateCount = Options.v().verbose() ? 1 : 0;
do {
if (aggregateCount != 0) {
logger.debug("[" + body.getMethod().getName() + "] Aggregating iteration " + aggregateCount + "...");
aggregateCount++;
}
} while (internalAggregate(body, boxToZone, onlyStackVars));
if (time) {
Timers.v().aggregationTimer.end();
}
}
private static boolean internalAggregate(StmtBody body, Map<ValueBox, Zone> boxToZone, boolean onlyStackVars) {
boolean hadAggregation = false;
final Chain<Unit> units = body.getUnits();
final ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body);
final LocalDefs localDefs = G.v().soot_toolkits_scalar_LocalDefsFactory().newLocalDefs(graph);
final LocalUses localUses = LocalUses.Factory.newLocalUses(body, localDefs);
NEXT_UNIT: for (Unit u : new PseudoTopologicalOrderer<Unit>().newList(graph, false)) {
if (!(u instanceof AssignStmt)) {
continue;
}
AssignStmt s = (AssignStmt) u;
Value lhs = s.getLeftOp();
if (!(lhs instanceof Local)) {
continue;
}
final Local lhsLocal = (Local) lhs;
if (onlyStackVars) {
if (!lhsLocal.isStackLocal()) {
continue;
}
}
Unit usepairUnit;
ValueBox usepairValueBox;
{
List<UnitValueBoxPair> lu = localUses.getUsesOf(s);
if (lu.size() != 1) {
continue;
}
UnitValueBoxPair usepair = lu.get(0);
usepairUnit = usepair.unit;
usepairValueBox = usepair.valueBox;
}
if (localDefs.getDefsOfAt(lhsLocal, usepairUnit).size() != 1) {
continue;
}
// Check to make sure aggregation pair in the same zone
if (boxToZone.get(s.getRightOpBox()) != boxToZone.get(usepairValueBox)) {
continue;
}
/*
* Need to check the path between def and use to see if there are any intervening re-defs of RHS in fact, we should
* check that this path is unique. If the RHS uses only locals, then we know what to do; if RHS has a method invocation
* f(a, b, c) or field access, we must ban field writes, other method calls and (as usual) writes to a, b, c.
*/
// look for a path from s to use in graph.
// only look in an extended basic block, though.
List<Unit> path = graph.getExtendedBasicBlockPathBetween(s, usepairUnit);
if (path == null) {
continue;
}
{
boolean propagatingInvokeExpr = false;
boolean propagatingFieldRef = false;
boolean propagatingArrayRef = false;
ArrayList<FieldRef> fieldRefList = new ArrayList<FieldRef>();// iteration
HashSet<Value> localsUsed = new HashSet<Value>();// fast contains check
for (ValueBox vb : s.getUseBoxes()) {
Value v = vb.getValue();
if (v instanceof Local) {
localsUsed.add(v);
} else if (v instanceof InvokeExpr) {
propagatingInvokeExpr = true;
} else if (v instanceof ArrayRef) {
propagatingArrayRef = true;
} else if (v instanceof FieldRef) {
propagatingFieldRef = true;
fieldRefList.add((FieldRef) v);
}
}
Iterator<Unit> pathIt = path.iterator();
assert (pathIt.hasNext());
pathIt.next(); // skip s.
while (pathIt.hasNext()) {
Stmt between = (Stmt) pathIt.next();
if (between != usepairUnit) {
// Make sure not propagating past a {enter,exit}Monitor
if (propagatingInvokeExpr && between instanceof MonitorStmt) {
continue NEXT_UNIT;// give up: can't aggregate.
}
// Check for killing definitions
for (ValueBox vb : between.getDefBoxes()) {
Value v = vb.getValue();
if (localsUsed.contains(v)) {
continue NEXT_UNIT;// give up: can't aggregate.
} else if (v instanceof FieldRef) {
if (propagatingInvokeExpr) {
continue NEXT_UNIT;// give up: can't aggregate.
} else if (propagatingFieldRef) {
// Can't aggregate a field access if passing a definition of
// a field with the same name, because they might be aliased.
for (FieldRef fieldRef : fieldRefList) {
if (isSameField((FieldRef) v, fieldRef)) {
continue NEXT_UNIT;// give up: can't aggregate.
}
}
}
} else if (v instanceof ArrayRef) {
if (propagatingInvokeExpr) {
// Cannot aggregate an invoke expr past an array write
continue NEXT_UNIT;// give up: can't aggregate.
} else if (propagatingArrayRef) {
// Cannot aggregate an array read past a write. This is
// conservative (if types differ they may not be aliased).
continue NEXT_UNIT;// give up: can't aggregate.
}
}
}
}
// Check for intervening side effects due to method calls
if (propagatingInvokeExpr || propagatingFieldRef || propagatingArrayRef) {
for (ValueBox box : between.getUseBoxes()) {
if (between == usepairUnit && box == usepairValueBox) {
// Reached use point, stop looking for side effects
break;
}
Value v = box.getValue();
if (v instanceof InvokeExpr || (propagatingInvokeExpr && (v instanceof FieldRef || v instanceof ArrayRef))) {
continue NEXT_UNIT;// give up: can't aggregate.
}
}
}
} // end while
}
// assuming that the d-u chains are correct, we need not check the actual contents of ld
Value aggregatee = s.getRightOp();
if (usepairValueBox.canContainValue(aggregatee)) {
boolean wasSimpleCopy = isSimpleCopy(usepairUnit);
usepairValueBox.setValue(aggregatee);
units.remove(s);
// clean up the tags. If s was not a simple copy, the new
// statement should get the tags of s.
// OK, this fix was wrong. The condition should not be
// "If s was not a simple copy", but rather "If usepairUnit
// was a simple copy". This way, when there's a load of a
// constant followed by an invoke, the invoke gets the tags.
if (wasSimpleCopy) {
// usepairUnit.removeAllTags();
usepairUnit.addAllTagsOf(s);
}
hadAggregation = true;
}
} // end for(...)
return hadAggregation;
}
/**
* Checks whether two field references point to the same field
*
* @param ref1
* The first field reference
* @param ref2
* The second reference
* @return True if the two references point to the same field, otherwise false
*/
private static boolean isSameField(FieldRef ref1, FieldRef ref2) {
return (ref1 == ref2) || ref1.getFieldRef().equals(ref2.getFieldRef());
}
private static boolean isSimpleCopy(Unit u) {
if (!(u instanceof DefinitionStmt)) {
return false;
}
DefinitionStmt defstmt = (DefinitionStmt) u;
return defstmt.getRightOp() instanceof Local && defstmt.getLeftOp() instanceof Local;
}
}
| 10,599
| 35.30137
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/ExceptionChecker.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import soot.ArrayType;
import soot.Body;
import soot.BodyTransformer;
import soot.FastHierarchy;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Trap;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.tagkit.SourceLnPosTag;
import soot.tagkit.ThrowCreatedByCompilerTag;
import soot.util.NumberedString;
public class ExceptionChecker extends BodyTransformer {
protected final ExceptionCheckerErrorReporter reporter;
protected FastHierarchy hierarchy;
public ExceptionChecker(ExceptionCheckerErrorReporter r) {
this.reporter = r;
}
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
for (Unit u : b.getUnits()) {
Stmt s = (Stmt) u;
if (s instanceof ThrowStmt) {
checkThrow(b, (ThrowStmt) s);
} else if (s instanceof InvokeStmt) {
checkInvoke(b, (InvokeStmt) s);
} else if (s instanceof AssignStmt) {
Value rightOp = ((AssignStmt) s).getRightOp();
if (rightOp instanceof InvokeExpr) {
checkInvokeExpr(b, (InvokeExpr) rightOp, s);
}
}
}
}
protected void checkThrow(Body b, ThrowStmt ts) {
RefType opType = (RefType) ts.getOp().getType();
if (isThrowDeclared(b, opType.getSootClass()) || isThrowFromCompiler(ts) || isExceptionCaught(b, ts, opType)) {
return;
}
if (reporter != null) {
reporter.reportError(new ExceptionCheckerError(b.getMethod(), opType.getSootClass(), ts,
(SourceLnPosTag) ts.getOpBox().getTag(SourceLnPosTag.NAME)));
}
}
// does the method declare the throw if its a throw that needs declaring
// RuntimeException and subclasses do not need to be declared
// Error and subclasses do not need to be declared
protected boolean isThrowDeclared(Body b, SootClass throwClass) {
if (hierarchy == null) {
hierarchy = new FastHierarchy();
}
final SootClass sootClassRuntimeException = Scene.v().getSootClass("java.lang.RuntimeException");
final SootClass sootClassError = Scene.v().getSootClass("java.lang.Error");
// handles case when exception is RuntimeException or Error
if (throwClass.equals(sootClassRuntimeException) || throwClass.equals(sootClassError)) {
return true;
}
// handles case when exception is a subclass of RuntimeException or Error
if (hierarchy.isSubclass(throwClass, sootClassRuntimeException) || hierarchy.isSubclass(throwClass, sootClassError)) {
return true;
}
// handles case when exact exception is thrown
if (b.getMethod().throwsException(throwClass)) {
return true;
}
// handles case when a super type of the exception is thrown
List<SootClass> exceptions = b.getMethod().getExceptionsUnsafe();
if (exceptions != null) {
for (SootClass nextEx : exceptions) {
if (hierarchy.isSubclass(throwClass, nextEx)) {
return true;
}
}
}
return false;
}
// is the throw created by the compiler
protected boolean isThrowFromCompiler(ThrowStmt ts) {
return ts.hasTag(ThrowCreatedByCompilerTag.NAME);
}
// is the throw caught inside the method
protected boolean isExceptionCaught(Body b, Stmt s, RefType throwType) {
if (hierarchy == null) {
hierarchy = new FastHierarchy();
}
for (Trap trap : b.getTraps()) {
RefType type = trap.getException().getType();
if (type.equals(throwType) || hierarchy.isSubclass(throwType.getSootClass(), type.getSootClass())) {
if (isThrowInStmtRange(b, (Stmt) trap.getBeginUnit(), (Stmt) trap.getEndUnit(), s)) {
return true;
}
}
}
return false;
}
protected boolean isThrowInStmtRange(Body b, Stmt begin, Stmt end, Stmt s) {
for (Iterator<Unit> it = b.getUnits().iterator(begin, end); it.hasNext();) {
Unit u = it.next();
if (u.equals(s)) {
return true;
}
}
return false;
}
protected void checkInvoke(Body b, InvokeStmt is) {
checkInvokeExpr(b, is.getInvokeExpr(), is);
}
// Given a method signature, see if it is declared in the given interface.
// If so, return the exceptions thrown by the declaration. Otherwise,
// Do the same thing recursively on superinterfaces and Object
// and return the intersection. This gives
// the maximal set of exceptions that could be declared to be thrown if the
// interface had declared the method. Returns null if no supertype declares
// the method.
private List<SootClass> getExceptionSpec(SootClass intrface, NumberedString sig) {
SootMethod sm = intrface.getMethodUnsafe(sig);
if (sm != null) {
return sm.getExceptions();
}
sm = Scene.v().getSootClass("java.lang.Object").getMethodUnsafe(sig);
if (sm != null && sm.getExceptionsUnsafe() == null) {
return Collections.emptyList();
}
List<SootClass> result = sm == null ? null : new ArrayList<SootClass>(sm.getExceptions());
for (SootClass suprintr : intrface.getInterfaces()) {
List<SootClass> other = getExceptionSpec(suprintr, sig);
if (other != null) {
if (result == null) {
result = other;
} else {
result.retainAll(other);
}
}
}
return result;
}
protected void checkInvokeExpr(Body b, InvokeExpr ie, Stmt s) {
final SootMethodRef methodRef = ie.getMethodRef();
if ("clone".equals(methodRef.name()) && methodRef.parameterTypes().isEmpty() && ie instanceof InstanceInvokeExpr
&& ((InstanceInvokeExpr) ie).getBase().getType() instanceof ArrayType) {
// the call is to the clone() method of an array type, which
// is defined not to throw any exceptions; if we left this to
// normal resolution we'd get the method in Object which does
// throw CloneNotSupportedException
return;
}
// For an invokeinterface, there is no unique resolution for the
// method reference that will get the "correct" exception spec. We
// actually need to look at the intersection of all declarations of
// the method in supertypes.
// Otherwise, we just do normal resolution.
List<SootClass> exceptions = (ie instanceof InterfaceInvokeExpr)
? getExceptionSpec(methodRef.declaringClass(), methodRef.getSubSignature()) : ie.getMethod().getExceptionsUnsafe();
if (exceptions != null) {
for (SootClass sc : exceptions) {
if (isThrowDeclared(b, sc) || isExceptionCaught(b, s, sc.getType())) {
continue;
}
if (reporter != null) {
if (s instanceof InvokeStmt) {
reporter.reportError(
new ExceptionCheckerError(b.getMethod(), sc, s, (SourceLnPosTag) s.getTag(SourceLnPosTag.NAME)));
} else if (s instanceof AssignStmt) {
reporter.reportError(new ExceptionCheckerError(b.getMethod(), sc, s,
(SourceLnPosTag) ((AssignStmt) s).getRightOpBox().getTag(SourceLnPosTag.NAME)));
}
}
}
}
}
}
| 8,234
| 34.804348
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/ExceptionCheckerError.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootClass;
import soot.SootMethod;
import soot.jimple.Stmt;
import soot.tagkit.SourceLnPosTag;
public class ExceptionCheckerError extends Exception {
private SootMethod method;
private SootClass excType;
private Stmt throwing;
private SourceLnPosTag position;
public ExceptionCheckerError(SootMethod m, SootClass sc, Stmt s, SourceLnPosTag pos) {
method(m);
excType(sc);
throwing(s);
position(pos);
}
public SootMethod method() {
return method;
}
public void method(SootMethod sm) {
method = sm;
}
public SootClass excType() {
return excType;
}
public void excType(SootClass sc) {
excType = sc;
}
public Stmt throwing() {
return throwing;
}
public void throwing(Stmt s) {
throwing = s;
}
public SourceLnPosTag position() {
return position;
}
public void position(SourceLnPosTag pos) {
position = pos;
}
}
| 1,756
| 22.118421
| 88
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/ExceptionCheckerErrorReporter.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public interface ExceptionCheckerErrorReporter {
public void reportError(ExceptionCheckerError e);
}
| 941
| 30.4
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/JimpleConstructorFolder.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2006 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.AssignStmt;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NewExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.options.Options;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
import soot.util.Chain;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
import soot.util.PhaseDumper;
/**
* This {@link BodyTransformer} pushes all {@link NewExpr} down the {@link Unit} {@link Chain} so that it is the statement
* directly before the invoke of the {@code <init>} function.
*/
public class JimpleConstructorFolder extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(JimpleConstructorFolder.class);
private static final boolean DEBUG_DUMP_BODIES = false;
public JimpleConstructorFolder() {
}
static Value rhs(Stmt s) {
return ((AssignStmt) s).getRightOp();
}
static Value lhs(Stmt s) {
return ((AssignStmt) s).getLeftOp();
}
static Local rhsLocal(Stmt s) {
return (Local) rhs(s);
}
static Local lhsLocal(Stmt s) {
return (Local) lhs(s);
}
static boolean isNew(Stmt s) {
return (s instanceof AssignStmt) && (rhs(s) instanceof NewExpr);
}
static boolean isConstructor(Stmt s) {
if (s instanceof InvokeStmt) {
InvokeExpr expr = ((InvokeStmt) s).getInvokeExpr();
if (expr instanceof SpecialInvokeExpr) {
SpecialInvokeExpr sie = (SpecialInvokeExpr) expr;
return SootMethod.constructorName.equals(sie.getMethodRef().getName());
}
}
return false;
}
static Local base(Stmt s) {
InvokeStmt is = (InvokeStmt) s;
InstanceInvokeExpr expr = (InstanceInvokeExpr) is.getInvokeExpr();
return (Local) expr.getBase();
}
static void setBase(Stmt s, Local l) {
InvokeStmt is = (InvokeStmt) s;
InstanceInvokeExpr expr = (InstanceInvokeExpr) is.getInvokeExpr();
expr.getBaseBox().setValue(l);
}
static boolean isCopy(Stmt s) {
return (s instanceof AssignStmt) && (rhs(s) instanceof Local) && (lhs(s) instanceof Local);
}
private static class Fact {
private Map<Local, Stmt> varToStmt = new HashMap<>();
private MultiMap<Stmt, Local> stmtToVar = new HashMultiMap<>();
private Stmt alloc = null;
public void add(Local l, Stmt s) {
varToStmt.put(l, s);
stmtToVar.put(s, l);
}
public Stmt get(Local l) {
return varToStmt.get(l);
}
public Set<Local> get(Stmt s) {
return stmtToVar.get(s);
}
public void removeAll(Stmt s) {
for (Local var : stmtToVar.get(s)) {
varToStmt.remove(var);
}
stmtToVar.remove(s);
}
public Stmt alloc() {
return alloc;
}
public void setAlloc(Stmt newAlloc) {
alloc = newAlloc;
}
public void copyFrom(Fact in) {
this.varToStmt = new HashMap<>(in.varToStmt);
this.stmtToVar = new HashMultiMap<>(in.stmtToVar);
this.alloc = in.alloc;
}
public void mergeFrom(Fact in1, Fact in2) {
this.varToStmt = new HashMap<>();
for (Map.Entry<Local, Stmt> e : in1.varToStmt.entrySet()) {
Local l = e.getKey();
Stmt newStmt = e.getValue();
if (in2.varToStmt.containsKey(l) && !newStmt.equals(in2.varToStmt.get(l))) {
throw new RuntimeException("Merge of different uninitialized values; are you sure this bytecode is verifiable?");
}
add(l, newStmt);
}
for (Map.Entry<Local, Stmt> e : in2.varToStmt.entrySet()) {
add(e.getKey(), e.getValue());
}
Stmt alloc1 = in1.alloc;
this.alloc = (alloc1 != null && alloc1.equals(in2.alloc)) ? alloc1 : null;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Fact)) {
return false;
}
Fact o = (Fact) other;
if (this.alloc == null && o.alloc != null) {
return false;
}
if (this.alloc != null && o.alloc == null) {
return false;
}
return (this.alloc == null || this.alloc.equals(o.alloc)) && this.stmtToVar.equals(o.stmtToVar);
}
@Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + Objects.hashCode(this.stmtToVar);
hash = 89 * hash + Objects.hashCode(this.alloc);
return hash;
}
}
private class Analysis extends ForwardFlowAnalysis<Unit, Fact> {
public Analysis(DirectedGraph<Unit> graph) {
super(graph);
doAnalysis();
}
@Override
protected Fact newInitialFlow() {
return new Fact();
}
@Override
public void flowThrough(Fact in, Unit u, Fact out) {
Stmt s = (Stmt) u;
copy(in, out);
out.setAlloc(null);
if (isNew(s)) {
out.add(lhsLocal(s), s);
} else if (isCopy(s)) {
Stmt newStmt = out.get(rhsLocal(s));
if (newStmt != null) {
out.add(lhsLocal(s), newStmt);
}
} else if (isConstructor(s)) {
Stmt newStmt = out.get(base(s));
if (newStmt != null) {
out.removeAll(newStmt);
out.setAlloc(newStmt);
}
}
}
@Override
public void copy(Fact source, Fact dest) {
dest.copyFrom(source);
}
@Override
public void merge(Fact in1, Fact in2, Fact out) {
out.mergeFrom(in1, in2);
}
}
@Override
public void internalTransform(Body b, String phaseName, Map<String, String> options) {
final JimpleBody body = (JimpleBody) b;
if (DEBUG_DUMP_BODIES) {
PhaseDumper.v().dumpBody(body, "constructorfolder.in");
}
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Folding Jimple constructors...");
}
Analysis analysis = new Analysis(new BriefUnitGraph(body));
final Chain<Unit> units = body.getUnits();
for (Unit u : units) {
Stmt s = (Stmt) u;
if (isCopy(s) || isConstructor(s)) {
continue;
}
Fact before = analysis.getFlowBefore(s);
for (ValueBox usebox : s.getUseBoxes()) {
Value value = usebox.getValue();
if (value instanceof Local && before.get((Local) value) != null) {
throw new RuntimeException(
"Use of an unitialized value before constructor call; are you sure this bytecode is verifiable?\n " + s);
}
}
}
// throw out all new statements
for (Iterator<Unit> it = units.snapshotIterator(); it.hasNext();) {
Stmt s = (Stmt) it.next();
if (isNew(s)) {
units.remove(s);
}
}
final Jimple jimp = Jimple.v();
for (Iterator<Unit> it = units.snapshotIterator(); it.hasNext();) {
Stmt s = (Stmt) it.next();
// throw out copies of uninitialized variables
if (isCopy(s)) {
final Fact before = analysis.getFlowBefore(s);
if (before.get(rhsLocal(s)) != null) {
units.remove(s);
}
} else if (analysis.getFlowAfter(s).alloc() != null) {
// insert the new just before the constructor
final Fact before = analysis.getFlowBefore(s);
final Local baseS = base(s);
final Stmt newStmt = before.get(baseS);
setBase(s, lhsLocal(newStmt));
units.insertBefore(newStmt, s);
// add necessary copies
for (Local l : before.get(newStmt)) {
if (!baseS.equals(l)) {
units.insertAfter(jimp.newAssignStmt(l, baseS), s);
}
}
}
}
if (DEBUG_DUMP_BODIES) {
PhaseDumper.v().dumpBody(body, "constructorfolder.out");
}
}
}
| 8,873
| 27.351438
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/PartialConstructorFolder.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.NewExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.options.Options;
import soot.tagkit.SourceLnPosTag;
import soot.toolkits.scalar.LocalUses;
import soot.toolkits.scalar.UnitValueBoxPair;
import soot.util.Chain;
public class PartialConstructorFolder extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(PartialConstructorFolder.class);
// public JimpleConstructorFolder( Singletons.Global g ) {}
// public static JimpleConstructorFolder v() { return G.v().JimpleConstructorFolder(); }
private List<Type> types;
public void setTypes(List<Type> t) {
this.types = t;
}
public List<Type> getTypes() {
return types;
}
/**
* This method pushes all newExpr down to be the stmt directly before every invoke of the init only if they are in the
* types list
*/
@Override
public void internalTransform(Body b, String phaseName, Map<String, String> options) {
JimpleBody body = (JimpleBody) b;
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Folding Jimple constructors...");
}
final Chain<Unit> units = body.getUnits();
List<Unit> stmtList = new ArrayList<Unit>(units);
LocalUses localUses = LocalUses.Factory.newLocalUses(body);
Iterator<Unit> nextStmtIt = stmtList.iterator();
nextStmtIt.next(); // start ahead one
/* fold in NewExpr's with specialinvoke's */
for (final Unit u : stmtList) {
if (u instanceof AssignStmt) {
final AssignStmt as = (AssignStmt) u;
/* this should be generalized to ArrayRefs */
// only deal with stmts that are an local = newExpr
final Value lhs = as.getLeftOp();
if (!(lhs instanceof Local)) {
continue;
}
final Value rhs = as.getRightOp();
if (!(rhs instanceof NewExpr)) {
continue;
}
// check if very next statement is invoke -->
// this indicates there is no control flow between
// new and invoke and should do nothing
if (nextStmtIt.hasNext()) {
Unit next = nextStmtIt.next();
if (next instanceof InvokeStmt) {
InvokeExpr ie = ((InvokeStmt) next).getInvokeExpr();
if (ie instanceof SpecialInvokeExpr) {
SpecialInvokeExpr invokeExpr = (SpecialInvokeExpr) ie;
if (invokeExpr.getBase() == lhs) {
break;
}
}
}
}
// check if new is in the types list - only process these
if (!types.contains(((NewExpr) rhs).getType())) {
continue;
}
boolean madeNewInvokeExpr = false;
for (UnitValueBoxPair uvb : localUses.getUsesOf(u)) {
Unit use = uvb.unit;
if (use instanceof InvokeStmt) {
InvokeExpr ie = ((InvokeStmt) use).getInvokeExpr();
if (!(ie instanceof SpecialInvokeExpr) || lhs != ((SpecialInvokeExpr) ie).getBase()) {
continue;
}
// make a new one here
AssignStmt constructStmt = Jimple.v().newAssignStmt(lhs, rhs);
constructStmt.setRightOp(Jimple.v().newNewExpr(((NewExpr) rhs).getBaseType()));
madeNewInvokeExpr = true;
// redirect jumps
use.redirectJumpsToThisTo(constructStmt);
// insert new one here
units.insertBefore(constructStmt, use);
constructStmt.addTag(u.getTag(SourceLnPosTag.NAME));
}
}
if (madeNewInvokeExpr) {
units.remove(u);
}
}
}
}
}
| 4,881
| 30.701299
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/RenameDuplicatedClasses.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.PhaseOptions;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.SootClass;
import soot.options.Options;
/**
* A scene transformer that renames the duplicated class names.
*
* The definition of duplicated class names. if (className1.equalsIgnoreCase(className2) { //className1 and className2 are
* duplicated class names. }
*
* Because some file systems are case-insensitive (e.g., Mac OS). When file a.b.c.class exists, a.b.C.class will over-write
* the content of a.b.c.class and case inconsistent that a.b.c.class file contains the content of a.b.C.class.
*
* However, in some case, at lest in Android applications, the duplicated class names exist. For example, an app (Sha256:
* 0015AE7C27688D45F79170DCEA16131CE557912A1A0C5F3B6B0465EE0774A452) in the Genome project contains duplicated class names.
* When transforming the app to classes, some classes are missing and consequently case problems for other analysis tools
* that relay on Soot (e.g., Error: class com.adwo.adsdk.s read in from a classfile in which com.adwo.adsdk.S was expected).
*/
public 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) {
// 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);
}
}
}
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;
}
}
| 5,045
| 34.787234
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/ThisInliner.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.SootMethod;
import soot.Trap;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.CaughtExceptionRef;
import soot.jimple.GotoStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.JimpleBody;
import soot.jimple.ParameterRef;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.ThisRef;
import soot.jimple.toolkits.scalar.LocalNameStandardizer;
import soot.shimple.ShimpleBody;
import soot.util.Chain;
public class ThisInliner extends BodyTransformer {
private static final boolean DEBUG = false;
@Override
public void internalTransform(Body b, String phaseName, Map<String, String> options) {
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());
}
}
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;
}
}
| 7,541
| 35.790244
| 115
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/Zonation.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import soot.Trap;
import soot.Unit;
import soot.jimple.StmtBody;
import soot.util.Chain;
public 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) {
Zone z = unitToZone.get(u);
if (z == null) {
throw new RuntimeException("null zone!");
} else {
return z;
}
}
public int getZoneCount() {
return zoneCount;
}
}
| 3,268
| 28.718182
| 95
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/base/Zone.java
|
package soot.jimple.toolkits.base;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 1999 Raja Vallee-Rai
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class Zone {
private final String name;
public Zone(String name) {
this.name = name;
}
@Override
public String toString() {
return "<zone: " + name + ">";
}
}
| 1,032
| 26.184211
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/AbstractCallSite.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.jimple.Stmt;
/**
* Abstract base class for call sites
*
* @author Steven Arzt
*/
public class AbstractCallSite {
protected Stmt stmt;
protected SootMethod container;
public AbstractCallSite(Stmt stmt, SootMethod container) {
this.stmt = stmt;
this.container = container;
}
public Stmt getStmt() {
return stmt;
}
public SootMethod getContainer() {
return container;
}
@Override
public String toString() {
return stmt == null ? "<null>" : stmt.toString();
}
}
| 1,386
| 23.767857
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/CHATransformer.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.G;
import soot.Scene;
import soot.SceneTransformer;
import soot.Singletons;
import soot.jimple.toolkits.pointer.DumbPointerAnalysis;
import soot.options.CHAOptions;
/**
* Builds an invoke graph using Class Hierarchy Analysis.
*/
public 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) {
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());
}
}
}
| 1,875
| 30.266667
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/CallGraph.java
|
package soot.jimple.toolkits.callgraph;
import java.util.Collection;
import java.util.HashSet;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import soot.Kind;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.Stmt;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/**
* Represents the edges in a call graph. This class is meant to act as only a container of edges; code for various call graph
* builders should be kept out of it, as well as most code for accessing the edges.
*
* @author Ondrej Lhotak
*/
public class CallGraph implements Iterable<Edge> {
protected Set<Edge> edges = new LinkedHashSet<Edge>();
protected ChunkedQueue<Edge> stream = new ChunkedQueue<Edge>();
protected QueueReader<Edge> reader = stream.reader();
protected Map<MethodOrMethodContext, Edge> srcMethodToEdge = new LinkedHashMap<MethodOrMethodContext, Edge>();
protected Map<Unit, Edge> srcUnitToEdge = new LinkedHashMap<Unit, Edge>();
protected Map<MethodOrMethodContext, Edge> tgtToEdge = new LinkedHashMap<MethodOrMethodContext, Edge>();
protected Edge dummy = new Edge(null, null, null, Kind.INVALID);
/**
* Used to add an edge to the call graph. Returns true iff the edge was not already present.
*/
public boolean addEdge(Edge e) {
if (!edges.add(e)) {
return false;
}
stream.add(e);
Edge position = srcUnitToEdge.get(e.srcUnit());
if (position == null) {
srcUnitToEdge.put(e.srcUnit(), e);
position = dummy;
}
e.insertAfterByUnit(position);
position = srcMethodToEdge.get(e.getSrc());
if (position == null) {
srcMethodToEdge.put(e.getSrc(), e);
position = dummy;
}
e.insertAfterBySrc(position);
position = tgtToEdge.get(e.getTgt());
if (position == null) {
tgtToEdge.put(e.getTgt(), e);
position = dummy;
}
e.insertAfterByTgt(position);
return true;
}
/**
* Removes all outgoing edges that start at the given unit
*
* @param u
* The unit from which to remove all outgoing edges
* @return True if at least one edge has been removed, otherwise false
*/
public boolean removeAllEdgesOutOf(Unit u) {
boolean hasRemoved = false;
Set<Edge> edgesToRemove = new HashSet<>();
for (QueueReader<Edge> edgeRdr = listener(); edgeRdr.hasNext();) {
Edge e = edgeRdr.next();
if (e.srcUnit() == u) {
e.remove();
removeEdge(e, false);
edgesToRemove.add(e);
hasRemoved = true;
}
}
if (hasRemoved) {
reader.remove(edgesToRemove);
}
return hasRemoved;
}
/**
* Swaps an invocation statement. All edges that previously went from the given statement to some callee now go from the
* new statement to the same callee. This method is intended to be used when a Jimple statement is replaced, but the
* replacement does not semantically affect the edges.
*
* @param out
* The old statement
* @param in
* The new statement
* @return True if at least one edge was affected by this operation
*/
public boolean swapEdgesOutOf(Stmt out, Stmt in) {
boolean hasSwapped = false;
for (Iterator<Edge> edgeRdr = edgesOutOf(out); edgeRdr.hasNext();) {
Edge e = edgeRdr.next();
MethodOrMethodContext src = e.getSrc();
MethodOrMethodContext tgt = e.getTgt();
removeEdge(e);
e.remove();
addEdge(new Edge(src, in, tgt));
hasSwapped = true;
}
return hasSwapped;
}
/**
* Removes the edge e from the call graph. Returns true iff the edge was originally present in the call graph.
*/
public boolean removeEdge(Edge e) {
return removeEdge(e, true);
}
/**
* Removes the edge e from the call graph. Returns true iff the edge was originally present in the call graph.
*
* @param e
* the edge
* @param removeInEdgeList
* when true (recommended), it is ensured that the edge reader is informed about the removal
* @return whether the removal was successful.
*/
public boolean removeEdge(Edge e, boolean removeInEdgeList) {
if (!edges.remove(e)) {
return false;
}
e.remove();
if (srcUnitToEdge.get(e.srcUnit()) == e) {
if (e.nextByUnit().srcUnit() == e.srcUnit()) {
srcUnitToEdge.put(e.srcUnit(), e.nextByUnit());
} else {
srcUnitToEdge.remove(e.srcUnit());
}
}
if (srcMethodToEdge.get(e.getSrc()) == e) {
if (e.nextBySrc().getSrc() == e.getSrc()) {
srcMethodToEdge.put(e.getSrc(), e.nextBySrc());
} else {
srcMethodToEdge.remove(e.getSrc());
}
}
if (tgtToEdge.get(e.getTgt()) == e) {
if (e.nextByTgt().getTgt() == e.getTgt()) {
tgtToEdge.put(e.getTgt(), e.nextByTgt());
} else {
tgtToEdge.remove(e.getTgt());
}
}
// This is an linear operation, so we want to avoid it if possible.
if (removeInEdgeList) {
reader.remove(e);
}
return true;
}
/**
* Removes the edges from the call graph. Returns true iff one edge was originally present in the call graph.
*
* @param edges
* the edges
* @return whether the removal was successful.
*/
public boolean removeEdges(Collection<Edge> edges) {
if (!edges.removeAll(edges)) {
return false;
}
for (Edge e : edges) {
removeEdge(e, false);
}
reader.remove(edges);
return true;
}
/**
* Does this method have no incoming edge?
*
* @param method
* @return
*/
public boolean isEntryMethod(SootMethod method) {
return !tgtToEdge.containsKey(method);
}
/**
* Find the specific call edge that is going out from the callsite u and the call target is callee. Without advanced data
* structure, we can only sequentially search for the match. Fortunately, the number of outgoing edges for a unit is not
* too large.
*
* @param u
* @param callee
* @return
*/
public Edge findEdge(Unit u, SootMethod callee) {
Edge e = srcUnitToEdge.get(u);
while (e.srcUnit() == u && e.kind() != Kind.INVALID) {
if (e.tgt() == callee) {
return e;
}
e = e.nextByUnit();
}
return null;
}
/**
* Returns an iterator over all methods that are the sources of at least one edge.
*/
public Iterator<MethodOrMethodContext> sourceMethods() {
return srcMethodToEdge.keySet().iterator();
}
/**
* Returns an iterator over all edges that have u as their source unit.
*/
public Iterator<Edge> edgesOutOf(Unit u) {
return new TargetsOfUnitIterator(u);
}
class TargetsOfUnitIterator implements Iterator<Edge> {
private final Unit u;
private Edge position;
TargetsOfUnitIterator(Unit u) {
this.u = u;
if (u == null) {
throw new RuntimeException();
}
this.position = srcUnitToEdge.get(u);
if (position == null) {
position = dummy;
}
}
@Override
public boolean hasNext() {
if (position.srcUnit() != u) {
return false;
}
return position.kind() != Kind.INVALID;
}
@Override
public Edge next() {
Edge ret = position;
position = position.nextByUnit();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Returns an iterator over all edges that have m as their source method.
*/
public Iterator<Edge> edgesOutOf(MethodOrMethodContext m) {
return new TargetsOfMethodIterator(m);
}
class TargetsOfMethodIterator implements Iterator<Edge> {
private final MethodOrMethodContext m;
private Edge position;
TargetsOfMethodIterator(MethodOrMethodContext m) {
this.m = m;
if (m == null) {
throw new RuntimeException();
}
this.position = srcMethodToEdge.get(m);
if (position == null) {
position = dummy;
}
}
@Override
public boolean hasNext() {
if (position.getSrc() != m) {
return false;
}
return position.kind() != Kind.INVALID;
}
@Override
public Edge next() {
Edge ret = position;
position = position.nextBySrc();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Returns an iterator over all edges that have m as their target method.
*/
public Iterator<Edge> edgesInto(MethodOrMethodContext m) {
return new CallersOfMethodIterator(m);
}
class CallersOfMethodIterator implements Iterator<Edge> {
private final MethodOrMethodContext m;
private Edge position;
CallersOfMethodIterator(MethodOrMethodContext m) {
this.m = m;
if (m == null) {
throw new RuntimeException();
}
this.position = tgtToEdge.get(m);
if (position == null) {
position = dummy;
}
}
@Override
public boolean hasNext() {
if (position.getTgt() != m) {
return false;
}
return position.kind() != Kind.INVALID;
}
@Override
public Edge next() {
Edge ret = position;
position = position.nextByTgt();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* 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.
*/
public QueueReader<Edge> listener() {
return reader.clone();
}
/**
* Returns a QueueReader object which will contain ONLY NEW edges which will be added to the graph.
*/
public QueueReader<Edge> newListener() {
return stream.reader();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
for (QueueReader<Edge> reader = listener(); reader.hasNext();) {
Edge e = reader.next();
out.append(e.toString()).append('\n');
}
return out.toString();
}
/**
* Returns the number of edges in the call graph.
*/
public int size() {
return edges.size();
}
@Override
public Iterator<Edge> iterator() {
return edges.iterator();
}
}
| 11,153
| 26.007264
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/CallGraphBuilder.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.EntryPoints;
import soot.Local;
import soot.MethodOrMethodContext;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.Scene;
import soot.Type;
import soot.Value;
import soot.jimple.IntConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.spark.pag.AllocNode;
import soot.jimple.spark.pag.ArrayElement;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.sets.P2SetVisitor;
import soot.jimple.spark.sets.PointsToSetInternal;
import soot.util.queue.QueueReader;
/**
* Models the call graph.
*
* @author Ondrej Lhotak
*/
public 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 (!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) {
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);
}
}
}
}
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);
}
}
}
}
}
| 7,069
| 33.154589
| 123
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/CallGraphPack.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.List;
import soot.EntryPoints;
import soot.PhaseOptions;
import soot.RadioScenePack;
import soot.Scene;
import soot.SootClass;
import soot.SootMethod;
import soot.options.CGOptions;
/**
* A radio pack implementation for the call graph pack that calls the intra-procedural clinit eliminator after the call graph
* has been built.
*/
public class CallGraphPack extends RadioScenePack {
public CallGraphPack(String name) {
super(name);
}
@Override
protected void internalApply() {
CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions(this));
if (!Scene.v().hasCustomEntryPoints()) {
if (!options.implicit_entry()) {
Scene.v().setEntryPoints(EntryPoints.v().application());
}
if (options.all_reachable()) {
List<SootMethod> entryPoints = new ArrayList<SootMethod>();
entryPoints.addAll(EntryPoints.v().all());
entryPoints.addAll(EntryPoints.v().methodsOfApplicationClasses());
Scene.v().setEntryPoints(entryPoints);
}
}
super.internalApply();
if (options.trim_clinit()) {
ClinitElimTransformer trimmer = new ClinitElimTransformer();
for (SootClass cl : Scene.v().getClasses(SootClass.BODIES)) {
for (SootMethod m : cl.getMethods()) {
if (m.isConcrete() && m.hasActiveBody()) {
trimmer.transform(m.getActiveBody());
}
}
}
}
}
}
| 2,298
| 29.653333
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ClinitElimAnalysis.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.toolkits.graph.UnitGraph;
import soot.toolkits.scalar.ArraySparseSet;
import soot.toolkits.scalar.FlowSet;
import soot.toolkits.scalar.ForwardFlowAnalysis;
public class ClinitElimAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<SootMethod>> {
private final CallGraph cg = Scene.v().getCallGraph();
private final UnitGraph g;
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 ArraySparseSet<SootMethod>();
}
@Override
protected FlowSet<SootMethod> newInitialFlow() {
ArraySparseSet<SootMethod> set = new ArraySparseSet<SootMethod>();
for (Iterator<Edge> mIt = cg.edgesOutOf(g.getBody().getMethod()); mIt.hasNext();) {
Edge edge = mIt.next();
if (edge.isClinit()) {
set.add(edge.tgt());
}
}
return set;
}
}
| 2,618
| 27.467391
| 96
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ClinitElimTransformer.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import java.util.Map;
import soot.Body;
import soot.BodyTransformer;
import soot.Scene;
import soot.jimple.Stmt;
import soot.toolkits.graph.BriefUnitGraph;
public class ClinitElimTransformer extends BodyTransformer {
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
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);
}
}
}
}
}
}
| 1,651
| 29.592593
| 91
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ConstantArrayAnalysis.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import soot.ArrayType;
import soot.Body;
import soot.Local;
import soot.NullType;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.ArrayRef;
import soot.jimple.DefinitionStmt;
import soot.jimple.IntConstant;
import soot.jimple.NewArrayExpr;
import soot.jimple.NullConstant;
import soot.jimple.Stmt;
import soot.shimple.PhiExpr;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.scalar.ForwardFlowAnalysis;
public class ConstantArrayAnalysis extends ForwardFlowAnalysis<Unit, ConstantArrayAnalysis.ArrayState> {
private class ArrayTypesInternal implements Cloneable {
BitSet mustAssign;
BitSet typeState[];
BitSet sizeState = new BitSet(szSize);
@Override
public Object clone() {
ArrayTypesInternal s;
try {
s = (ArrayTypesInternal) super.clone();
s.sizeState = (BitSet) s.sizeState.clone();
s.typeState = s.typeState.clone();
s.mustAssign = (BitSet) s.mustAssign.clone();
return s;
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ArrayTypesInternal)) {
return false;
}
ArrayTypesInternal otherTypes = (ArrayTypesInternal) obj;
return this.sizeState.equals(otherTypes.sizeState) && Arrays.equals(this.typeState, otherTypes.typeState)
&& this.mustAssign.equals(otherTypes.mustAssign);
}
@Override
public int hashCode() {
int hash = 5;
hash = 59 * hash + Objects.hashCode(this.mustAssign);
hash = 59 * hash + Arrays.deepHashCode(this.typeState);
hash = 59 * hash + Objects.hashCode(this.sizeState);
return hash;
}
}
public static class ArrayTypes {
public Set<Integer> possibleSizes;
public Set<Type>[] possibleTypes;
@Override
public String toString() {
return "ArrayTypes [possibleSizes=" + possibleSizes + ", possibleTypes=" + Arrays.toString(possibleTypes) + "]";
}
}
public class ArrayState {
ArrayTypesInternal[] state = new ArrayTypesInternal[size];
BitSet active = new BitSet(size);
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ArrayState)) {
return false;
}
ArrayState otherState = (ArrayState) obj;
return this.active.equals(otherState.active) && Arrays.equals(this.state, otherState.state);
}
@Override
public int hashCode() {
int hash = 3;
hash = 73 * hash + Arrays.deepHashCode(this.state);
hash = 73 * hash + Objects.hashCode(this.active);
return hash;
}
public void deepCloneLocalValueSlot(int localRef, int index) {
this.state[localRef] = (ArrayTypesInternal) this.state[localRef].clone();
this.state[localRef].typeState[index] = (BitSet) this.state[localRef].typeState[index].clone();
}
}
private final Map<Local, Integer> localToInt = new HashMap<Local, Integer>();
private final Map<Type, Integer> typeToInt = new HashMap<Type, Integer>();
private final Map<Integer, Integer> sizeToInt = new HashMap<Integer, Integer>();
private final Map<Integer, Type> rvTypeToInt = new HashMap<Integer, Type>();
private final Map<Integer, Integer> rvSizeToInt = new HashMap<Integer, Integer>();
private int size;
private int typeSize;
private int szSize;
public ConstantArrayAnalysis(DirectedGraph<Unit> graph, Body b) {
super(graph);
for (Local l : b.getLocals()) {
localToInt.put(l, size++);
}
for (Unit u : b.getUnits()) {
if (u instanceof DefinitionStmt) {
Value rhs = ((DefinitionStmt) u).getRightOp();
Type ty = rhs.getType();
if (!typeToInt.containsKey(ty)) {
int key = typeSize++;
typeToInt.put(ty, key);
rvTypeToInt.put(key, ty);
}
if (rhs instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) rhs;
if (nae.getSize() instanceof IntConstant) {
int sz = ((IntConstant) nae.getSize()).value;
if (!sizeToInt.containsKey(sz)) {
int key = szSize++;
sizeToInt.put(sz, key);
rvSizeToInt.put(key, sz);
}
}
}
}
}
doAnalysis();
}
@Override
protected void flowThrough(ArrayState in, Unit d, ArrayState out) {
out.active.clear();
out.active.or(in.active);
out.state = Arrays.copyOf(in.state, in.state.length);
if (d instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) d;
Value rhs = ds.getRightOp();
Value lhs = ds.getLeftOp();
if (rhs instanceof NewArrayExpr) {
Local l = (Local) lhs;
int varRef = localToInt.get(l);
out.active.set(varRef);
Value naeSize = ((NewArrayExpr) rhs).getSize();
if (naeSize instanceof IntConstant) {
int arraySize = ((IntConstant) naeSize).value;
out.state[varRef] = new ArrayTypesInternal();
out.state[varRef].sizeState.set(sizeToInt.get(arraySize));
out.state[varRef].typeState = new BitSet[arraySize];
out.state[varRef].mustAssign = new BitSet(arraySize);
for (int i = 0; i < arraySize; i++) {
out.state[varRef].typeState[i] = new BitSet(typeSize);
}
} else {
out.state[varRef] = null;
}
} else if (lhs instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) lhs;
int localRef = localToInt.get((Local) ar.getBase());
Value indexVal = ar.getIndex();
if (!(indexVal instanceof IntConstant)) {
out.state[localRef] = null;
out.active.set(localRef);
} else if (out.state[localRef] != null) {
int index = ((IntConstant) indexVal).value;
assert (index < out.state[localRef].typeState.length);
out.deepCloneLocalValueSlot(localRef, index);
assert (out.state[localRef].typeState[index] != null) : d;
out.state[localRef].typeState[index].set(typeToInt.get(rhs.getType()));
out.state[localRef].mustAssign.set(index);
}
} else if (lhs instanceof Local) {
if (rhs instanceof NullConstant && lhs.getType() instanceof ArrayType) {
int varRef = localToInt.get((Local) lhs);
out.active.clear(varRef);
out.state[varRef] = null;
} else if (rhs instanceof Local && in.state[localToInt.get((Local) rhs)] != null
&& in.active.get(localToInt.get((Local) rhs))) {
int lhsRef = localToInt.get((Local) lhs);
int rhsRef = localToInt.get((Local) rhs);
out.active.set(lhsRef);
out.state[lhsRef] = in.state[rhsRef];
out.state[rhsRef] = null;
} else if (rhs instanceof PhiExpr) {
PhiExpr rPhi = (PhiExpr) rhs;
int lhsRef = localToInt.get((Local) lhs);
out.state[lhsRef] = null;
int i = 0;
List<Value> phiValues = rPhi.getValues();
for (; i < phiValues.size(); i++) {
int argRef = localToInt.get((Local) phiValues.get(i));
if (!in.active.get(argRef)) {
continue;
}
out.active.set(lhsRef);
// one bottom -> all bottom
if (in.state[argRef] == null) {
out.state[lhsRef] = null;
break;
}
if (out.state[lhsRef] == null) {
out.state[lhsRef] = in.state[argRef];
} else {
out.state[lhsRef] = mergeTypeStates(in.state[argRef], out.state[lhsRef]);
}
out.state[argRef] = null;
}
for (; i < phiValues.size(); i++) {
int argRef = localToInt.get((Local) phiValues.get(i));
out.state[argRef] = null;
}
} else {
int varRef = localToInt.get((Local) lhs);
out.active.set(varRef);
out.state[varRef] = null;
}
}
for (ValueBox b : rhs.getUseBoxes()) {
Value v = b.getValue();
if (v instanceof Local) {
Integer localRef = localToInt.get((Local) v);
if (localRef != null) {
int iLocalRef = localRef;
out.state[iLocalRef] = null;
out.active.set(iLocalRef);
}
}
}
if (rhs instanceof Local) {
Integer localRef = localToInt.get((Local) rhs);
if (localRef != null) {
int iLocalRef = localRef;
out.state[iLocalRef] = null;
out.active.set(iLocalRef);
}
}
} else {
for (ValueBox b : d.getUseBoxes()) {
Value v = b.getValue();
if (v instanceof Local) {
Integer localRef = localToInt.get((Local) v);
if (localRef != null) {
int iLocalRef = localRef;
out.state[iLocalRef] = null;
out.active.set(iLocalRef);
}
}
}
}
}
@Override
protected ArrayState newInitialFlow() {
return new ArrayState();
}
@Override
protected void merge(ArrayState in1, ArrayState in2, ArrayState out) {
out.active.clear();
out.active.or(in1.active);
out.active.or(in2.active);
BitSet in2_excl = (BitSet) in2.active.clone();
in2_excl.andNot(in1.active);
for (int i = in1.active.nextSetBit(0); i >= 0; i = in1.active.nextSetBit(i + 1)) {
if (in1.state[i] == null) {
out.state[i] = null;
} else if (in2.active.get(i)) {
if (in2.state[i] == null) {
out.state[i] = null;
} else {
out.state[i] = mergeTypeStates(in1.state[i], in2.state[i]);
}
} else {
out.state[i] = in1.state[i];
}
}
for (int i = in2_excl.nextSetBit(0); i >= 0; i = in2_excl.nextSetBit(i + 1)) {
out.state[i] = in2.state[i];
}
}
private ArrayTypesInternal mergeTypeStates(ArrayTypesInternal a1, ArrayTypesInternal a2) {
assert (a1 != null && a2 != null);
ArrayTypesInternal toRet = new ArrayTypesInternal();
toRet.sizeState.or(a1.sizeState);
toRet.sizeState.or(a2.sizeState);
int maxSize = Math.max(a1.typeState.length, a2.typeState.length);
int commonSize = Math.min(a1.typeState.length, a2.typeState.length);
toRet.mustAssign = new BitSet(maxSize);
toRet.typeState = new BitSet[maxSize];
for (int i = 0; i < commonSize; i++) {
toRet.typeState[i] = new BitSet(typeSize);
toRet.typeState[i].or(a1.typeState[i]);
toRet.typeState[i].or(a2.typeState[i]);
toRet.mustAssign.set(i, a1.mustAssign.get(i) && a2.mustAssign.get(i));
}
for (int i = commonSize; i < maxSize; i++) {
if (a1.typeState.length > i) {
toRet.typeState[i] = (BitSet) a1.typeState[i].clone();
toRet.mustAssign.set(i, a1.mustAssign.get(i));
} else {
toRet.mustAssign.set(i, a2.mustAssign.get(i));
toRet.typeState[i] = (BitSet) a2.typeState[i].clone();
}
}
return toRet;
}
@Override
protected void copy(ArrayState source, ArrayState dest) {
dest.active = source.active;
dest.state = source.state;
}
public boolean isConstantBefore(Stmt s, Local arrayLocal) {
ArrayState flowResults = getFlowBefore(s);
int varRef = localToInt.get(arrayLocal);
return flowResults.active.get(varRef) && flowResults.state[varRef] != null;
}
@SuppressWarnings("unchecked")
public ArrayTypes getArrayTypesBefore(Stmt s, Local arrayLocal) {
if (!isConstantBefore(s, arrayLocal)) {
return null;
}
ArrayTypes toRet = new ArrayTypes();
int varRef = localToInt.get(arrayLocal);
ArrayTypesInternal ati = getFlowBefore(s).state[varRef];
toRet.possibleSizes = new HashSet<Integer>();
toRet.possibleTypes = new Set[ati.typeState.length];
for (int i = ati.sizeState.nextSetBit(0); i >= 0; i = ati.sizeState.nextSetBit(i + 1)) {
toRet.possibleSizes.add(rvSizeToInt.get(i));
}
for (int i = 0; i < toRet.possibleTypes.length; i++) {
toRet.possibleTypes[i] = new HashSet<Type>();
for (int j = ati.typeState[i].nextSetBit(0); j >= 0; j = ati.typeState[i].nextSetBit(j + 1)) {
toRet.possibleTypes[i].add(rvTypeToInt.get(j));
}
if (!ati.mustAssign.get(i)) {
toRet.possibleTypes[i].add(NullType.v());
}
}
return toRet;
}
}
| 13,400
| 33.717617
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ContextInsensitiveContextManager.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Kind;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
/**
* A context manager which adds no context-sensitivity to the call graph.
*
* @author Ondrej Lhotak
*/
public class ContextInsensitiveContextManager implements ContextManager {
private final CallGraph cg;
public ContextInsensitiveContextManager(CallGraph cg) {
this.cg = cg;
}
@Override
public void addStaticEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind) {
cg.addEdge(new Edge(src, srcUnit, target, kind));
}
@Override
public void addVirtualEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind, Context typeContext) {
cg.addEdge(new Edge(src.method(), srcUnit, target, kind));
}
@Override
public CallGraph callGraph() {
return cg;
}
}
| 1,695
| 27.745763
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ContextManager.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Kind;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
/**
* Interface for context managers, which decide how edges should be added to a context-sensitive call graph.
*
* @author Ondrej Lhotak
*/
public interface ContextManager {
public void addStaticEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind);
public void addVirtualEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind, Context typeContext);
public CallGraph callGraph();
}
| 1,394
| 31.44186
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ContextSensitiveCallGraph.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import soot.Context;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
/**
* Represents a context-sensitive call graph for querying by client analyses.
*
* @author Ondrej Lhotak
*/
public interface ContextSensitiveCallGraph {
/**
* Returns all MethodOrMethodContext's (context,method pairs) that are the source of some edge.
*/
public Iterator<MethodOrMethodContext> edgeSources();
/**
* Returns all ContextSensitiveEdge's in the call graph.
*/
public Iterator<ContextSensitiveEdge> allEdges();
/**
* Returns all ContextSensitiveEdge's out of unit srcUnit in method src in context srcCtxt.
*/
public Iterator<ContextSensitiveEdge> edgesOutOf(Context srcCtxt, SootMethod src, Unit srcUnit);
/**
* Returns all ContextSensitiveEdge's out of method src in context srcCtxt.
*/
public Iterator<ContextSensitiveEdge> edgesOutOf(Context srcCtxt, SootMethod src);
/**
* Returns all ContextSensitiveEdge's into method tgt in context tgtCtxt.
*/
public Iterator<ContextSensitiveEdge> edgesInto(Context tgtCtxt, SootMethod tgt);
}
| 1,973
| 30.333333
| 98
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ContextSensitiveEdge.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2005 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Kind;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.Stmt;
/**
* Represents a single context-sensitive edge in a call graph.
*
* @author Ondrej Lhotak
*/
public interface ContextSensitiveEdge {
/**
* The context at the source of the call.
*/
public Context srcCtxt();
/**
* The method in which the call occurs; may be null for calls not occurring in a specific method (eg. implicit calls by the
* VM)
*/
public SootMethod src();
/**
* The unit at which the call occurs; may be null for calls not occurring at a specific statement (eg. calls in native
* code)
*/
public Unit srcUnit();
public Stmt srcStmt();
/**
* The context at the target of the call.
*/
public Context tgtCtxt();
/**
* The target method of the call edge.
*/
public SootMethod tgt();
/**
* The kind of edge. Note: kind should not be tested by other classes; instead, accessors such as isExplicit() should be
* added.
*/
public Kind kind();
}
| 1,879
| 24.753425
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/Edge.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Kind;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.InterfaceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.VirtualInvokeExpr;
import soot.util.Invalidable;
/**
* Represents a single edge in a call graph.
*
* @author Ondrej Lhotak
*/
public final class Edge implements Invalidable {
/**
* The method in which the call occurs; may be null for calls not occurring in a specific method (eg. implicit calls by the
* VM)
*/
private MethodOrMethodContext src;
/**
* The target method of the call edge.
*/
private MethodOrMethodContext tgt;
/**
* The unit at which the call occurs; may be null for calls not occurring at a specific statement (eg. calls in native
* code)
*/
private Unit srcUnit;
/**
* The kind of edge. Note: kind should not be tested by other classes; instead, accessors such as isExplicit() should be
* added.
*/
private final Kind kind;
private boolean invalid = false;
public Edge(MethodOrMethodContext src, Unit srcUnit, MethodOrMethodContext tgt, Kind kind) {
this.src = src;
this.srcUnit = srcUnit;
this.tgt = tgt;
this.kind = kind;
}
public Edge(MethodOrMethodContext src, Stmt srcUnit, MethodOrMethodContext tgt) {
this.kind = ieToKind(srcUnit.getInvokeExpr());
this.src = src;
this.srcUnit = srcUnit;
this.tgt = tgt;
}
public SootMethod src() {
return (src == null) ? null : src.method();
}
public Context srcCtxt() {
return (src == null) ? null : src.context();
}
public MethodOrMethodContext getSrc() {
return src;
}
public Unit srcUnit() {
return srcUnit;
}
public Stmt srcStmt() {
return (Stmt) srcUnit;
}
public SootMethod tgt() {
return (tgt == null) ? null : tgt.method();
}
public Context tgtCtxt() {
return (tgt == null) ? null : tgt.context();
}
public MethodOrMethodContext getTgt() {
return tgt;
}
public Kind kind() {
return kind;
}
public static Kind ieToKind(InvokeExpr ie) {
if (ie instanceof VirtualInvokeExpr) {
return Kind.VIRTUAL;
} else if (ie instanceof SpecialInvokeExpr) {
return Kind.SPECIAL;
} else if (ie instanceof InterfaceInvokeExpr) {
return Kind.INTERFACE;
} else if (ie instanceof StaticInvokeExpr) {
return Kind.STATIC;
} else {
throw new RuntimeException();
}
}
/**
* Returns true if the call is due to an explicit invoke statement.
*/
public boolean isExplicit() {
return Kind.isExplicit(this.kind);
}
/**
* Returns true if the call is due to an explicit instance invoke statement.
*/
public boolean isInstance() {
return Kind.isInstance(this.kind);
}
public boolean isVirtual() {
return Kind.isVirtual(this.kind);
}
public boolean isSpecial() {
return Kind.isSpecial(this.kind);
}
/**
* Returns true if the call is to static initializer.
*/
public boolean isClinit() {
return Kind.isClinit(this.kind);
}
/**
* Returns true if the call is due to an explicit static invoke statement.
*/
public boolean isStatic() {
return Kind.isStatic(this.kind);
}
public boolean isThreadRunCall() {
return Kind.isThread(this.kind);
}
public boolean passesParameters() {
return Kind.passesParameters(this.kind);
}
@Override
public boolean isInvalid() {
return invalid;
}
@Override
public void invalidate() {
// Since the edge remains in the QueueReaders for a while, the GC could not claim old units.
src = null;
srcUnit = null;
tgt = null;
invalid = true;
}
@Override
public int hashCode() {
if (invalid) {
return 0;
}
int ret = (tgt.hashCode() + 20) + (kind == null ? 0 : kind.getNumber());
if (src != null) {
ret = ret * 32 + src.hashCode();
}
if (srcUnit != null) {
ret = ret * 32 + srcUnit.hashCode();
}
return ret;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Edge)) {
return false;
}
Edge o = (Edge) other;
return (o.src == this.src) && (o.srcUnit == srcUnit) && (o.tgt == tgt) && (o.kind == kind);
}
@Override
public String toString() {
return String.valueOf(this.kind) + " edge: " + srcUnit + " in " + src + " ==> " + tgt;
}
private Edge nextByUnit = this;
private Edge prevByUnit = this;
private Edge nextBySrc = this;
private Edge prevBySrc = this;
private Edge nextByTgt = this;
private Edge prevByTgt = this;
void insertAfterByUnit(Edge other) {
nextByUnit = other.nextByUnit;
nextByUnit.prevByUnit = this;
other.nextByUnit = this;
prevByUnit = other;
}
void insertAfterBySrc(Edge other) {
nextBySrc = other.nextBySrc;
nextBySrc.prevBySrc = this;
other.nextBySrc = this;
prevBySrc = other;
}
void insertAfterByTgt(Edge other) {
nextByTgt = other.nextByTgt;
nextByTgt.prevByTgt = this;
other.nextByTgt = this;
prevByTgt = other;
}
void insertBeforeByUnit(Edge other) {
prevByUnit = other.prevByUnit;
prevByUnit.nextByUnit = this;
other.prevByUnit = this;
nextByUnit = other;
}
void insertBeforeBySrc(Edge other) {
prevBySrc = other.prevBySrc;
prevBySrc.nextBySrc = this;
other.prevBySrc = this;
nextBySrc = other;
}
void insertBeforeByTgt(Edge other) {
prevByTgt = other.prevByTgt;
prevByTgt.nextByTgt = this;
other.prevByTgt = this;
nextByTgt = other;
}
void remove() {
invalid = true;
nextByUnit.prevByUnit = prevByUnit;
prevByUnit.nextByUnit = nextByUnit;
nextBySrc.prevBySrc = prevBySrc;
prevBySrc.nextBySrc = nextBySrc;
nextByTgt.prevByTgt = prevByTgt;
prevByTgt.nextByTgt = nextByTgt;
}
Edge nextByUnit() {
return nextByUnit;
}
Edge nextBySrc() {
return nextBySrc;
}
Edge nextByTgt() {
return nextByTgt;
}
Edge prevByUnit() {
return prevByUnit;
}
Edge prevBySrc() {
return prevBySrc;
}
Edge prevByTgt() {
return prevByTgt;
}
}
| 7,058
| 22.220395
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/EdgePredicate.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* An interface for predicates on edges, used to specify which edges should or shouldn't be included as part of a particular
* subgraph.
*
* @author Ondrej Lhotak
*/
public interface EdgePredicate {
/**
* Returns true iff the edge e is wanted.
*/
public boolean want(Edge e);
}
| 1,136
| 28.921053
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ExplicitEdgesPred.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A predicate that accepts edges that are the result of an explicit invoke.
*
* @author Ondrej Lhotak
*/
public class ExplicitEdgesPred implements EdgePredicate {
/**
* Returns true iff the edge e is wanted.
*/
@Override
public boolean want(Edge e) {
return e.isExplicit();
}
}
| 1,144
| 27.625
| 76
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/Filter.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
/**
* Represents a subset of the edges in a call graph satisfying an EdgePredicate predicate.
*
* @author Ondrej Lhotak
*/
public 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() {
while (source.hasNext()) {
next = source.next();
if (pred.want(next)) {
return;
}
}
next = null;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Edge next() {
Edge ret = next;
advance();
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 1,744
| 22.266667
| 90
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/InstanceInvokeEdgesPred.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/**
* A predicate that accepts edges that are the result of an explicit instance invoke.
*
* @author Ondrej Lhotak
*/
public class InstanceInvokeEdgesPred implements EdgePredicate {
/**
* Returns true iff the edge e is wanted.
*/
@Override
public boolean want(Edge e) {
return e.isInstance();
}
}
| 1,160
| 28.025
| 85
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/InvokeCallSite.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Local;
import soot.SootMethod;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.toolkits.callgraph.ConstantArrayAnalysis.ArrayTypes;
public class InvokeCallSite extends AbstractCallSite {
public static final int MUST_BE_NULL = 0;
public static final int MUST_NOT_BE_NULL = 1;
public static final int MAY_BE_NULL = -1;
private final InstanceInvokeExpr iie;
private final Local argArray;
private final Local base;
private final int nullnessCode;
private final ArrayTypes reachingTypes;
public InvokeCallSite(Stmt stmt, SootMethod container, InstanceInvokeExpr iie, Local base) {
this(stmt, container, iie, base, (Local) null, 0);
}
public InvokeCallSite(Stmt stmt, SootMethod container, InstanceInvokeExpr iie, Local base, Local argArray,
int nullnessCode) {
super(stmt, container);
this.iie = iie;
this.base = base;
this.argArray = argArray;
this.nullnessCode = nullnessCode;
this.reachingTypes = null;
}
public InvokeCallSite(Stmt stmt, SootMethod container, InstanceInvokeExpr iie, Local base, ArrayTypes reachingArgTypes,
int nullnessCode) {
super(stmt, container);
this.iie = iie;
this.base = base;
this.argArray = null;
this.nullnessCode = nullnessCode;
this.reachingTypes = reachingArgTypes;
}
/**
* @deprecated use {@link #getStmt()}
*/
@Deprecated
public Stmt stmt() {
return stmt;
}
/**
* @deprecated use {@link #getContainer()}
*/
@Deprecated
public SootMethod container() {
return container;
}
public InstanceInvokeExpr iie() {
return iie;
}
public Local base() {
return base;
}
public Local argArray() {
return argArray;
}
public int nullnessCode() {
return nullnessCode;
}
public ArrayTypes reachingTypes() {
return reachingTypes;
}
@Override
public String toString() {
return stmt.toString();
}
}
| 2,806
| 25.233645
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ObjSensContextManager.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Kind;
import soot.MethodContext;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
/**
* A context manager which creates an object-sensitive call graph.
*
* @author Ondrej Lhotak
*/
public class ObjSensContextManager implements ContextManager {
private final CallGraph cg;
public ObjSensContextManager(CallGraph cg) {
this.cg = cg;
}
@Override
public void addStaticEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind) {
cg.addEdge(new Edge(src, srcUnit, target, kind));
}
@Override
public void addVirtualEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind, Context typeContext) {
cg.addEdge(new Edge(src, srcUnit, MethodContext.v(target, typeContext), kind));
}
@Override
public CallGraph callGraph() {
return cg;
}
}
| 1,713
| 28.050847
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/OnFlyCallGraphBuilder.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.AnySubType;
import soot.ArrayType;
import soot.Body;
import soot.BooleanType;
import soot.ByteType;
import soot.CharType;
import soot.Context;
import soot.DoubleType;
import soot.EntryPoints;
import soot.FastHierarchy;
import soot.FloatType;
import soot.IntType;
import soot.Kind;
import soot.Local;
import soot.LocalGenerator;
import soot.LongType;
import soot.MethodContext;
import soot.MethodOrMethodContext;
import soot.MethodSubSignature;
import soot.NullType;
import soot.PackManager;
import soot.PhaseOptions;
import soot.PrimType;
import soot.RefLikeType;
import soot.RefType;
import soot.Scene;
import soot.SceneTransformer;
import soot.ShortType;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Transform;
import soot.Type;
import soot.Unit;
import soot.UnitPatchingChain;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.DynamicInvokeExpr;
import soot.jimple.FieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.NullConstant;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.VirtualInvokeExpr;
import soot.jimple.spark.pag.AllocDotField;
import soot.jimple.spark.pag.PAG;
import soot.jimple.toolkits.annotation.nullcheck.NullnessAnalysis;
import soot.jimple.toolkits.callgraph.ConstantArrayAnalysis.ArrayTypes;
import soot.jimple.toolkits.callgraph.VirtualEdgesSummaries.DirectTarget;
import soot.jimple.toolkits.callgraph.VirtualEdgesSummaries.IndirectTarget;
import soot.jimple.toolkits.callgraph.VirtualEdgesSummaries.VirtualEdge;
import soot.jimple.toolkits.callgraph.VirtualEdgesSummaries.VirtualEdgeTarget;
import soot.jimple.toolkits.reflection.ReflectionTraceInfo;
import soot.options.CGOptions;
import soot.options.Options;
import soot.options.SparkOptions;
import soot.toolkits.graph.ExceptionalUnitGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
import soot.util.HashMultiMap;
import soot.util.IterableNumberer;
import soot.util.LargeNumberedMap;
import soot.util.MultiMap;
import soot.util.NumberedString;
import soot.util.SmallNumberedMap;
import soot.util.StringNumberer;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/**
* Models the call graph.
*
* @author Ondrej Lhotak
*/
public class OnFlyCallGraphBuilder {
private static final Logger logger = LoggerFactory.getLogger(OnFlyCallGraphBuilder.class);
// NOTE: this field must be static to avoid adding the transformation again if the call graph is rebuilt.
static boolean registeredGuardsTransformation = false;
private static final PrimType[] CHAR_NARROWINGS;
private static final PrimType[] INT_NARROWINGS;
private static final PrimType[] SHORT_NARROWINGS;
private static final PrimType[] LONG_NARROWINGS;
private static final ByteType[] BYTE_NARROWINGS;
private static final PrimType[] FLOAT_NARROWINGS;
private static final PrimType[] BOOLEAN_NARROWINGS;
private static final PrimType[] DOUBLE_NARROWINGS;
static {
final CharType cT = CharType.v();
final IntType iT = IntType.v();
final ShortType sT = ShortType.v();
final ByteType bT = ByteType.v();
final LongType lT = LongType.v();
final FloatType fT = FloatType.v();
CHAR_NARROWINGS = new PrimType[] { cT };
INT_NARROWINGS = new PrimType[] { iT, cT, sT, bT, sT };
SHORT_NARROWINGS = new PrimType[] { sT, bT };
LONG_NARROWINGS = new PrimType[] { lT, iT, cT, sT, bT, sT };
BYTE_NARROWINGS = new ByteType[] { bT };
FLOAT_NARROWINGS = new PrimType[] { fT, lT, iT, cT, sT, bT, sT };
BOOLEAN_NARROWINGS = new PrimType[] { BooleanType.v() };
DOUBLE_NARROWINGS = new PrimType[] { DoubleType.v(), fT, lT, iT, cT, sT, bT, sT };
}
protected final NumberedString sigFinalize;
protected final NumberedString sigInit;
protected final NumberedString sigForName;
protected final RefType clRunnable = RefType.v("java.lang.Runnable");
protected final RefType clAsyncTask = RefType.v("android.os.AsyncTask");
protected final RefType clHandler = RefType.v("android.os.Handler");
/** context-insensitive stuff */
private final CallGraph cicg = Scene.v().internalMakeCallGraph();
// end type based reflection resolution
protected final LargeNumberedMap<Local, List<VirtualCallSite>> receiverToSites;
protected final LargeNumberedMap<SootMethod, List<Local>> methodToReceivers;
protected final LargeNumberedMap<SootMethod, List<Local>> methodToInvokeBases;
protected final LargeNumberedMap<SootMethod, List<Local>> methodToInvokeArgs;
protected final LargeNumberedMap<SootMethod, List<Local>> methodToStringConstants;
protected final SmallNumberedMap<Local, List<VirtualCallSite>> stringConstToSites;
protected final HashSet<SootMethod> analyzedMethods = new HashSet<SootMethod>();
protected final MultiMap<Local, InvokeCallSite> baseToInvokeSite = new HashMultiMap<>();
protected final MultiMap<Local, InvokeCallSite> invokeArgsToInvokeSite = new HashMultiMap<>();
protected final Map<Local, BitSet> invokeArgsToSize = new IdentityHashMap<>();
protected final MultiMap<AllocDotField, Local> allocDotFieldToLocal = new HashMultiMap<>();
protected final MultiMap<Local, Type> reachingArgTypes = new HashMultiMap<>();
protected final MultiMap<Local, Type> reachingBaseTypes = new HashMultiMap<>();
protected final ChunkedQueue<SootMethod> targetsQueue = new ChunkedQueue<SootMethod>();
protected final QueueReader<SootMethod> targets = targetsQueue.reader();
protected final ReflectionModel reflectionModel;
protected final CGOptions options;
protected boolean appOnly;
/** context-sensitive stuff */
protected final ReachableMethods rm;
protected final QueueReader<MethodOrMethodContext> worklist;
protected final ContextManager cm;
protected final VirtualEdgesSummaries virtualEdgeSummaries = initializeEdgeSummaries();
protected NullnessAnalysis nullnessCache = null;
protected ConstantArrayAnalysis arrayCache = null;
protected SootMethod analysisKey = null;
public OnFlyCallGraphBuilder(ContextManager cm, ReachableMethods rm, boolean appOnly) {
final Scene sc = Scene.v();
{
final StringNumberer nmbr = sc.getSubSigNumberer();
this.sigFinalize = nmbr.findOrAdd("void finalize()");
this.sigInit = nmbr.findOrAdd("void <init>()");
this.sigForName = nmbr.findOrAdd("java.lang.Class forName(java.lang.String)");
}
{
this.receiverToSites = new LargeNumberedMap<Local, List<VirtualCallSite>>(sc.getLocalNumberer());
final IterableNumberer<SootMethod> methodNumberer = sc.getMethodNumberer();
this.methodToReceivers = new LargeNumberedMap<SootMethod, List<Local>>(methodNumberer);
this.methodToInvokeBases = new LargeNumberedMap<SootMethod, List<Local>>(methodNumberer);
this.methodToInvokeArgs = new LargeNumberedMap<SootMethod, List<Local>>(methodNumberer);
this.methodToStringConstants = new LargeNumberedMap<SootMethod, List<Local>>(methodNumberer);
this.stringConstToSites = new SmallNumberedMap<Local, List<VirtualCallSite>>();
}
this.cm = cm;
this.rm = rm;
this.worklist = rm.listener();
this.options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
if (!options.verbose()) {
logger.debug("[Call Graph] For information on where the call graph may be incomplete,"
+ " use the verbose option to the cg phase.");
}
if (options.reflection_log() == null || options.reflection_log().length() == 0) {
if (options.types_for_invoke() && new SparkOptions(PhaseOptions.v().getPhaseOptions("cg.spark")).enabled()) {
this.reflectionModel = new TypeBasedReflectionModel();
} else {
this.reflectionModel = new DefaultReflectionModel();
}
} else {
this.reflectionModel = new TraceBasedReflectionModel();
}
this.appOnly = appOnly;
}
public OnFlyCallGraphBuilder(ContextManager cm, ReachableMethods rm) {
this(cm, rm, false);
}
/**
* Initializes the edge summaries that model callbacks in library classes. Custom implementations may override this method
* to supply a specialized summary provider.
*
* @return A provider object for virtual edge summaries
*/
protected VirtualEdgesSummaries initializeEdgeSummaries() {
return new VirtualEdgesSummaries();
}
public ContextManager getContextManager() {
return cm;
}
public LargeNumberedMap<SootMethod, List<Local>> methodToReceivers() {
return methodToReceivers;
}
public LargeNumberedMap<SootMethod, List<Local>> methodToInvokeArgs() {
return methodToInvokeArgs;
}
public LargeNumberedMap<SootMethod, List<Local>> methodToInvokeBases() {
return methodToInvokeBases;
}
public LargeNumberedMap<SootMethod, List<Local>> methodToStringConstants() {
return methodToStringConstants;
}
public void processReachables() {
while (true) {
if (!worklist.hasNext()) {
rm.update();
if (!worklist.hasNext()) {
break;
}
}
MethodOrMethodContext momc = worklist.next();
SootMethod m = momc.method();
if (appOnly && !m.getDeclaringClass().isApplicationClass()) {
continue;
}
if (analyzedMethods.add(m)) {
processNewMethod(m);
}
processNewMethodContext(momc);
}
}
public boolean wantTypes(Local receiver) {
return receiverToSites.get(receiver) != null || baseToInvokeSite.get(receiver) != null;
}
public void addBaseType(Local base, Context context, Type ty) {
assert (context == null);
final Set<InvokeCallSite> invokeSites = baseToInvokeSite.get(base);
if (invokeSites != null) {
if (reachingBaseTypes.put(base, ty) && !invokeSites.isEmpty()) {
resolveInvoke(invokeSites);
}
}
}
public void addInvokeArgType(Local argArray, Context context, Type t) {
assert (context == null);
final Set<InvokeCallSite> invokeSites = invokeArgsToInvokeSite.get(argArray);
if (invokeSites != null) {
if (reachingArgTypes.put(argArray, t)) {
resolveInvoke(invokeSites);
}
}
}
public void setArgArrayNonDetSize(Local argArray, Context context) {
assert (context == null);
final Set<InvokeCallSite> invokeSites = invokeArgsToInvokeSite.get(argArray);
if (invokeSites != null) {
if (!invokeArgsToSize.containsKey(argArray)) {
invokeArgsToSize.put(argArray, null);
resolveInvoke(invokeSites);
}
}
}
public void addPossibleArgArraySize(Local argArray, int value, Context context) {
assert (context == null);
final Set<InvokeCallSite> invokeSites = invokeArgsToInvokeSite.get(argArray);
if (invokeSites != null) {
// non-det size
BitSet sizeSet = invokeArgsToSize.get(argArray);
if (sizeSet == null || !sizeSet.isEmpty()) {
if (sizeSet == null) {
invokeArgsToSize.put(argArray, sizeSet = new BitSet());
}
if (!sizeSet.get(value)) {
sizeSet.set(value);
resolveInvoke(invokeSites);
}
}
}
}
private static Set<RefLikeType> resolveToClasses(Set<Type> rawTypes) {
Set<RefLikeType> toReturn = new HashSet<>();
if (!rawTypes.isEmpty()) {
final FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
for (Type ty : rawTypes) {
if (ty instanceof AnySubType) {
AnySubType anySubType = (AnySubType) ty;
RefType base = anySubType.getBase();
Set<SootClass> classRoots;
if (base.getSootClass().isInterface()) {
classRoots = fh.getAllImplementersOfInterface(base.getSootClass());
} else {
classRoots = Collections.singleton(base.getSootClass());
}
toReturn.addAll(getTransitiveSubClasses(classRoots));
} else if (ty instanceof RefType) {
toReturn.add((RefType) ty);
}
}
}
return toReturn;
}
private static Collection<RefLikeType> getTransitiveSubClasses(Set<SootClass> classRoots) {
Set<RefLikeType> resolved = new HashSet<>();
if (!classRoots.isEmpty()) {
final FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
for (LinkedList<SootClass> worklist = new LinkedList<>(classRoots); !worklist.isEmpty();) {
SootClass cls = worklist.removeFirst();
if (resolved.add(cls.getType())) {
worklist.addAll(fh.getSubclassesOf(cls));
}
}
}
return resolved;
}
private void resolveInvoke(Collection<InvokeCallSite> list) {
for (InvokeCallSite ics : list) {
Set<Type> s = reachingBaseTypes.get(ics.base());
if (s == null || s.isEmpty()) {
continue;
}
if (ics.reachingTypes() != null) {
assert (ics.nullnessCode() != InvokeCallSite.MUST_BE_NULL);
resolveStaticTypes(s, ics);
continue;
}
boolean mustNotBeNull = ics.nullnessCode() == InvokeCallSite.MUST_NOT_BE_NULL;
boolean mustBeNull = ics.nullnessCode() == InvokeCallSite.MUST_BE_NULL;
// if the arg array may be null and we haven't seen a size or type
// yet, then generate nullary methods
if (mustBeNull || (ics.nullnessCode() == InvokeCallSite.MAY_BE_NULL
&& (!invokeArgsToSize.containsKey(ics.argArray()) || !reachingArgTypes.containsKey(ics.argArray())))) {
for (Type bType : resolveToClasses(s)) {
assert (bType instanceof RefType);
// do not handle array reflection
if (bType instanceof ArrayType) {
continue;
}
SootClass baseClass = ((RefType) bType).getSootClass();
assert (!baseClass.isInterface());
for (Iterator<SootMethod> mIt = getPublicNullaryMethodIterator(baseClass); mIt.hasNext();) {
SootMethod sm = mIt.next();
cm.addVirtualEdge(ics.getContainer(), ics.getStmt(), sm, Kind.REFL_INVOKE, null);
}
}
} else {
/*
* In this branch, either the invoke arg must not be null, or may be null and we have size and type information.
* Invert the above condition: ~mustBeNull && (~mayBeNull || (has-size && has-type)) => (~mustBeNull && ~mayBeNull)
* || (~mustBeNull && has-size && has-type) => mustNotBeNull || (~mustBeNull && has-types && has-size) =>
* mustNotBeNull || (mayBeNull && has-types && has-size)
*/
Set<Type> reachingTypes = reachingArgTypes.get(ics.argArray());
/*
* the path condition allows must-not-be null without type and size info. Do nothing in this case. THIS IS UNSOUND if
* default null values in an argument array are used.
*/
if (reachingTypes == null || !invokeArgsToSize.containsKey(ics.argArray())) {
assert (ics.nullnessCode() == InvokeCallSite.MUST_NOT_BE_NULL) : ics;
return;
}
BitSet methodSizes = invokeArgsToSize.get(ics.argArray());
for (Type bType : resolveToClasses(s)) {
assert (bType instanceof RefLikeType);
// we do not handle static methods or array reflection
if (!(bType instanceof NullType) && !(bType instanceof ArrayType)) {
SootClass baseClass = ((RefType) bType).getSootClass();
Iterator<SootMethod> mIt = getPublicMethodIterator(baseClass, reachingTypes, methodSizes, mustNotBeNull);
while (mIt.hasNext()) {
SootMethod sm = mIt.next();
cm.addVirtualEdge(ics.container(), ics.stmt(), sm, Kind.REFL_INVOKE, null);
}
}
}
}
}
}
/* End of public methods. */
private void resolveStaticTypes(Set<Type> s, InvokeCallSite ics) {
ArrayTypes at = ics.reachingTypes();
for (Type bType : resolveToClasses(s)) {
// do not handle array reflection
if (bType instanceof ArrayType) {
continue;
}
SootClass baseClass = ((RefType) bType).getSootClass();
for (Iterator<SootMethod> mIt = getPublicMethodIterator(baseClass, at); mIt.hasNext();) {
SootMethod sm = mIt.next();
cm.addVirtualEdge(ics.getContainer(), ics.getStmt(), sm, Kind.REFL_INVOKE, null);
}
}
}
private static Iterator<SootMethod> getPublicMethodIterator(SootClass baseClass, final ArrayTypes at) {
return new AbstractMethodIterator(baseClass) {
@Override
protected boolean acceptMethod(SootMethod m) {
if (!at.possibleSizes.contains(m.getParameterCount())) {
return false;
}
for (int i = 0; i < m.getParameterCount(); i++) {
Set<Type> possibleType = at.possibleTypes[i];
if (possibleType.isEmpty()) {
continue;
}
if (!isReflectionCompatible(m.getParameterType(i), possibleType)) {
return false;
}
}
return true;
}
};
}
private static PrimType[] narrowings(PrimType f) {
if (f instanceof IntType) {
return INT_NARROWINGS;
} else if (f instanceof ShortType) {
return SHORT_NARROWINGS;
} else if (f instanceof LongType) {
return LONG_NARROWINGS;
} else if (f instanceof ByteType) {
return BYTE_NARROWINGS;
} else if (f instanceof FloatType) {
return FLOAT_NARROWINGS;
} else if (f instanceof BooleanType) {
return BOOLEAN_NARROWINGS;
} else if (f instanceof DoubleType) {
return DOUBLE_NARROWINGS;
} else if (f instanceof CharType) {
return CHAR_NARROWINGS;
} else {
throw new RuntimeException("Unexpected primitive type: " + f);
}
}
private static boolean isReflectionCompatible(Type paramType, Set<Type> reachingTypes) {
/*
* attempting to pass in a null will match any type (although attempting to pass it to a primitive arg will give an NPE)
*/
if (reachingTypes.contains(NullType.v())) {
return true;
}
if (paramType instanceof RefLikeType) {
final FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
for (Type rType : reachingTypes) {
if (fh.canStoreType(rType, paramType)) {
return true;
}
}
return false;
} else if (paramType instanceof PrimType) {
/*
* It appears, java reflection allows for unboxing followed by widening, so if there is a wrapper type that whose
* corresponding primitive type can be widened into the expected primitive type, we're set
*/
for (PrimType narrowings : narrowings((PrimType) paramType)) {
if (reachingTypes.contains(narrowings.boxedType())) {
return true;
}
}
return false;
} else {
// impossible?
return false;
}
}
private static Iterator<SootMethod> getPublicMethodIterator(final SootClass baseClass, final Set<Type> reachingTypes,
final BitSet methodSizes, final boolean mustNotBeNull) {
if (baseClass.isPhantom()) {
return Collections.emptyIterator();
}
return new AbstractMethodIterator(baseClass) {
@Override
protected boolean acceptMethod(SootMethod n) {
if (methodSizes != null) {
// if the arg array can be null we have to still allow for nullary methods
int nParams = n.getParameterCount();
boolean compatibleSize = methodSizes.get(nParams) || (!mustNotBeNull && nParams == 0);
if (!compatibleSize) {
return false;
}
}
for (Type pTy : n.getParameterTypes()) {
if (!isReflectionCompatible(pTy, reachingTypes)) {
return false;
}
}
return true;
}
};
}
private static Iterator<SootMethod> getPublicNullaryMethodIterator(final SootClass baseClass) {
if (baseClass.isPhantom()) {
return Collections.emptyIterator();
}
return new AbstractMethodIterator(baseClass) {
@Override
protected boolean acceptMethod(SootMethod n) {
return n.getParameterCount() == 0;
}
};
}
public void addType(Local receiver, Context srcContext, Type type, Context typeContext) {
final List<VirtualCallSite> rcvrToCallSites = receiverToSites.get(receiver);
if (rcvrToCallSites != null) {
final VirtualCalls virtualCalls = VirtualCalls.v();
final Scene sc = Scene.v();
final FastHierarchy fh = sc.getOrMakeFastHierarchy();
for (final VirtualCallSite site : rcvrToCallSites) {
if (skipSite(site, fh, type)) {
continue;
}
final InstanceInvokeExpr iie = site.iie();
if (iie instanceof SpecialInvokeExpr && !Kind.isFake(site.kind())) {
SootMethod target = virtualCalls.resolveSpecial(iie.getMethodRef(), site.getContainer(), appOnly);
// if the call target resides in a phantom class then "target" will be null;
// simply do not add the target in that case
if (target != null) {
targetsQueue.add(target);
}
} else {
SootMethodRef ref = null;
Type receiverType = receiver.getType();
// Fake edges map to a different method signature, e.g., from execute(a) to a.run()
if (receiverType instanceof RefType) {
SootClass receiverClass = ((RefType) receiverType).getSootClass();
MethodSubSignature subsig = site.subSig();
ref = sc.makeMethodRef(receiverClass, subsig.methodName, subsig.parameterTypes, subsig.getReturnType(),
Kind.isStatic(site.kind()));
} else {
ref = site.getStmt().getInvokeExpr().getMethodRef();
}
if (ref != null) {
virtualCalls.resolve(type, receiver.getType(), ref, site.getContainer(), targetsQueue, appOnly);
if (!targets.hasNext() && options.resolve_all_abstract_invokes()) {
/*
* In the situation where we find nothing to resolve an invoke to in the first call, this might be because the
* type for the invoking object is a abstract class and the method is declared in a parent class. In this
* situation, when the abstract class has no classes that extend it in the scene, resolve would not find any
* targets for the invoke, even if the parent contained a possible target.
*
* This may have been by design since without a concrete class, we have no idea if the method in the parent
* class is overridden. However, the same could be said for any non private method in the abstract class (and
* these all resolve fine inside the abstract class even though there are no sub classes of the abstract
* class). This makes this situation a corner case.
*
* Where as, it used to not resolve any targets in this situation, I want to at least resolve the method in the
* parent class if there is one (as this is technically a possibility and the only information we have).
*/
virtualCalls.resolveSuperType(type, receiver.getType(), iie.getMethodRef(), targetsQueue, appOnly);
}
}
}
while (targets.hasNext()) {
SootMethod target = targets.next();
cm.addVirtualEdge(MethodContext.v(site.getContainer(), srcContext), site.getStmt(), target, site.kind(),
typeContext);
}
}
}
if (baseToInvokeSite.get(receiver) != null) {
addBaseType(receiver, srcContext, type);
}
}
protected boolean skipSite(VirtualCallSite site, FastHierarchy fh, Type type) {
Kind k = site.kind();
if (k == Kind.THREAD) {
return !fh.canStoreType(type, clRunnable);
} else if (k == Kind.EXECUTOR) {
return !fh.canStoreType(type, clRunnable);
} else if (k == Kind.ASYNCTASK) {
return !fh.canStoreType(type, clAsyncTask);
} else if (k == Kind.HANDLER) {
return !fh.canStoreType(type, clHandler);
} else {
return false;
}
}
public boolean wantStringConstants(Local stringConst) {
return stringConstToSites.get(stringConst) != null;
}
public void addStringConstant(Local l, Context srcContext, String constant) {
if (constant != null) {
final Scene sc = Scene.v();
for (Iterator<VirtualCallSite> siteIt = stringConstToSites.get(l).iterator(); siteIt.hasNext();) {
final VirtualCallSite site = siteIt.next();
final int constLen = constant.length();
if (constLen > 0 && constant.charAt(0) == '[') {
if (constLen > 2 && constant.charAt(1) == 'L' && constant.charAt(constLen - 1) == ';') {
constant = constant.substring(2, constLen - 1);
} else {
continue;
}
}
if (sc.containsClass(constant)) {
SootClass sootcls = sc.getSootClass(constant);
if (!sootcls.isApplicationClass() && !sootcls.isPhantom()) {
sootcls.setLibraryClass();
}
for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) {
cm.addStaticEdge(MethodContext.v(site.getContainer(), srcContext), site.getStmt(), clinit, Kind.CLINIT);
}
} else if (options.verbose()) {
logger.warn("Class " + constant + " is a dynamic class and was not specified as such; graph will be incomplete!");
}
}
} else if (options.verbose()) {
for (Iterator<VirtualCallSite> siteIt = stringConstToSites.get(l).iterator(); siteIt.hasNext();) {
final VirtualCallSite site = siteIt.next();
logger.warn("Method " + site.getContainer() + " is reachable, and calls Class.forName on a non-constant"
+ " String; graph will be incomplete! Use safe-forname option for a conservative result.");
}
}
}
public boolean wantArrayField(AllocDotField df) {
return allocDotFieldToLocal.containsKey(df);
}
public void addInvokeArgType(AllocDotField df, Context context, Type type) {
if (allocDotFieldToLocal.containsKey(df)) {
for (Local l : allocDotFieldToLocal.get(df)) {
addInvokeArgType(l, context, type);
}
}
}
public boolean wantInvokeArg(Local receiver) {
return invokeArgsToInvokeSite.containsKey(receiver);
}
public void addInvokeArgDotField(Local receiver, AllocDotField dot) {
allocDotFieldToLocal.put(dot, receiver);
}
/*
* How type based reflection resolution works:
*
* In general, for each call to invoke(), we record the local of the receiver argument and the argument array. Whenever a
* new type is added to the points to set of the receiver argument we add that type to the reachingBaseTypes and try to
* resolve the reflective method call (see addType, addBaseType, and updatedNode() in OnFlyCallGraph).
*
* For added precision, we also record the second argument to invoke. If it is always null, this means the invoke() call
* resolves only to nullary methods.
*
* When the second argument is a variable that must not be null we can narrow down the called method based on the possible
* sizes of the argument array and the types it contains. Whenever a new allocation reaches this variable we record the
* possible size of the array (by looking at the allocation site) and the possible types stored in the array (see
* updatedNode in OnFlyCallGraph in the branch wantInvokeArg()). If the size of the array isn't statically known, the
* analysis considers methods of all possible arities. In addition, we track the PAG node corresponding to the array
* contents. If a new type reaches this node, we update the possible argument types. (see propagate() in PropWorklist and
* the visitor, and updatedFieldRef in OnFlyCallGraph).
*
* For details on the method resolution process, see resolveInvoke()
*
* Finally, for cases like o.invoke(b, foo, bar, baz); it is very easy to statically determine precisely which types are in
* which argument positions. This is computed using the ConstantArrayAnalysis and are resolved using resolveStaticTypes().
*/
private void addInvokeCallSite(Stmt s, SootMethod container, InstanceInvokeExpr d) {
Local l = (Local) d.getArg(0);
Value argArray = d.getArg(1);
InvokeCallSite ics;
if (argArray instanceof NullConstant) {
ics = new InvokeCallSite(s, container, d, l);
} else {
if (analysisKey != container) {
ExceptionalUnitGraph graph = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(container.getActiveBody());
nullnessCache = new NullnessAnalysis(graph);
arrayCache = new ConstantArrayAnalysis(graph, container.getActiveBody());
analysisKey = container;
}
Local argLocal = (Local) argArray;
int nullnessCode;
if (nullnessCache.isAlwaysNonNullBefore(s, argLocal)) {
nullnessCode = InvokeCallSite.MUST_NOT_BE_NULL;
} else if (nullnessCache.isAlwaysNullBefore(s, argLocal)) {
nullnessCode = InvokeCallSite.MUST_BE_NULL;
} else {
nullnessCode = InvokeCallSite.MAY_BE_NULL;
}
if (nullnessCode != InvokeCallSite.MUST_BE_NULL && arrayCache.isConstantBefore(s, argLocal)) {
ArrayTypes reachingArgTypes = arrayCache.getArrayTypesBefore(s, argLocal);
if (nullnessCode == InvokeCallSite.MAY_BE_NULL) {
reachingArgTypes.possibleSizes.add(0);
}
ics = new InvokeCallSite(s, container, d, l, reachingArgTypes, nullnessCode);
} else {
ics = new InvokeCallSite(s, container, d, l, argLocal, nullnessCode);
invokeArgsToInvokeSite.put(argLocal, ics);
}
}
baseToInvokeSite.put(l, ics);
}
private void addVirtualCallSite(Stmt s, SootMethod m, Local receiver, InstanceInvokeExpr iie, MethodSubSignature subSig,
Kind kind) {
List<VirtualCallSite> sites = receiverToSites.get(receiver);
if (sites == null) {
receiverToSites.put(receiver, sites = new ArrayList<VirtualCallSite>());
List<Local> receivers = methodToReceivers.get(m);
if (receivers == null) {
methodToReceivers.put(m, receivers = new ArrayList<Local>());
}
receivers.add(receiver);
}
sites.add(new VirtualCallSite(s, m, iie, subSig, kind));
}
private void processNewMethod(SootMethod m) {
if (m.isConcrete()) {
Body b = m.retrieveActiveBody();
getImplicitTargets(m);
findReceivers(m, b);
}
}
private void findReceivers(SootMethod m, Body b) {
for (final Unit u : b.getUnits()) {
final Stmt s = (Stmt) u;
if (s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
Local receiver = (Local) iie.getBase();
MethodSubSignature subSig = new MethodSubSignature(iie.getMethodRef());
addVirtualCallSite(s, m, receiver, iie, new MethodSubSignature(iie.getMethodRef()), Edge.ieToKind(iie));
VirtualEdge virtualEdge = virtualEdgeSummaries.getVirtualEdgesMatchingSubSig(subSig);
if (virtualEdge != null) {
for (VirtualEdgeTarget t : virtualEdge.targets) {
processVirtualEdgeSummary(m, s, receiver, t, virtualEdge.edgeType);
}
}
} else if (ie instanceof DynamicInvokeExpr) {
if (options.verbose()) {
logger.warn("InvokeDynamic to " + ie + " not resolved during call-graph construction.");
}
} else {
SootMethod tgt = ie.getMethod();
if (tgt != null) {
addEdge(m, s, tgt);
String signature = tgt.getSignature();
VirtualEdge virtualEdge = virtualEdgeSummaries.getVirtualEdgesMatchingFunction(signature);
if (virtualEdge != null) {
for (VirtualEdgeTarget t : virtualEdge.targets) {
if (t instanceof DirectTarget) {
DirectTarget directTarget = (DirectTarget) t;
if (t.isBase()) {
// this should not happen
} else {
Value runnable = ie.getArg(t.argIndex);
if (runnable instanceof Local) {
addVirtualCallSite(s, m, (Local) runnable, null, directTarget.targetMethod, Kind.GENERIC_FAKE);
}
}
}
}
}
} else if (!Options.v().ignore_resolution_errors()) {
throw new InternalError(
"Unresolved target " + ie.getMethod() + ". Resolution error should have occured earlier.");
}
}
}
}
}
protected void processVirtualEdgeSummary(SootMethod m, final Stmt s, Local receiver, VirtualEdgeTarget target,
Kind edgeType) {
processVirtualEdgeSummary(m, s, s, receiver, target, edgeType);
}
protected void processVirtualEdgeSummary(SootMethod callSiteMethod, Stmt callSite, final Stmt curStmt, Local receiver,
VirtualEdgeTarget target, Kind edgeType) {
// Get the target object referenced by this edge summary
InvokeExpr ie = curStmt.getInvokeExpr();
Local targetLocal = null;
if (target.isBase()) {
targetLocal = receiver;
} else if (target.argIndex < ie.getArgCount()) {
Value runnable = ie.getArg(target.argIndex);
if (runnable instanceof Local) {
targetLocal = (Local) runnable;
}
}
if (targetLocal == null) {
return;
}
if (target instanceof DirectTarget) {
// A direct target means that we need to build an edge from the call site to a method on the current base object or a
// parameter argument
DirectTarget directTarget = (DirectTarget) target;
addVirtualCallSite(callSite, callSiteMethod, targetLocal, (InstanceInvokeExpr) ie, directTarget.targetMethod,
edgeType);
} else if (target instanceof IndirectTarget) {
// For an indirect target, we need to find out where the base object or a specific parameter argument was
// constructed. We then either have a direct target on that statement, or again an indirect one for searching further
// up in the code.
IndirectTarget w = (IndirectTarget) target;
// addVirtualCallSite() may change receiverToSites, which may lead to a ConcurrentModificationException
// I'm not entirely sure whether we ought to deal with the new call sites that are being added, instead of
// just working on a snapshot, though.
List<VirtualCallSite> indirectSites = receiverToSites.get(targetLocal);
if (indirectSites != null) {
for (final VirtualCallSite site : new ArrayList<>(indirectSites)) {
if (w.getTargetMethod().equals(site.subSig())) {
for (VirtualEdgeTarget siteTarget : w.getTargets()) {
Stmt siteStmt = site.getStmt();
if (siteStmt.containsInvokeExpr()) {
processVirtualEdgeSummary(callSiteMethod, callSite, siteStmt, receiver, siteTarget, edgeType);
}
}
}
}
}
}
}
private void getImplicitTargets(SootMethod source) {
final SootClass scl = source.getDeclaringClass();
if (!source.isConcrete()) {
return;
}
if (source.getSubSignature().contains("<init>")) {
handleInit(source, scl);
}
for (Unit u : source.retrieveActiveBody().getUnits()) {
final Stmt s = (Stmt) u;
if (s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
SootMethodRef methodRef = ie.getMethodRef();
switch (methodRef.getDeclaringClass().getName()) {
case "java.lang.reflect.Method":
if ("java.lang.Object invoke(java.lang.Object,java.lang.Object[])"
.equals(methodRef.getSubSignature().getString())) {
reflectionModel.methodInvoke(source, s);
}
break;
case "java.lang.Class":
if ("java.lang.Object newInstance()".equals(methodRef.getSubSignature().getString())) {
reflectionModel.classNewInstance(source, s);
}
break;
case "java.lang.reflect.Constructor":
if ("java.lang.Object newInstance(java.lang.Object[])".equals(methodRef.getSubSignature().getString())) {
reflectionModel.contructorNewInstance(source, s);
}
break;
}
if (methodRef.getSubSignature() == sigForName) {
reflectionModel.classForName(source, s);
}
if (ie instanceof StaticInvokeExpr) {
SootClass cl = ie.getMethodRef().getDeclaringClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge(source, s, clinit, Kind.CLINIT);
}
}
}
if (s.containsFieldRef()) {
FieldRef fr = s.getFieldRef();
if (fr instanceof StaticFieldRef) {
SootClass cl = fr.getFieldRef().declaringClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge(source, s, clinit, Kind.CLINIT);
}
}
}
if (s instanceof AssignStmt) {
Value rhs = ((AssignStmt) s).getRightOp();
if (rhs instanceof NewExpr) {
NewExpr r = (NewExpr) rhs;
SootClass cl = r.getBaseType().getSootClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge(source, s, clinit, Kind.CLINIT);
}
} else if (rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr) {
Type t = rhs.getType();
if (t instanceof ArrayType) {
t = ((ArrayType) t).baseType;
}
if (t instanceof RefType) {
SootClass cl = ((RefType) t).getSootClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge(source, s, clinit, Kind.CLINIT);
}
}
}
}
}
}
protected void processNewMethodContext(MethodOrMethodContext momc) {
SootMethod m = momc.method();
for (Iterator<Edge> it = cicg.edgesOutOf(m); it.hasNext();) {
Edge e = it.next();
cm.addStaticEdge(momc, e.srcUnit(), e.tgt(), e.kind());
}
}
private void handleInit(SootMethod source, final SootClass scl) {
addEdge(source, null, scl, sigFinalize, Kind.FINALIZE);
}
private void constantForName(final String cls, SootMethod src, Stmt srcUnit) {
final int clsLen = cls.length();
if (clsLen > 0 && cls.charAt(0) == '[') {
if (clsLen > 2 && cls.charAt(1) == 'L' && cls.charAt(clsLen - 1) == ';') {
constantForName(cls.substring(2, clsLen - 1), src, srcUnit);
}
} else {
final Scene sc = Scene.v();
if (sc.containsClass(cls)) {
SootClass sootcls = sc.getSootClass(cls);
if (!sootcls.isPhantomClass()) {
if (!sootcls.isApplicationClass()) {
sootcls.setLibraryClass();
}
for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) {
addEdge(src, srcUnit, clinit, Kind.CLINIT);
}
}
} else if (options.verbose()) {
logger.warn("Class " + cls + " is a dynamic class and was not specified as such; graph will be incomplete!");
}
}
}
private void addEdge(SootMethod src, Stmt stmt, SootMethod tgt, Kind kind) {
if (src.equals(tgt) && src.isStaticInitializer()) {
return;
}
cicg.addEdge(new Edge(src, stmt, tgt, kind));
}
private void addEdge(SootMethod src, Stmt stmt, SootClass cls, NumberedString methodSubSig, Kind kind) {
SootMethod sm = cls.getMethodUnsafe(methodSubSig);
if (sm != null) {
addEdge(src, stmt, sm, kind);
}
}
private void addEdge(SootMethod src, Stmt stmt, SootMethod tgt) {
InvokeExpr ie = stmt.getInvokeExpr();
addEdge(src, stmt, tgt, Edge.ieToKind(ie));
}
public class DefaultReflectionModel implements ReflectionModel {
protected final CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
protected final HashSet<SootMethod> warnedAlready = new HashSet<SootMethod>();
@Override
public void classForName(SootMethod source, Stmt s) {
List<Local> stringConstants = methodToStringConstants.get(source);
if (stringConstants == null) {
methodToStringConstants.put(source, stringConstants = new ArrayList<Local>());
}
Value className = s.getInvokeExpr().getArg(0);
if (className instanceof StringConstant) {
String cls = ((StringConstant) className).value;
constantForName(cls, source, s);
} else if (className instanceof Local) {
Local constant = (Local) className;
if (options.safe_forname()) {
for (SootMethod tgt : EntryPoints.v().clinits()) {
addEdge(source, s, tgt, Kind.CLINIT);
}
} else {
final EntryPoints ep = EntryPoints.v();
for (SootClass cls : Scene.v().dynamicClasses()) {
for (SootMethod clinit : ep.clinitsOf(cls)) {
addEdge(source, s, clinit, Kind.CLINIT);
}
}
VirtualCallSite site = new VirtualCallSite(s, source, null, null, Kind.CLINIT);
List<VirtualCallSite> sites = stringConstToSites.get(constant);
if (sites == null) {
stringConstToSites.put(constant, sites = new ArrayList<VirtualCallSite>());
stringConstants.add(constant);
}
sites.add(site);
}
}
}
@Override
public void classNewInstance(SootMethod source, Stmt s) {
if (options.safe_newinstance()) {
for (SootMethod tgt : EntryPoints.v().inits()) {
addEdge(source, s, tgt, Kind.NEWINSTANCE);
}
} else {
for (SootClass cls : Scene.v().dynamicClasses()) {
SootMethod sm = cls.getMethodUnsafe(sigInit);
if (sm != null) {
addEdge(source, s, sm, Kind.NEWINSTANCE);
}
}
if (options.verbose()) {
logger.warn("Method " + source + " is reachable, and calls Class.newInstance; graph will be incomplete!"
+ " Use safe-newinstance option for a conservative result.");
}
}
}
@Override
public void contructorNewInstance(SootMethod source, Stmt s) {
if (options.safe_newinstance()) {
for (SootMethod tgt : EntryPoints.v().allInits()) {
addEdge(source, s, tgt, Kind.NEWINSTANCE);
}
} else {
for (SootClass cls : Scene.v().dynamicClasses()) {
for (SootMethod m : cls.getMethods()) {
if ("<init>".equals(m.getName())) {
addEdge(source, s, m, Kind.NEWINSTANCE);
}
}
}
if (options.verbose()) {
logger.warn("Method " + source + " is reachable, and calls Constructor.newInstance; graph will be incomplete!"
+ " Use safe-newinstance option for a conservative result.");
}
}
}
@Override
public void methodInvoke(SootMethod container, Stmt invokeStmt) {
if (!warnedAlready(container)) {
if (options.verbose()) {
logger.warn("Call to java.lang.reflect.Method: invoke() from " + container + "; graph will be incomplete!");
}
markWarned(container);
}
}
private void markWarned(SootMethod m) {
warnedAlready.add(m);
}
private boolean warnedAlready(SootMethod m) {
return warnedAlready.contains(m);
}
}
public class TypeBasedReflectionModel extends DefaultReflectionModel {
@Override
public void methodInvoke(SootMethod container, Stmt invokeStmt) {
if (container.getDeclaringClass().isJavaLibraryClass()) {
super.methodInvoke(container, invokeStmt);
return;
}
InstanceInvokeExpr d = (InstanceInvokeExpr) invokeStmt.getInvokeExpr();
Value base = d.getArg(0);
// TODO no support for statics at the moment
// SA: Better just fall back to degraded functionality than fail altogether
if (!(base instanceof Local)) {
super.methodInvoke(container, invokeStmt);
return;
}
addInvokeCallSite(invokeStmt, container, d);
}
}
public class TraceBasedReflectionModel implements ReflectionModel {
protected final Set<Guard> guards;
protected final ReflectionTraceInfo reflectionInfo;
private TraceBasedReflectionModel() {
String logFile = options.reflection_log();
if (logFile == null) {
throw new InternalError("Trace based refection model enabled but no trace file given!?");
}
this.reflectionInfo = new ReflectionTraceInfo(logFile);
this.guards = new HashSet<Guard>();
}
/**
* Adds an edge to all class initializers of all possible receivers of Class.forName() calls within source.
*/
@Override
public void classForName(SootMethod container, Stmt forNameInvokeStmt) {
Set<String> classNames = reflectionInfo.classForNameClassNames(container);
if (classNames == null || classNames.isEmpty()) {
registerGuard(container, forNameInvokeStmt,
"Class.forName() call site; Soot did not expect this site to be reached");
} else {
for (String clsName : classNames) {
constantForName(clsName, container, forNameInvokeStmt);
}
}
}
/**
* Adds an edge to the constructor of the target class from this call to {@link Class#newInstance()}.
*/
@Override
public void classNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) {
Set<String> classNames = reflectionInfo.classNewInstanceClassNames(container);
if (classNames == null || classNames.isEmpty()) {
registerGuard(container, newInstanceInvokeStmt,
"Class.newInstance() call site; Soot did not expect this site to be reached");
} else {
final Scene sc = Scene.v();
for (String clsName : classNames) {
SootMethod constructor = sc.getSootClass(clsName).getMethodUnsafe(sigInit);
if (constructor != null) {
addEdge(container, newInstanceInvokeStmt, constructor, Kind.REFL_CLASS_NEWINSTANCE);
}
}
}
}
/**
* Adds a special edge of kind {@link Kind#REFL_CONSTR_NEWINSTANCE} to all possible target constructors of this call to
* {@link Constructor#newInstance(Object...)}. Those kinds of edges are treated specially in terms of how parameters are
* assigned, as parameters to the reflective call are passed into the argument array of
* {@link Constructor#newInstance(Object...)}.
*
* @see PAG#addCallTarget(Edge)
*/
@Override
public void contructorNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) {
Set<String> constructorSignatures = reflectionInfo.constructorNewInstanceSignatures(container);
if (constructorSignatures == null || constructorSignatures.isEmpty()) {
registerGuard(container, newInstanceInvokeStmt,
"Constructor.newInstance(..) call site; Soot did not expect this site to be reached");
} else {
final Scene sc = Scene.v();
for (String constructorSignature : constructorSignatures) {
SootMethod constructor = sc.getMethod(constructorSignature);
addEdge(container, newInstanceInvokeStmt, constructor, Kind.REFL_CONSTR_NEWINSTANCE);
}
}
}
/**
* Adds a special edge of kind {@link Kind#REFL_INVOKE} to all possible target methods of this call to
* {@link Method#invoke(Object, Object...)}. Those kinds of edges are treated specially in terms of how parameters are
* assigned, as parameters to the reflective call are passed into the argument array of
* {@link Method#invoke(Object, Object...)}.
*
* @see PAG#addCallTarget(Edge)
*/
@Override
public void methodInvoke(SootMethod container, Stmt invokeStmt) {
Set<String> methodSignatures = reflectionInfo.methodInvokeSignatures(container);
if (methodSignatures == null || methodSignatures.isEmpty()) {
registerGuard(container, invokeStmt, "Method.invoke(..) call site; Soot did not expect this site to be reached");
} else {
final Scene sc = Scene.v();
for (String methodSignature : methodSignatures) {
SootMethod method = sc.getMethod(methodSignature);
addEdge(container, invokeStmt, method, Kind.REFL_INVOKE);
}
}
}
private void registerGuard(SootMethod container, Stmt stmt, String string) {
guards.add(new Guard(container, stmt, string));
if (options.verbose()) {
logger.debug("Incomplete trace file: Class.forName() is called in method '" + container
+ "' but trace contains no information about the receiver class of this call.");
switch (options.guards()) {
case "ignore":
logger.debug("Guarding strategy is set to 'ignore'. Will ignore this problem.");
break;
case "print":
logger.debug("Guarding strategy is set to 'print'. "
+ "Program will print a stack trace if this location is reached during execution.");
break;
case "throw":
logger.debug("Guarding strategy is set to 'throw'. "
+ "Program will throw an error if this location is reached during execution.");
break;
default:
throw new RuntimeException("Invalid value for phase option (guarding): " + options.guards());
}
}
if (!registeredGuardsTransformation) {
registeredGuardsTransformation = true;
PackManager.v().getPack("wjap").add(new Transform("wjap.guards", new SceneTransformer() {
@Override
protected void internalTransform(String phaseName, Map<String, String> options) {
for (Guard g : guards) {
insertGuard(g);
}
}
}));
PhaseOptions.v().setPhaseOption("wjap.guards", "enabled");
}
}
private void insertGuard(Guard guard) {
if ("ignore".equals(options.guards())) {
return;
}
SootMethod container = guard.container;
if (!container.hasActiveBody()) {
logger.warn("Tried to insert guard into " + container + " but couldn't because method has no body.");
} else {
final Jimple jimp = Jimple.v();
final Body body = container.getActiveBody();
final UnitPatchingChain units = body.getUnits();
final LocalGenerator lg = Scene.v().createLocalGenerator(body);
// exc = new Error
RefType runtimeExceptionType = RefType.v("java.lang.Error");
Local exceptionLocal = lg.generateLocal(runtimeExceptionType);
AssignStmt assignStmt = jimp.newAssignStmt(exceptionLocal, jimp.newNewExpr(runtimeExceptionType));
units.insertBefore(assignStmt, guard.stmt);
// exc.<init>(message)
SootMethodRef cref = runtimeExceptionType.getSootClass()
.getMethod("<init>", Collections.<Type>singletonList(RefType.v("java.lang.String"))).makeRef();
InvokeStmt initStmt
= jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v(guard.message)));
units.insertAfter(initStmt, assignStmt);
switch (options.guards()) {
case "print":
// logger.error(exc.getMessage(), exc);
VirtualInvokeExpr printStackTraceExpr = jimp.newVirtualInvokeExpr(exceptionLocal, Scene.v()
.getSootClass("java.lang.Throwable").getMethod("printStackTrace", Collections.<Type>emptyList()).makeRef());
units.insertAfter(jimp.newInvokeStmt(printStackTraceExpr), initStmt);
break;
case "throw":
units.insertAfter(jimp.newThrowStmt(exceptionLocal), initStmt);
break;
default:
throw new RuntimeException("Invalid value for phase option (guarding): " + options.guards());
}
}
}
}
static final class Guard {
final SootMethod container;
final Stmt stmt;
final String message;
public Guard(SootMethod container, Stmt stmt, String message) {
this.container = container;
this.stmt = stmt;
this.message = message;
}
}
private static abstract class AbstractMethodIterator implements Iterator<SootMethod> {
private SootMethod next;
private SootClass currClass;
private Iterator<SootMethod> methodIterator;
AbstractMethodIterator(SootClass baseClass) {
this.currClass = baseClass;
this.next = null;
this.methodIterator = baseClass.methodIterator();
this.findNextMethod();
}
protected void findNextMethod() {
next = null;
if (methodIterator != null) {
while (true) {
while (methodIterator.hasNext()) {
SootMethod n = methodIterator.next();
if (!n.isPublic() || n.isStatic() || n.isConstructor() || n.isStaticInitializer() || !n.isConcrete()) {
continue;
}
if (!acceptMethod(n)) {
continue;
}
next = n;
return;
}
if (!currClass.hasSuperclass()) {
methodIterator = null;
return;
}
SootClass superclass = currClass.getSuperclass();
if (superclass.isPhantom() || "java.lang.Object".equals(superclass.getName())) {
methodIterator = null;
return;
} else {
methodIterator = superclass.methodIterator();
currClass = superclass;
}
}
}
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public SootMethod next() {
SootMethod toRet = next;
findNextMethod();
return toRet;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
protected abstract boolean acceptMethod(SootMethod m);
}
}
| 55,545
| 38.53452
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/OneCFAContextManager.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Context;
import soot.Kind;
import soot.MethodContext;
import soot.MethodOrMethodContext;
import soot.SootMethod;
import soot.Unit;
/**
* A context manager which creates a 1-CFA call graph.
*
* @author Ondrej Lhotak
*/
public class OneCFAContextManager implements ContextManager {
private final CallGraph cg;
public OneCFAContextManager(CallGraph cg) {
this.cg = cg;
}
@Override
public void addStaticEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind) {
cg.addEdge(new Edge(src, srcUnit, MethodContext.v(target, srcUnit), kind));
}
@Override
public void addVirtualEdge(MethodOrMethodContext src, Unit srcUnit, SootMethod target, Kind kind, Context typeContext) {
cg.addEdge(new Edge(src, srcUnit, MethodContext.v(target, srcUnit), kind));
}
@Override
public CallGraph callGraph() {
return cg;
}
}
| 1,721
| 28.186441
| 122
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ReachableMethods.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import soot.MethodOrMethodContext;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/**
* Keeps track of the methods transitively reachable from the specified entry points through the given call graph edges.
*
* @author Ondrej Lhotak
*/
public 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() {
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();
Iterator<Edge> targets = cg.edgesOutOf(m);
if (filter != null) {
targets = filter.wrap(targets);
}
addMethods(new Targets(targets));
}
}
/**
* 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();
}
}
| 4,077
| 30.369231
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/ReflectionModel.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.SootMethod;
import soot.jimple.Stmt;
public interface ReflectionModel {
void methodInvoke(SootMethod container, Stmt invokeStmt);
void classNewInstance(SootMethod source, Stmt s);
void contructorNewInstance(SootMethod source, Stmt s);
void classForName(SootMethod source, Stmt s);
}
| 1,168
| 28.974359
| 71
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/SlowCallGraph.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import soot.MethodOrMethodContext;
import soot.Unit;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/**
* Represents the edges in a call graph. This class is meant to act as only a container of edges; code for various call graph
* builders should be kept out of it, as well as most code for accessing the edges.
*
* @author Ondrej Lhotak
*/
public 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() {
StringBuilder out = new StringBuilder();
for (QueueReader<Edge> rdr = listener(); rdr.hasNext();) {
Edge e = rdr.next();
out.append(e.toString()).append('\n');
}
return out.toString();
}
/**
* Returns the number of edges in the call graph.
*/
@Override
public int size() {
return edges.size();
}
}
| 4,414
| 28.433333
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/Sources.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import soot.MethodOrMethodContext;
/**
* Adapts an iterator over a collection of Edge's to be an iterator over the source methods of the edges.
*
* @author Ondrej Lhotak
*/
public final class Sources implements Iterator<MethodOrMethodContext> {
final Iterator<Edge> edges;
public Sources(Iterator<Edge> edges) {
this.edges = edges;
}
@Override
public boolean hasNext() {
return edges.hasNext();
}
@Override
public MethodOrMethodContext next() {
Edge e = edges.next();
return e.getSrc();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 1,490
| 25.157895
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/Targets.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import soot.MethodOrMethodContext;
/**
* Adapts an iterator over a collection of Edge's to be an iterator over the target methods of the edges.
*
* @author Ondrej Lhotak
*/
public final class Targets implements Iterator<MethodOrMethodContext> {
final Iterator<Edge> edges;
public Targets(Iterator<Edge> edges) {
this.edges = edges;
}
@Override
public boolean hasNext() {
return edges.hasNext();
}
@Override
public MethodOrMethodContext next() {
Edge e = edges.next();
return e.getTgt();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 1,490
| 25.157895
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/TopologicalOrderer.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import soot.MethodOrMethodContext;
import soot.Scene;
import soot.SootMethod;
import soot.util.NumberedSet;
public class TopologicalOrderer {
private final CallGraph cg;
private final List<SootMethod> order;
private final NumberedSet<SootMethod> visited;
public TopologicalOrderer(CallGraph cg) {
this.cg = cg;
this.order = new ArrayList<SootMethod>();
this.visited = new NumberedSet<SootMethod>(Scene.v().getMethodNumberer());
}
public void go() {
for (Iterator<MethodOrMethodContext> methods = cg.sourceMethods(); methods.hasNext();) {
SootMethod m = (SootMethod) methods.next();
dfsVisit(m);
}
}
private void dfsVisit(SootMethod m) {
if (visited.contains(m)) {
return;
}
visited.add(m);
for (Iterator<MethodOrMethodContext> targets = new Targets(cg.edgesOutOf(m)); targets.hasNext();) {
SootMethod target = (SootMethod) targets.next();
dfsVisit(target);
}
order.add(m);
}
public List<SootMethod> order() {
return order;
}
}
| 1,950
| 27.691176
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/TransitiveTargets.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 - 2004 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import soot.MethodOrMethodContext;
import soot.Unit;
/**
* Extends a TargetsOfMethod or TargetsOfUnit to include edges transitively reachable from any target methods.
*
* @author Ondrej Lhotak
*/
public 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) {
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();
}
}
| 3,217
| 29.074766
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/Units.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Iterator;
import soot.Unit;
/**
* Adapts an iterator over a collection of Edge's to be an iterator over the source units of the edges.
*
* @author Ondrej Lhotak
*/
public final class Units implements Iterator<Unit> {
final Iterator<Edge> edges;
public Units(Iterator<Edge> edges) {
this.edges = edges;
}
@Override
public boolean hasNext() {
return edges.hasNext();
}
@Override
public Unit next() {
Edge e = edges.next();
return e.srcUnit();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 1,433
| 24.607143
| 103
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/UnreachableMethodTransformer.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import java.util.Map;
import java.util.Vector;
import soot.Body;
import soot.BodyTransformer;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.UnitPatchingChain;
import soot.jimple.IntConstant;
import soot.jimple.Jimple;
import soot.jimple.StringConstant;
public class UnreachableMethodTransformer extends BodyTransformer {
@Override
protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
// 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();
*/
}
}
| 4,743
| 44.180952
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/VirtualCallSite.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.Kind;
import soot.MethodSubSignature;
import soot.SootMethod;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.Stmt;
/**
* Holds relevant information about a particular virtual call site.
*
* @author Ondrej Lhotak
*/
public class VirtualCallSite extends AbstractCallSite {
private final InstanceInvokeExpr iie;
private final MethodSubSignature subSig;
final Kind kind;
public VirtualCallSite(Stmt stmt, SootMethod container, InstanceInvokeExpr iie, MethodSubSignature subSig, Kind kind) {
super(stmt, container);
this.iie = iie;
this.subSig = subSig;
this.kind = kind;
}
/**
* @deprecated use {@link #getStmt()}
*/
@Deprecated
public Stmt stmt() {
return stmt;
}
/**
* @deprecated use {@link #getContainer()}
*/
@Deprecated
public SootMethod container() {
return container;
}
public InstanceInvokeExpr iie() {
return iie;
}
public MethodSubSignature subSig() {
return subSig;
}
public Kind kind() {
return kind;
}
}
| 1,875
| 23.363636
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/VirtualCalls.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.AnySubType;
import soot.ArrayType;
import soot.FastHierarchy;
import soot.G;
import soot.NullType;
import soot.PhaseOptions;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Type;
import soot.options.CGOptions;
import soot.toolkits.scalar.Pair;
import soot.util.HashMultiMap;
import soot.util.MultiMap;
import soot.util.queue.ChunkedQueue;
/**
* Resolves virtual calls.
*
* @author Ondrej Lhotak
* @author Manuel Benz 22.10.19 - Delegate dispatch behavior to FastHierarchy to have one common place for extension
*/
public class VirtualCalls {
private static final Logger LOGGER = LoggerFactory.getLogger(VirtualCalls.class);
private final CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
protected MultiMap<Pair<Type, SootMethodRef>, Pair<Type, SootMethodRef>> baseToPossibleSubTypes = new HashMultiMap<>();
public VirtualCalls(Singletons.Global g) {
}
public static VirtualCalls v() {
return G.v().soot_jimple_toolkits_callgraph_VirtualCalls();
}
public SootMethod resolveSpecial(SootMethodRef calleeRef, SootMethod container) {
return resolveSpecial(calleeRef, container, false);
}
public SootMethod resolveSpecial(SootMethodRef calleeRef, SootMethod container, boolean appOnly) {
SootMethod callee = calleeRef.resolve();
/* cf. JVM spec, invokespecial instruction */
final SootClass containerCls = container.getDeclaringClass();
final SootClass calleeCls = callee.getDeclaringClass();
if (containerCls.getType() != calleeCls.getType()
&& Scene.v().getOrMakeFastHierarchy().canStoreType(containerCls.getType(), calleeCls.getType())
&& !SootMethod.constructorName.equals(callee.getName()) && !SootMethod.staticInitializerName.equals(callee.getName())
// default interface methods are explicitly dispatched to the default
// method with a specialinvoke instruction (i.e. do not dispatch to an
// overwritten version of that method)
&& !calleeCls.isInterface()) {
// The invokespecial instruction is used to invoke instance initialization methods as well
// as private methods and methods of a superclass of the current class.
return resolveNonSpecial(containerCls.getSuperclass().getType(), calleeRef, appOnly);
} else {
return callee;
}
}
public SootMethod resolveNonSpecial(RefType t, SootMethodRef callee) {
return resolveNonSpecial(t, callee, false);
}
public SootMethod resolveNonSpecial(RefType t, SootMethodRef callee, boolean appOnly) {
SootClass cls = t.getSootClass();
if (appOnly && cls.isLibraryClass()) {
return null;
} else if (!cls.isInterface()) {
return Scene.v().getOrMakeFastHierarchy().resolveConcreteDispatch(cls, callee);
} else {
return null;
}
}
public void resolve(Type t, Type declaredType, SootMethodRef callee, SootMethod container,
ChunkedQueue<SootMethod> targets) {
resolve(t, declaredType, null, callee, container, targets);
}
public void resolve(Type t, Type declaredType, SootMethodRef callee, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly) {
resolve(t, declaredType, null, callee, container, targets, appOnly);
}
public void resolve(Type t, Type declaredType, Type sigType, SootMethodRef callee, SootMethod container,
ChunkedQueue<SootMethod> targets) {
resolve(t, declaredType, sigType, callee, container, targets, false);
}
public void resolve(Type t, Type declaredType, Type sigType, SootMethodRef callee, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly) {
if (declaredType instanceof ArrayType) {
declaredType = RefType.v("java.lang.Object");
}
if (sigType instanceof ArrayType) {
sigType = RefType.v("java.lang.Object");
}
if (t instanceof ArrayType) {
t = RefType.v("java.lang.Object");
}
FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy();
if (declaredType != null && !fastHierachy.canStoreType(t, declaredType)) {
return;
} else if (sigType != null && !fastHierachy.canStoreType(t, sigType)) {
return;
} else if (t instanceof RefType) {
SootMethod target = resolveNonSpecial((RefType) t, callee, appOnly);
if (target != null) {
targets.add(target);
}
} else if (t instanceof AnySubType) {
RefType base = ((AnySubType) t).getBase();
/*
* Whenever any sub type of a specific type is considered as receiver for a method to call and the base type is an
* interface, calls to existing methods with matching signature (possible implementation of method to call) are also
* added. As Javas' subtyping allows contra-variance for return types and co-variance for parameters when overriding a
* method, these cases are also considered here.
*
* Example: Classes A, B (B sub type of A), interface I with method public A foo(B b); and a class C with method public
* B foo(A a) { ... }. The extended class hierarchy will contain C as possible implementation of I.
*
* Since Java has no multiple inheritance call by signature resolution is only activated if the base is an interface.
*/
if (options.library() == CGOptions.library_signature_resolution && base.getSootClass().isInterface()) {
LOGGER.warn("Deprecated library dispatch is conducted. The results might be unsound...");
resolveLibrarySignature(declaredType, sigType, callee, container, targets, appOnly, base);
} else {
for (SootMethod dispatch : Scene.v().getOrMakeFastHierarchy().resolveAbstractDispatch(base.getSootClass(), callee)) {
targets.add(dispatch);
}
}
} else if (t instanceof NullType) {
return;
} else {
throw new RuntimeException("oops " + t);
}
}
public void resolveSuperType(Type t, Type declaredType, SootMethodRef callee, ChunkedQueue<SootMethod> targets,
boolean appOnly) {
if (declaredType == null || t == null) {
return;
}
if (declaredType instanceof ArrayType) {
declaredType = RefType.v("java.lang.Object");
}
if (t instanceof ArrayType) {
t = RefType.v("java.lang.Object");
}
if (declaredType instanceof RefType) {
RefType child;
if (t instanceof AnySubType) {
child = ((AnySubType) t).getBase();
} else if (t instanceof RefType) {
child = (RefType) t;
} else {
return;
}
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
if (fh.canStoreClass(child.getSootClass(), ((RefType) declaredType).getSootClass())) {
SootMethod target = resolveNonSpecial(child, callee, appOnly);
if (target != null) {
targets.add(target);
}
}
}
}
@Deprecated
protected void resolveLibrarySignature(Type declaredType, Type sigType, SootMethodRef callee, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly, RefType base) {
// This is an old piece of code from before the refactoring of dispatch behavior to
// FastHierarchy
// This cannot handle default interfaces and it's questionable if the logic makes sense. The
// author states that Java allows for co-variant parameters which is not true (it will introduce
// overloading in this case) and co-variance for return values is already managed by the
// FastHierarchy
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
assert (declaredType instanceof RefType);
Pair<Type, SootMethodRef> pair = new Pair<Type, SootMethodRef>(base, callee);
{
Set<Pair<Type, SootMethodRef>> types = baseToPossibleSubTypes.get(pair);
// if this type and method has been resolved earlier we can
// just retrieve the previous result.
if (types != null) {
for (Pair<Type, SootMethodRef> tuple : types) {
Type st = tuple.getO1();
if (!fh.canStoreType(st, declaredType)) {
resolve(st, st, sigType, callee, container, targets, appOnly);
} else {
resolve(st, declaredType, sigType, callee, container, targets, appOnly);
}
}
return;
}
}
Set<Pair<Type, SootMethodRef>> types = new HashSet<>();
Type declaredReturnType = callee.getReturnType();
List<Type> declaredParamTypes = callee.getParameterTypes();
String declaredName = callee.getName();
for (SootClass sc : Scene.v().getClasses()) {
for (SootMethod sm : sc.getMethods()) {
if (!sm.isAbstract()) {
// method name has to match
if (!sm.getName().equals(declaredName)) {
continue;
}
// the return type has to be a the declared return
// type or a sub type of it
if (!fh.canStoreType(sm.getReturnType(), declaredReturnType)) {
continue;
}
List<Type> paramTypes = sm.getParameterTypes();
// method parameters have to match to the declared
// ones (same type or super type).
if (declaredParamTypes.size() != paramTypes.size()) {
continue;
}
boolean check = true;
for (int i = 0; i < paramTypes.size(); i++) {
if (!fh.canStoreType(declaredParamTypes.get(i), paramTypes.get(i))) {
check = false;
break;
}
}
if (check) {
Type st = sc.getType();
if (!fh.canStoreType(st, declaredType)) {
// final classes can not be extended and
// therefore not used in library client
if (!sc.isFinal()) {
resolve(st, st, sigType, sm.makeRef(), container, targets, appOnly);
types.add(new Pair<Type, SootMethodRef>(st, sm.makeRef()));
}
} else {
resolve(st, declaredType, sigType, callee, container, targets, appOnly);
types.add(new Pair<Type, SootMethodRef>(st, callee));
}
}
}
}
}
baseToPossibleSubTypes.putAll(pair, types);
}
}
| 11,214
| 38.076655
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/callgraph/VirtualEdgesSummaries.java
|
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.collect.Iterables;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import soot.Kind;
import soot.MethodSubSignature;
import soot.ModuleUtil;
import soot.Scene;
import soot.jimple.Stmt;
import soot.util.StringNumberer;
/**
* Utility class used by {@link OnFlyCallGraphBuilder} for finding functions at which to place virtual callgraph edges.
* Function signatures are configurable in {@link #SUMMARIESFILE}.
*
* @author Julius Naeumann
*/
public class VirtualEdgesSummaries {
public static final int BASE_INDEX = -1;
private static final String SUMMARIESFILE = "virtualedges.xml";
protected final HashMap<MethodSubSignature, VirtualEdge> instanceinvokeEdges = new LinkedHashMap<>();
protected final HashMap<String, VirtualEdge> staticinvokeEdges = new LinkedHashMap<>();
private static final Logger logger = LoggerFactory.getLogger(VirtualEdgesSummaries.class);
/**
* Creates a default instance of the {@link VirtualEdgesSummaries} and loads the summaries from the
* <code>virtualedges.xml</code> that comes with Soot.
*/
public VirtualEdgesSummaries() {
Path summariesFile = Paths.get(SUMMARIESFILE);
try (InputStream in = Files.exists(summariesFile) ? Files.newInputStream(summariesFile)
: ModuleUtil.class.getResourceAsStream("/" + SUMMARIESFILE)) {
if (in == null) {
logger.error("Virtual edge summaries file not found");
} else {
loadSummaries(in);
}
} catch (IOException | ParserConfigurationException | SAXException e1) {
logger.error("An error occurred while reading in virtual edge summaries", e1);
}
}
/**
* Creates a new instance of the {@link VirtualEdgesSummaries} class and loads the summaries from the given input file
*
* @param summariesFile
* The file from which to load the virtual edge summaries
*/
public VirtualEdgesSummaries(File summariesFile) {
try (InputStream in = new FileInputStream(summariesFile)) {
loadSummaries(in);
} catch (IOException | ParserConfigurationException | SAXException e1) {
logger.error("An error occurred while reading in virtual edge summaries", e1);
}
}
/**
* Loads the edge summaries from the given stream
*
* @param in
* The {@link InputStream} from which to load the summaries
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
protected void loadSummaries(InputStream in) throws SAXException, IOException, ParserConfigurationException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
doc.getDocumentElement().normalize();
NodeList edges = doc.getElementsByTagName("edge");
for (int i = 0, e = edges.getLength(); i < e; i++) {
if (edges.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element edge = (Element) edges.item(i);
VirtualEdge edg = new VirtualEdge();
switch (edge.getAttribute("type")) {
case "THREAD":
edg.edgeType = Kind.THREAD;
break;
case "EXECUTOR":
edg.edgeType = Kind.EXECUTOR;
break;
case "HANDLER":
edg.edgeType = Kind.HANDLER;
break;
case "ASYNCTASK":
edg.edgeType = Kind.ASYNCTASK;
break;
case "PRIVILEGED":
edg.edgeType = Kind.PRIVILEGED;
break;
case "GENERIC_FAKE":
default:
edg.edgeType = Kind.GENERIC_FAKE;
break;
}
edg.source = parseEdgeSource((Element) (edge.getElementsByTagName("source").item(0)));
edg.targets = new HashSet<VirtualEdgeTarget>();
Element targetsElement = (Element) edge.getElementsByTagName("targets").item(0);
edg.targets.addAll(parseEdgeTargets(targetsElement));
if (edg.source instanceof InstanceinvokeSource) {
InstanceinvokeSource inst = (InstanceinvokeSource) edg.source;
MethodSubSignature subsig = inst.subSignature;
// don't overwrite existing definition
addInstanceInvoke(edg, subsig);
}
if (edg.source instanceof StaticinvokeSource) {
StaticinvokeSource stat = (StaticinvokeSource) edg.source;
staticinvokeEdges.put(stat.signature, edg);
}
}
}
logger.debug("Found {} instanceinvoke, {} staticinvoke edge descriptions", instanceinvokeEdges.size(),
staticinvokeEdges.size());
}
protected void addInstanceInvoke(VirtualEdge edg, MethodSubSignature subsig) {
VirtualEdge existing = instanceinvokeEdges.get(subsig);
if (existing != null) {
existing.targets.addAll(edg.targets);
} else {
instanceinvokeEdges.put(subsig, edg);
}
}
public VirtualEdgesSummaries(Collection<VirtualEdge> edges) {
for (VirtualEdge vi : edges) {
if (vi.source instanceof InstanceinvokeSource) {
InstanceinvokeSource inst = (InstanceinvokeSource) vi.source;
addInstanceInvoke(vi, inst.subSignature);
} else if (vi.source instanceof StaticinvokeSource) {
StaticinvokeSource stat = (StaticinvokeSource) vi.source;
staticinvokeEdges.put(stat.signature, vi);
}
}
}
public Document toXMLDocument() throws ParserConfigurationException {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element root = document.createElement("virtualedges");
document.appendChild(root);
for (VirtualEdge edge : Iterables.concat(instanceinvokeEdges.values(), staticinvokeEdges.values())) {
Node e = edgeToXML(document, edge);
root.appendChild(e);
}
return document;
}
private static Element edgeToXML(Document doc, VirtualEdge edge) {
Element node = doc.createElement("edge");
node.setAttribute("type", edge.edgeType.name());
Element source = doc.createElement("source");
node.appendChild(source);
if (edge.source instanceof StaticinvokeSource) {
StaticinvokeSource inv = (StaticinvokeSource) edge.source;
source.setAttribute("invoketype", "static");
source.setAttribute("signature", inv.signature);
} else if (edge.source instanceof InstanceinvokeSource) {
InstanceinvokeSource inv = (InstanceinvokeSource) edge.source;
source.setAttribute("invoketype", "instance");
source.setAttribute("subsignature", inv.subSignature.toString());
} else {
if (edge.source == null) {
throw new IllegalArgumentException("Unsupported null source type");
} else {
throw new IllegalArgumentException("Unsupported source type " + edge.source.getClass());
}
}
Element targets = doc.createElement("targets");
node.appendChild(targets);
for (VirtualEdgeTarget e : edge.targets) {
Element target = edgeTargetToXML(doc, e);
targets.appendChild(target);
}
return node;
}
private static Element edgeTargetToXML(Document doc, VirtualEdgeTarget e) {
Element target;
if (e instanceof DirectTarget) {
target = doc.createElement("direct");
} else if (e instanceof IndirectTarget) {
target = doc.createElement("indirect");
IndirectTarget id = (IndirectTarget) e;
for (VirtualEdgeTarget i : id.targets) {
target.appendChild(edgeTargetToXML(doc, i));
}
} else {
if (e == null) {
throw new IllegalArgumentException("Unsupported null edge type");
} else {
throw new IllegalArgumentException("Unsupported source type " + e.getClass());
}
}
target.setAttribute("subsignature", e.targetMethod.toString());
if (e.isBase()) {
target.setAttribute("target-position", "base");
} else {
target.setAttribute("index", String.valueOf(e.argIndex));
target.setAttribute("target-position", "argument");
}
return target;
}
public VirtualEdge getVirtualEdgesMatchingSubSig(MethodSubSignature subsig) {
return instanceinvokeEdges.get(subsig);
}
public VirtualEdge getVirtualEdgesMatchingFunction(String signature) {
return staticinvokeEdges.get(signature);
}
private static VirtualEdgeSource parseEdgeSource(Element source) {
switch (source.getAttribute("invoketype")) {
case "instance":
return new InstanceinvokeSource(source.getAttribute("subsignature"));
case "static":
return new StaticinvokeSource(source.getAttribute("signature"));
default:
return null;
}
}
private static List<VirtualEdgeTarget> parseEdgeTargets(Element targetsElement) {
List<VirtualEdgeTarget> targets = new ArrayList<>();
final StringNumberer nmbr = Scene.v().getSubSigNumberer();
NodeList children = targetsElement.getChildNodes();
for (int i = 0, e = children.getLength(); i < e; i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element targetElement = (Element) children.item(i);
switch (targetElement.getTagName()) {
case "direct": {
MethodSubSignature subsignature
= new MethodSubSignature(nmbr.findOrAdd(targetElement.getAttribute("subsignature")));
String tpos = targetElement.getAttribute("target-position");
switch (tpos) {
case "argument":
int argIdx = Integer.valueOf(targetElement.getAttribute("index"));
targets.add(new DirectTarget(subsignature, argIdx));
break;
case "base":
targets.add(new DirectTarget(subsignature));
break;
default:
throw new IllegalArgumentException("Unsupported target position " + tpos);
}
break;
}
case "indirect": {
// Parse the attributes of the current target
IndirectTarget target;
MethodSubSignature subsignature
= new MethodSubSignature(nmbr.findOrAdd(targetElement.getAttribute("subsignature")));
String tpos = targetElement.getAttribute("target-position");
switch (tpos) {
case "argument":
int argIdx = Integer.valueOf(targetElement.getAttribute("index"));
target = new IndirectTarget(subsignature, argIdx);
break;
case "base":
target = new IndirectTarget(subsignature);
break;
default:
throw new IllegalArgumentException("Unsupported target position " + tpos);
}
targets.add(target);
// Parse child targets, since we have a chain of target methods to track back to the point where the actual
// callback
// was originally registered
target.addTargets(parseEdgeTargets(targetElement));
targets.add(target);
break;
}
}
}
}
return targets;
}
public static abstract class VirtualEdgeSource {
}
public static class StaticinvokeSource extends VirtualEdgeSource {
/**
* The method signature at which to insert this edge.
*/
String signature;
public StaticinvokeSource(String signature) {
this.signature = signature;
}
public String getSignature() {
return signature;
}
@Override
public String toString() {
return signature;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((signature == null) ? 0 : signature.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
StaticinvokeSource other = (StaticinvokeSource) obj;
if (signature == null) {
if (other.signature != null) {
return false;
}
} else if (!signature.equals(other.signature)) {
return false;
}
return true;
}
}
public static class InstanceinvokeSource extends VirtualEdgeSource {
/**
* The method subsignature at which to insert this edge.
*/
MethodSubSignature subSignature;
/**
* Creates a new instance of the {@link InstanceinvokeSource} class based on a method that is being invoked on the
* current object instance
*
* @param subSignature
* The subsignature of the method that is invoked
*/
public InstanceinvokeSource(String subSignature) {
this.subSignature = new MethodSubSignature(Scene.v().getSubSigNumberer().findOrAdd(subSignature));
}
/**
* Convenience constructor that extracts the subsignature of the callee from a call site statement
*
* @param invokeStmt
* The statement at the call site
*/
public InstanceinvokeSource(Stmt invokeStmt) {
this(invokeStmt.getInvokeExpr().getMethodRef().getSubSignature().getString());
}
@Override
public String toString() {
return subSignature.toString();
}
public MethodSubSignature getSubSignature() {
return subSignature;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((subSignature == null) ? 0 : subSignature.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
InstanceinvokeSource other = (InstanceinvokeSource) obj;
if (subSignature == null) {
if (other.subSignature != null) {
return false;
}
} else if (!subSignature.equals(other.subSignature)) {
return false;
}
return true;
}
}
public static abstract class VirtualEdgeTarget {
protected int argIndex;
protected MethodSubSignature targetMethod;
VirtualEdgeTarget() {
// internal use only
}
public VirtualEdgeTarget(MethodSubSignature targetMethod) {
this.argIndex = BASE_INDEX;
this.targetMethod = targetMethod;
}
public VirtualEdgeTarget(MethodSubSignature targetMethod, int argIndex) {
this.argIndex = argIndex;
this.targetMethod = targetMethod;
}
@Override
public String toString() {
return isBase() ? "base" : String.format("argument %d", argIndex);
}
public boolean isBase() {
return argIndex == BASE_INDEX;
}
public int getArgIndex() {
return argIndex;
}
public MethodSubSignature getTargetMethod() {
return targetMethod;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + argIndex;
result = prime * result + ((targetMethod == null) ? 0 : targetMethod.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VirtualEdgeTarget other = (VirtualEdgeTarget) obj;
if (argIndex != other.argIndex) {
return false;
}
if (targetMethod == null) {
if (other.targetMethod != null) {
return false;
}
} else if (!targetMethod.equals(other.targetMethod)) {
return false;
}
return true;
}
}
public static class DirectTarget extends VirtualEdgeTarget {
DirectTarget() {
// internal use only
}
/**
* Creates a new direct method invocation on an object passed to the original source as an argument. For example,
* <code>foo.do(x)></code> could invoke <code>x.bar()</code> as a callback.
*
* @param targetMethod
* The target method that is invoked on the argument object
* @param argIndex
* The index of the argument that receives the target object
*/
public DirectTarget(MethodSubSignature targetMethod, int argIndex) {
super(targetMethod, argIndex);
}
/**
* Creates a new direct method invocation on the base object of the original source. For example, <code>foo.do()></code>
* could invoke <code>foo.bar()</code> as a callback.
*
* @param targetMethod
* The target method that is invoked on the base object
*/
public DirectTarget(MethodSubSignature targetMethod) {
super(targetMethod);
}
@Override
public String toString() {
return String.format("Direct to %s on %s", targetMethod.toString(), super.toString());
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return true;
}
}
public static class IndirectTarget extends VirtualEdgeTarget {
List<VirtualEdgeTarget> targets = new ArrayList<>();
IndirectTarget() {
// internal use only
}
/**
* Creates a new direct method invocation. The signature of this indirect target references a method that was called
* earlier, and which received the object on which the callback is invoked. This constructor assumes that the earlier
* method has created an object which is passed the current method as an argument.
*
* @param targetMethod
* The method with which the original callback was registered
* @param argIndex
* The index of the argument that holds the object that holds the callback or next step of the indirect
* invocation
*/
public IndirectTarget(MethodSubSignature targetMethod, int argIndex) {
super(targetMethod, argIndex);
}
/**
* Creates a new indirect target as an indirection from a method that was previously considered a source
*
* @param source
* The source from which to create the indirect target
*/
public IndirectTarget(InstanceinvokeSource source) {
super(source.subSignature);
}
/**
* Creates a new direct method invocation. The signature of this indirect target references a method that was called
* earlier, and which received the object on which the callback is invoked.
*
* @param targetMethod
* The method with which the original callback was registered
*/
public IndirectTarget(MethodSubSignature targetMethod) {
super(targetMethod);
}
public void addTarget(VirtualEdgeTarget target) {
if (!targets.contains(target)) {
targets.add(target);
}
}
public void addTargets(Collection<? extends VirtualEdgeTarget> targets) {
for (VirtualEdgeTarget target : targets) {
addTarget(target);
}
}
public List<VirtualEdgeTarget> getTargets() {
return targets;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (VirtualEdgeTarget t : targets) {
sb.append('(').append(t.toString()).append(") ");
}
return String.format("(Instances passed to <?: %s> on %s => %s)", targetMethod.toString(), super.toString(),
sb.toString());
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((targets == null) ? 0 : targets.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
IndirectTarget other = (IndirectTarget) obj;
if (targets == null) {
if (other.targets != null) {
return false;
}
} else if (!targets.equals(other.targets)) {
return false;
}
return true;
}
}
public static class VirtualEdge {
/**
* The kind of edge to insert
*/
Kind edgeType;
VirtualEdgeSource source;
Set<VirtualEdgeTarget> targets;
VirtualEdge() {
// internal use only
}
public VirtualEdge(Kind edgeType, VirtualEdgeSource source, VirtualEdgeTarget target) {
this(edgeType, source, new ArrayList<>(Collections.singletonList(target)));
}
public VirtualEdge(Kind edgeType, VirtualEdgeSource source, Collection<VirtualEdgeTarget> targets) {
this.edgeType = edgeType;
this.source = source;
this.targets = new HashSet<>(targets);
}
public Kind getEdgeType() {
return edgeType;
}
public VirtualEdgeSource getSource() {
return source;
}
public Set<VirtualEdgeTarget> getTargets() {
return targets;
}
/**
* Adds the given targets to this edge summary
*
* @param newTargets
* The targets to add
*/
public void addTargets(Collection<VirtualEdgeTarget> newTargets) {
this.targets.addAll(newTargets);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (VirtualEdgeTarget t : targets) {
sb.append(t.toString()).append(' ');
}
return String.format("%s %s => %s", edgeType, source.toString(), sb.toString());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((edgeType == null) ? 0 : edgeType.hashCode());
result = prime * result + ((source == null) ? 0 : source.hashCode());
result = prime * result + ((targets == null) ? 0 : targets.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
VirtualEdge other = (VirtualEdge) obj;
if (edgeType == null) {
if (other.edgeType != null) {
return false;
}
} else if (!edgeType.equals(other.edgeType)) {
return false;
}
if (source == null) {
if (other.source != null) {
return false;
}
} else if (!source.equals(other.source)) {
return false;
}
if (targets == null) {
if (other.targets != null) {
return false;
}
} else if (!targets.equals(other.targets)) {
return false;
}
return true;
}
}
public boolean isEmpty() {
return instanceinvokeEdges.isEmpty() && staticinvokeEdges.isEmpty();
}
public Set<VirtualEdge> getAllVirtualEdges() {
Set<VirtualEdge> allEdges = new HashSet<>(instanceinvokeEdges.size() + staticinvokeEdges.size());
allEdges.addAll(instanceinvokeEdges.values());
allEdges.addAll(staticinvokeEdges.values());
return allEdges;
}
}
| 24,978
| 29.686732
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/graph/CriticalEdgeRemover.java
|
package soot.jimple.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.G;
import soot.Singletons;
import soot.Unit;
import soot.UnitBox;
import soot.jimple.Jimple;
import soot.options.Options;
import soot.util.Chain;
/**
* removes all critical edges.<br>
* A critical edge is an edge from Block A to block B, if B has more than one predecessor and A has more the one successor.
* <br>
* As an example: If we wanted a computation to be only on the path A->B this computation must be directly on the edge.
* Otherwise it is either executed on the path through the second predecessor of A or throught the second successor of B.<br>
* Our critical edge-remover overcomes this problem by introducing synthetic nodes on this critical edges.<br>
* Exceptions will be ignored.
*/
public 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) {
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);
}
}
}
}
}
}
}
| 8,203
| 38.066667
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/graph/LoopConditionUnroller.java
|
package soot.jimple.toolkits.graph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Florian Loitsch
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.BodyTransformer;
import soot.PhaseOptions;
import soot.Trap;
import soot.Unit;
import soot.jimple.GotoStmt;
import soot.jimple.IfStmt;
import soot.jimple.Jimple;
import soot.options.Options;
import soot.toolkits.graph.Block;
import soot.toolkits.graph.BlockGraph;
import soot.toolkits.graph.BriefBlockGraph;
import soot.util.Chain;
/**
* "unrolls" the condition of while/for loops.<br>
* before the first test of a while-loop, we can't be sure, if the body will be taken or not, and several optimizations
* (especially LCM) can't be done. In this class we try to solve this problem by unrolling the condition of the while-block:
* we make a copy of the condition-block, and redirect the back-edge of the while-loop to the new block.<br>
* After this transformation the edge between the original condition-block and the loop-body is only executed once (and hence
* suitable for LCM) and we can be sure, that the loop-body will get executed.<br>
* Exceptions are ignored (the transformation is done on a <code>BriefBlockGraph</code>.
*/
public class LoopConditionUnroller extends BodyTransformer {
private static final Logger logger = LoggerFactory.getLogger(LoopConditionUnroller.class);
/**
* contained blocks are currently visiting successors. We need this to find back-edges. The "visitedBlocks" is not enough,
* as Java Bytecodes might not be in tree-form.
*/
private Set<Block> visitingSuccs;
private Set<Block> visitedBlocks;
private int maxSize;
private Chain<Unit> unitChain;
private Chain<Trap> trapChain;
private Map<Unit, List<Trap>> unitsToTraps;
/**
* unrolls conditions.
*/
/*
* this implementation still fails in finding all possible while-loops, but does a good job.
*/
@Override
protected void internalTransform(Body body, String phaseName, Map<String, String> options) {
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Unrolling Loop Conditions...");
}
this.visitingSuccs = new HashSet<Block>();
this.visitedBlocks = new HashSet<Block>();
this.maxSize = PhaseOptions.getInt(options, "maxSize");
this.unitChain = body.getUnits();
this.trapChain = body.getTraps();
this.unitsToTraps = mapBeginEndUnitToTrap(trapChain);
BlockGraph bg = new BriefBlockGraph(body);
for (Block b : bg.getHeads()) {
unrollConditions(b);
}
if (Options.v().verbose()) {
logger.debug("[" + body.getMethod().getName() + "] Unrolling Loop Conditions done.");
}
}
/**
* inserts a Jimple<code>Goto</code> to <code> target, directly after
* <code>node</code> in the <code>unitChain</code> of the body.<br>
* As we use <code>JGoto</code> the chain must contain Jimple-stmts.
*
* @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 Unit insertGotoAfter(Unit node, Unit target) {
Unit newGoto = Jimple.v().newGotoStmt(target);
unitChain.insertAfter(newGoto, node);
return newGoto;
}
/**
* inserts a clone of <code>toClone</code> after <code>node</code> in the <code>unitChain</code>.<br>
* Everything is done in Jimple.
*
* @param node
* the Unit after which we insert the clone.
* @param toClone
* the Unit that will get cloned and then inserted.
*/
private Unit insertCloneAfter(Unit node, Unit toClone) {
Unit clone = (Unit) toClone.clone();
unitChain.insertAfter(clone, node);
return clone;
}
/**
* "calculates" the length of the given block in Units.
*
* @param block
* @return the size of <code>block</code>.
*/
private int getSize(Block block) {
int size = 1; // add 1 for the tail not counted by the loop below
Chain<Unit> chain = this.unitChain;
for (Unit unit = block.getHead(), e = block.getTail(); unit != e; unit = chain.getSuccOf(unit)) {
size++;
}
return size;
}
/**
* returns a mapping of units to trap-changes. whenever the scope of a trap changes (ie. a trap opens or closes), an entry
* is added in the map, and the unit is mapped to the trap. The values associated to the keys are lists, as more than one
* exception can change at a unit.<br>
* Even if a trap opens and closes at a unit, this trap is only reported once (ie. is only once in the list).
*
* @return the map of units to changing traps.
*/
private static Map<Unit, List<Trap>> mapBeginEndUnitToTrap(Chain<Trap> trapChain) {
Map<Unit, List<Trap>> unitsToTraps = new HashMap<Unit, List<Trap>>();
for (Trap trap : trapChain) {
Unit beginUnit = trap.getBeginUnit();
{
List<Trap> unitTraps = unitsToTraps.get(beginUnit);
if (unitTraps == null) {
unitTraps = new ArrayList<Trap>();
unitsToTraps.put(beginUnit, unitTraps);
}
unitTraps.add(trap);
}
Unit endUnit = trap.getEndUnit();
if (endUnit != beginUnit) {
List<Trap> unitTraps = unitsToTraps.get(endUnit);
if (unitTraps == null) {
unitTraps = new ArrayList<Trap>();
unitsToTraps.put(endUnit, unitTraps);
}
unitTraps.add(trap);
}
}
return unitsToTraps;
}
/**
* puts a copy (clone) of the given block in the unitChain. The block is ensured to have the same exceptions as the
* original block. (So we will modify the exception-chain). Furthermore the inserted block will not change the behaviour of
* the program.<br>
* Without any further modifications the returned block is unreachable. To make it reachable one must <code>goto</code> to
* the returned head of the new block.
*
* @param block
* the Block to clone.
* @return the head of the copied block.
*/
private Unit copyBlock(Block block) {
final Set<Trap> openedTraps = new HashSet<Trap>();
final Map<Trap, Trap> copiedTraps = new HashMap<Trap, Trap>();
final Chain<Unit> chain = this.unitChain;
final Unit tail = block.getTail();
final Unit newGoto = insertGotoAfter(tail, chain.getSuccOf(tail));
Unit last = newGoto; // the last inserted unit
Unit copiedHead = null;
for (Unit curr = block.getHead(); curr != newGoto; curr = chain.getSuccOf(curr)) {
last = insertCloneAfter(last, curr);
if (copiedHead == null) {
copiedHead = last;
assert (copiedHead != null);
}
/*
* the traps...: if a trap is closed (in the original block) that hasn't been opened before, we have to open it at the
* beginning of the copied block. If a trap gets opened, but not closed, we only have to close it at the end of the
* (original) block (as it will be open at the end of the copied block.)
*/
List<Trap> currentTraps = unitsToTraps.get(curr);
if (currentTraps != null) {
for (Trap trap : currentTraps) {
if (trap.getBeginUnit() == curr) {
Trap copiedTrap = (Trap) trap.clone();
copiedTrap.setBeginUnit(last);
copiedTraps.put(trap, copiedTrap);
openedTraps.add(copiedTrap);
trapChain.insertAfter(copiedTrap, trap);
}
if (trap.getEndUnit() == curr) {
Trap copiedTrap = copiedTraps.get(trap);
if (copiedTrap == null) {
/* trap has been opened before the current block */
copiedTrap = (Trap) trap.clone();
copiedTrap.setBeginUnit(copiedHead);
trapChain.insertAfter(copiedTrap, trap);
} else {
openedTraps.remove(copiedTrap);
}
copiedTrap.setEndUnit(last);
}
}
}
}
/* close all open traps */
for (Trap t : openedTraps) {
t.setEndUnit(last);
}
return copiedHead;
}
/**
* recursively searches for back-edges. if the found block is a condition-block makes a clone and redirects the back-edge.
*
* @param block
* the current Block.
*/
private void unrollConditions(Block block) {
/* if the block was already visited we can leave... */
if (visitedBlocks.contains(block)) {
return; // should never happen
}
visitedBlocks.add(block);
visitingSuccs.add(block); // currently visiting successors
for (Block succ : block.getSuccs()) {
if (visitedBlocks.contains(succ)) {
if (succ != block && visitingSuccs.contains(succ)) {
/*
* we only want blocks with at least 2 predecessors, to avoid that a copied while-condition gets copied again in a
* future pass of unrollConditions
*/
if (succ.getPreds().size() >= 2 && succ.getSuccs().size() == 2) {
Block condition = succ; // just renaming for clearer code
Block loopTailBlock = block; // just renaming for clearer code
if (getSize(condition) <= maxSize) {
Unit copiedHead = copyBlock(condition);
/* now just redirect the tail of the loop-body */
Unit loopTail = loopTailBlock.getTail();
if (loopTail instanceof GotoStmt) {
((GotoStmt) loopTail).setTarget(copiedHead);
} else if (loopTail instanceof IfStmt) {
IfStmt tailIf = (IfStmt) loopTail;
if (tailIf.getTarget() == condition.getHead()) {
tailIf.setTarget(copiedHead);
} else {
insertGotoAfter(loopTail, copiedHead);
}
} else {
insertGotoAfter(loopTail, copiedHead);
}
}
}
}
} else {
/* unvisited successor */
unrollConditions(succ);
}
}
visitingSuccs.remove(block);
}
}
| 10,958
| 35.652174
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/DefaultJimpleIDETabulationProblem.java
|
package soot.jimple.toolkits.ide;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.InterproceduralCFG;
import heros.template.DefaultIDETabulationProblem;
import soot.SootMethod;
import soot.Unit;
/**
* A {@link DefaultIDETabulationProblem} with {@link Unit}s as nodes and {@link SootMethod}s as methods.
*/
public abstract class DefaultJimpleIDETabulationProblem<D, V, I extends InterproceduralCFG<Unit, SootMethod>>
extends DefaultIDETabulationProblem<Unit, D, SootMethod, V, I> {
public DefaultJimpleIDETabulationProblem(I icfg) {
super(icfg);
}
}
| 1,347
| 31.095238
| 109
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/DefaultJimpleIFDSTabulationProblem.java
|
package soot.jimple.toolkits.ide;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.InterproceduralCFG;
import heros.template.DefaultIDETabulationProblem;
import heros.template.DefaultIFDSTabulationProblem;
import soot.SootMethod;
import soot.Unit;
/**
* A {@link DefaultIDETabulationProblem} with {@link Unit}s as nodes and {@link SootMethod}s as methods.
*/
public abstract class DefaultJimpleIFDSTabulationProblem<D, I extends InterproceduralCFG<Unit, SootMethod>>
extends DefaultIFDSTabulationProblem<Unit, D, SootMethod, I> {
public DefaultJimpleIFDSTabulationProblem(I icfg) {
super(icfg);
}
}
| 1,396
| 31.488372
| 107
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/JimpleIDESolver.java
|
package soot.jimple.toolkits.ide;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.collect.Table.Cell;
import heros.IDETabulationProblem;
import heros.InterproceduralCFG;
import heros.solver.IDESolver;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.PatchingChain;
import soot.SootMethod;
import soot.Unit;
public 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() {
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);
}
}
}
| 2,880
| 28.701031
| 117
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/JimpleIFDSSolver.java
|
package soot.jimple.toolkits.ide;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.collect.Table.Cell;
import heros.IFDSTabulationProblem;
import heros.InterproceduralCFG;
import heros.solver.IFDSSolver;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.PatchingChain;
import soot.SootMethod;
import soot.Unit;
public 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() {
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);
}
}
}
| 3,017
| 29.795918
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/Main.java
|
package soot.jimple.toolkits.ide;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.IFDSTabulationProblem;
import heros.InterproceduralCFG;
import java.util.Map;
import soot.PackManager;
import soot.SceneTransformer;
import soot.SootMethod;
import soot.Transform;
import soot.Unit;
import soot.jimple.toolkits.ide.exampleproblems.IFDSPossibleTypes;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
PackManager.v().getPack("wjtp").add(new Transform("wjtp.ifds", new SceneTransformer() {
protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
IFDSTabulationProblem<Unit, ?, SootMethod, InterproceduralCFG<Unit, SootMethod>> problem
= new IFDSPossibleTypes(new JimpleBasedInterproceduralCFG());
@SuppressWarnings({ "rawtypes", "unchecked" })
JimpleIFDSSolver<?, InterproceduralCFG<Unit, SootMethod>> solver = new JimpleIFDSSolver(problem);
solver.solve();
}
}));
soot.Main.main(args);
}
}
| 1,895
| 30.081967
| 105
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/SortableCSVString.java
|
package soot.jimple.toolkits.ide;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Christian Fritz and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
public class SortableCSVString implements Comparable<SortableCSVString> {
String value;
int position;
public SortableCSVString(String str, int pos) {
value = str;
position = pos;
}
public int compareTo(SortableCSVString anotherString) {
// "@"+i+";
int result;
String subString = value.substring(0, value.indexOf(';'));
String anotherSubString = anotherString.value.substring(0, anotherString.value.indexOf(';'));
result = subString.compareTo(anotherSubString);
if (result == 0) {
if (position < anotherString.position) {
return -1;
}
if (position > anotherString.position) {
return 1;
}
return 0;
} else {
return result;
}
}
}
| 1,588
| 28.425926
| 97
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSLiveVariables.java
|
package soot.jimple.toolkits.ide.exampleproblems;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.DefaultSeeds;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Local;
import soot.NullType;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.InvokeExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
public 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) {
// 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);
}
};
}
};
}
public Map<Unit, Set<Value>> initialSeeds() {
return DefaultSeeds.make(interproceduralCFG().getStartPointsOf(Scene.v().getMainMethod()), zeroValue());
}
public Value createZeroValue() {
return new JimpleLocal("<<zero>>", NullType.v());
}
}
| 6,541
| 32.377551
| 121
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSLocalInfoFlow.java
|
package soot.jimple.toolkits.ide.exampleproblems;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.DefaultSeeds;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Gen;
import heros.flowfunc.Identity;
import heros.flowfunc.Kill;
import heros.flowfunc.KillAll;
import heros.flowfunc.Transfer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Local;
import soot.NullType;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.AssignStmt;
import soot.jimple.DefinitionStmt;
import soot.jimple.IdentityStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.ParameterRef;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
public class IFDSLocalInfoFlow extends DefaultJimpleIFDSTabulationProblem<Local, InterproceduralCFG<Unit, SootMethod>> {
public IFDSLocalInfoFlow(InterproceduralCFG<Unit, SootMethod> icfg) {
super(icfg);
}
public FlowFunctions<Unit, Local, SootMethod> createFlowFunctionsFactory() {
return new FlowFunctions<Unit, Local, SootMethod>() {
@Override
public FlowFunction<Local> getNormalFlowFunction(Unit src, Unit dest) {
if (src instanceof IdentityStmt && interproceduralCFG().getMethodOf(src) == Scene.v().getMainMethod()) {
IdentityStmt is = (IdentityStmt) src;
Local leftLocal = (Local) is.getLeftOp();
Value right = is.getRightOp();
if (right instanceof ParameterRef) {
return new Gen<Local>(leftLocal, zeroValue());
}
}
if (src instanceof AssignStmt) {
AssignStmt assignStmt = (AssignStmt) src;
Value right = assignStmt.getRightOp();
if (assignStmt.getLeftOp() instanceof Local) {
final Local leftLocal = (Local) assignStmt.getLeftOp();
if (right instanceof Local) {
final Local rightLocal = (Local) right;
return new Transfer<Local>(leftLocal, rightLocal);
} else {
return new Kill<Local>(leftLocal);
}
}
}
return Identity.v();
}
@Override
public FlowFunction<Local> getCallFlowFunction(Unit src, final SootMethod dest) {
Stmt s = (Stmt) src;
InvokeExpr ie = s.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<Local>() {
public Set<Local> computeTargets(Local source) {
// ignore implicit calls to static initializers
if (dest.getName().equals(SootMethod.staticInitializerName) && dest.getParameterCount() == 0) {
return Collections.emptySet();
}
Set<Local> taintsInCaller = new HashSet<Local>();
for (int i = 0; i < callArgs.size(); i++) {
if (callArgs.get(i).equivTo(source)) {
taintsInCaller.add(paramLocals.get(i));
}
}
return taintsInCaller;
}
};
}
@Override
public FlowFunction<Local> 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<Local>() {
public Set<Local> computeTargets(Local source) {
if (source == retLocal) {
return Collections.singleton(tgtLocal);
}
return Collections.emptySet();
}
};
}
}
}
}
return KillAll.v();
}
@Override
public FlowFunction<Local> getCallToReturnFlowFunction(Unit call, Unit returnSite) {
return Identity.v();
}
};
}
@Override
public Local createZeroValue() {
return new JimpleLocal("zero", NullType.v());
}
@Override
public Map<Unit, Set<Local>> initialSeeds() {
return DefaultSeeds.make(Collections.singleton(Scene.v().getMainMethod().getActiveBody().getUnits().getFirst()),
zeroValue());
}
}
| 5,754
| 33.255952
| 120
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSPossibleTypes.java
|
package soot.jimple.toolkits.ide.exampleproblems;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.DefaultSeeds;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import heros.flowfunc.KillAll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Local;
import soot.PointsToAnalysis;
import soot.PointsToSet;
import soot.PrimType;
import soot.Scene;
import soot.SootMethod;
import soot.Type;
import soot.Unit;
import soot.UnknownType;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.Constant;
import soot.jimple.DefinitionStmt;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.NewExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
import soot.toolkits.scalar.Pair;
@SuppressWarnings("serial")
public 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() {
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 == 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();
}
};
}
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());
}
}
| 8,855
| 38.713004
| 116
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSReachingDefinitions.java
|
package soot.jimple.toolkits.ide.exampleproblems;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.DefaultSeeds;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import heros.flowfunc.KillAll;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.EquivalentValue;
import soot.Local;
import soot.NullType;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.DefinitionStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.Jimple;
import soot.jimple.ReturnStmt;
import soot.jimple.ReturnVoidStmt;
import soot.jimple.Stmt;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
import soot.toolkits.scalar.Pair;
public 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) {
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();
}
};
}
@Override
public FlowFunction<Pair<Value, Set<DefinitionStmt>>> getReturnFlowFunction(final Unit callSite,
SootMethod calleeMethod, final Unit exitStmt, Unit returnSite) {
if (!(callSite instanceof DefinitionStmt)) {
return KillAll.v();
}
if (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());
}
}
| 7,085
| 36.099476
| 124
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/exampleproblems/IFDSUninitializedVariables.java
|
package soot.jimple.toolkits.ide.exampleproblems;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import heros.DefaultSeeds;
import heros.FlowFunction;
import heros.FlowFunctions;
import heros.InterproceduralCFG;
import heros.flowfunc.Identity;
import heros.flowfunc.Kill;
import heros.flowfunc.KillAll;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Local;
import soot.NullType;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.ValueBox;
import soot.jimple.DefinitionStmt;
import soot.jimple.InvokeExpr;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.internal.JimpleLocal;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
public class IFDSUninitializedVariables
extends DefaultJimpleIFDSTabulationProblem<Local, InterproceduralCFG<Unit, SootMethod>> {
public IFDSUninitializedVariables(InterproceduralCFG<Unit, SootMethod> icfg) {
super(icfg);
}
@Override
public FlowFunctions<Unit, Local, SootMethod> createFlowFunctionsFactory() {
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();
}
};
}
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());
}
}
| 7,979
| 33.396552
| 125
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/icfg/AbstractJimpleBasedICFG.java
|
package soot.jimple.toolkits.ide.icfg;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2018 Raja Vallée-Rai and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import heros.DontSynchronize;
import heros.SynchronizedBy;
import heros.solver.IDESolver;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.Body;
import soot.PatchingChain;
import soot.SootMethod;
import soot.Unit;
import soot.UnitBox;
import soot.Value;
import soot.jimple.Stmt;
import soot.toolkits.graph.BriefUnitGraph;
import soot.toolkits.graph.DirectedGraph;
import soot.toolkits.graph.ExceptionalUnitGraphFactory;
public abstract class AbstractJimpleBasedICFG implements BiDiInterproceduralCFG<Unit, SootMethod> {
protected final boolean enableExceptions;
@DontSynchronize("written by single thread; read afterwards")
private final Map<Unit, Body> unitToOwner = createUnitToOwnerMap();
@SynchronizedBy("by use of synchronized LoadingCache class")
protected LoadingCache<Body, DirectedGraph<Unit>> bodyToUnitGraph
= IDESolver.DEFAULT_CACHE_BUILDER.build(new CacheLoader<Body, DirectedGraph<Unit>>() {
@Override
public DirectedGraph<Unit> load(Body body) throws Exception {
return makeGraph(body);
}
});
@SynchronizedBy("by use of synchronized LoadingCache class")
protected LoadingCache<SootMethod, List<Value>> methodToParameterRefs
= IDESolver.DEFAULT_CACHE_BUILDER.build(new CacheLoader<SootMethod, List<Value>>() {
@Override
public List<Value> load(SootMethod m) throws Exception {
return m.getActiveBody().getParameterRefs();
}
});
@SynchronizedBy("by use of synchronized LoadingCache class")
protected LoadingCache<SootMethod, Set<Unit>> methodToCallsFromWithin
= IDESolver.DEFAULT_CACHE_BUILDER.build(new CacheLoader<SootMethod, Set<Unit>>() {
@Override
public Set<Unit> load(SootMethod m) throws Exception {
return getCallsFromWithinMethod(m);
}
});
public AbstractJimpleBasedICFG() {
this(true);
}
protected Map<Unit, Body> createUnitToOwnerMap() {
return new LinkedHashMap<Unit, Body>();
}
public AbstractJimpleBasedICFG(boolean enableExceptions) {
this.enableExceptions = enableExceptions;
}
public Body getBodyOf(Unit u) {
assert unitToOwner.containsKey(u) : "Statement " + u + " not in unit-to-owner mapping";
Body b = unitToOwner.get(u);
return b;
}
@Override
public SootMethod getMethodOf(Unit u) {
Body b = getBodyOf(u);
return b == null ? null : b.getMethod();
}
@Override
public List<Unit> getSuccsOf(Unit u) {
Body body = getBodyOf(u);
if (body == null) {
return Collections.emptyList();
}
DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body);
return unitGraph.getSuccsOf(u);
}
@Override
public DirectedGraph<Unit> getOrCreateUnitGraph(SootMethod m) {
return getOrCreateUnitGraph(m.getActiveBody());
}
public DirectedGraph<Unit> getOrCreateUnitGraph(Body body) {
return bodyToUnitGraph.getUnchecked(body);
}
protected DirectedGraph<Unit> makeGraph(Body body) {
return enableExceptions ? ExceptionalUnitGraphFactory.createExceptionalUnitGraph(body) : new BriefUnitGraph(body);
}
protected Set<Unit> getCallsFromWithinMethod(SootMethod m) {
Set<Unit> res = null;
for (Unit u : m.getActiveBody().getUnits()) {
if (isCallStmt(u)) {
if (res == null) {
res = new LinkedHashSet<Unit>();
}
res.add(u);
}
}
return res == null ? Collections.<Unit>emptySet() : res;
}
@Override
public boolean isExitStmt(Unit u) {
Body body = getBodyOf(u);
DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body);
return unitGraph.getTails().contains(u);
}
@Override
public boolean isStartPoint(Unit u) {
Body body = getBodyOf(u);
DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body);
return unitGraph.getHeads().contains(u);
}
@Override
public boolean isFallThroughSuccessor(Unit u, Unit succ) {
assert getSuccsOf(u).contains(succ);
if (!u.fallsThrough()) {
return false;
}
Body body = getBodyOf(u);
return body.getUnits().getSuccOf(u) == succ;
}
@Override
public boolean isBranchTarget(Unit u, Unit succ) {
assert getSuccsOf(u).contains(succ);
if (!u.branches()) {
return false;
}
for (UnitBox ub : u.getUnitBoxes()) {
if (ub.getUnit() == succ) {
return true;
}
}
return false;
}
@Override
public List<Value> getParameterRefs(SootMethod m) {
return methodToParameterRefs.getUnchecked(m);
}
@Override
public Collection<Unit> getStartPointsOf(SootMethod m) {
if (m.hasActiveBody()) {
Body body = m.getActiveBody();
DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body);
return unitGraph.getHeads();
}
return Collections.emptySet();
}
public boolean setOwnerStatement(Unit u, Body b) {
return unitToOwner.put(u, b) == null;
}
@Override
public boolean isCallStmt(Unit u) {
return ((Stmt) u).containsInvokeExpr();
}
@Override
public Set<Unit> allNonCallStartNodes() {
Set<Unit> res = new LinkedHashSet<Unit>(unitToOwner.keySet());
for (Iterator<Unit> iter = res.iterator(); iter.hasNext();) {
Unit u = iter.next();
if (isStartPoint(u) || isCallStmt(u)) {
iter.remove();
}
}
return res;
}
@Override
public Set<Unit> allNonCallEndNodes() {
Set<Unit> res = new LinkedHashSet<Unit>(unitToOwner.keySet());
for (Iterator<Unit> iter = res.iterator(); iter.hasNext();) {
Unit u = iter.next();
if (isExitStmt(u) || isCallStmt(u)) {
iter.remove();
}
}
return res;
}
@Override
public Collection<Unit> getReturnSitesOfCallAt(Unit u) {
return getSuccsOf(u);
}
@Override
public Set<Unit> getCallsFromWithin(SootMethod m) {
return methodToCallsFromWithin.getUnchecked(m);
}
public void initializeUnitToOwner(SootMethod m) {
if (m.hasActiveBody()) {
Body b = m.getActiveBody();
PatchingChain<Unit> units = b.getUnits();
for (Unit unit : units) {
unitToOwner.put(unit, b);
}
}
}
@Override
public List<Unit> getPredsOf(Unit u) {
assert u != null;
Body body = getBodyOf(u);
if (body == null) {
return Collections.emptyList();
}
DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body);
return unitGraph.getPredsOf(u);
}
@Override
public Collection<Unit> getEndPointsOf(SootMethod m) {
if (m.hasActiveBody()) {
Body body = m.getActiveBody();
DirectedGraph<Unit> unitGraph = getOrCreateUnitGraph(body);
return unitGraph.getTails();
}
return Collections.emptySet();
}
@Override
public List<Unit> getPredsOfCallAt(Unit u) {
return getPredsOf(u);
}
@Override
public boolean isReturnSite(Unit n) {
for (Unit pred : getPredsOf(n)) {
if (isCallStmt(pred)) {
return true;
}
}
return false;
}
@Override
public boolean isReachable(Unit u) {
return unitToOwner.containsKey(u);
}
}
| 8,142
| 26.697279
| 118
|
java
|
soot
|
soot-master/src/main/java/soot/jimple/toolkits/ide/icfg/BackwardsInterproceduralCFG.java
|
package soot.jimple.toolkits.ide.icfg;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 1997 - 2013 Eric Bodden and others
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.List;
import java.util.Set;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.toolkits.graph.DirectedGraph;
/**
* Same as {@link JimpleBasedInterproceduralCFG} but based on inverted unit graphs. This should be used for backward
* analyses.
*/
public class BackwardsInterproceduralCFG implements BiDiInterproceduralCFG<Unit, SootMethod> {
protected final BiDiInterproceduralCFG<Unit, SootMethod> delegate;
public BackwardsInterproceduralCFG(BiDiInterproceduralCFG<Unit, SootMethod> fwICFG) {
delegate = fwICFG;
}
// swapped
@Override
public List<Unit> getSuccsOf(Unit n) {
return delegate.getPredsOf(n);
}
// swapped
@Override
public Collection<Unit> getStartPointsOf(SootMethod m) {
return delegate.getEndPointsOf(m);
}
// swapped
@Override
public List<Unit> getReturnSitesOfCallAt(Unit n) {
return delegate.getPredsOfCallAt(n);
}
// swapped
@Override
public boolean isExitStmt(Unit stmt) {
return delegate.isStartPoint(stmt);
}
// swapped
@Override
public boolean isStartPoint(Unit stmt) {
return delegate.isExitStmt(stmt);
}
// swapped
@Override
public Set<Unit> allNonCallStartNodes() {
return delegate.allNonCallEndNodes();
}
// swapped
@Override
public List<Unit> getPredsOf(Unit u) {
return delegate.getSuccsOf(u);
}
// swapped
@Override
public Collection<Unit> getEndPointsOf(SootMethod m) {
return delegate.getStartPointsOf(m);
}
// swapped
@Override
public List<Unit> getPredsOfCallAt(Unit u) {
return delegate.getSuccsOf(u);
}
// swapped
@Override
public Set<Unit> allNonCallEndNodes() {
return delegate.allNonCallStartNodes();
}
// same
@Override
public SootMethod getMethodOf(Unit n) {
return delegate.getMethodOf(n);
}
// same
@Override
public Collection<SootMethod> getCalleesOfCallAt(Unit n) {
return delegate.getCalleesOfCallAt(n);
}
// same
@Override
public Collection<Unit> getCallersOf(SootMethod m) {
return delegate.getCallersOf(m);
}
// same
@Override
public Set<Unit> getCallsFromWithin(SootMethod m) {
return delegate.getCallsFromWithin(m);
}
// same
@Override
public boolean isCallStmt(Unit stmt) {
return delegate.isCallStmt(stmt);
}
// same
@Override
public DirectedGraph<Unit> getOrCreateUnitGraph(SootMethod m) {
return delegate.getOrCreateUnitGraph(m);
}
// same
@Override
public List<Value> getParameterRefs(SootMethod m) {
return delegate.getParameterRefs(m);
}
@Override
public boolean isFallThroughSuccessor(Unit stmt, Unit succ) {
throw new UnsupportedOperationException("not implemented because semantics unclear");
}
@Override
public boolean isBranchTarget(Unit stmt, Unit succ) {
throw new UnsupportedOperationException("not implemented because semantics unclear");
}
// swapped
@Override
public boolean isReturnSite(Unit n) {
for (Unit pred : getSuccsOf(n)) {
if (isCallStmt(pred)) {
return true;
}
}
return false;
}
// same
@Override
public boolean isReachable(Unit u) {
return delegate.isReachable(u);
}
}
| 4,085
| 22.215909
| 116
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.