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/ide/icfg/BiDiInterproceduralCFG.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 heros.InterproceduralCFG; import java.util.Collection; import java.util.List; import java.util.Set; import soot.Value; import soot.toolkits.graph.DirectedGraph; /** * An {@link InterproceduralCFG} which supports the computation of predecessors. */ public interface BiDiInterproceduralCFG<N, M> extends InterproceduralCFG<N, M> { public List<N> getPredsOf(N u); public Collection<N> getEndPointsOf(M m); public List<N> getPredsOfCallAt(N u); public Set<N> allNonCallEndNodes(); // also exposed to some clients who need it public DirectedGraph<N> getOrCreateUnitGraph(M body); public List<Value> getParameterRefs(M m); /** * Gets whether the given statement is a return site of at least one call * * @param n * The statement to check * @return True if the given statement is a return site, otherwise false */ public boolean isReturnSite(N n); /** * Checks whether the given statement is rachable from the entry point * * @param u * The statement to check * @return True if there is a control flow path from the entry point of the program to the given statement, otherwise false */ public boolean isReachable(N u); }
2,071
28.183099
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/ide/icfg/JimpleBasedInterproceduralCFG.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 com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import heros.DontSynchronize; import heros.InterproceduralCFG; import heros.SynchronizedBy; import heros.ThreadSafe; import heros.solver.IDESolver; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.EdgePredicate; import soot.jimple.toolkits.callgraph.Filter; /** * Default implementation for the {@link InterproceduralCFG} interface. Includes all statements reachable from * {@link Scene#getEntryPoints()} through explicit call statements or through calls to {@link Thread#start()}. * * This class is designed to be thread safe, and subclasses of this class must be designed in a thread-safe way, too. */ @ThreadSafe public class JimpleBasedInterproceduralCFG extends AbstractJimpleBasedICFG { protected static final Logger logger = LoggerFactory.getLogger(IDESolver.class); protected boolean includeReflectiveCalls = false; protected boolean includePhantomCallees = false; // retains only callers that are explicit call sites or Thread.start() public class EdgeFilter extends Filter { protected EdgeFilter() { super(new EdgePredicate() { @Override public boolean want(Edge e) { return e.kind().isExplicit() || e.kind().isFake() || e.kind().isClinit() || (includeReflectiveCalls && e.kind().isReflection()); } }); } } @DontSynchronize("readonly") protected final CallGraph cg; protected CacheLoader<Unit, Collection<SootMethod>> loaderUnitToCallees = new CacheLoader<Unit, Collection<SootMethod>>() { @Override public Collection<SootMethod> load(Unit u) throws Exception { ArrayList<SootMethod> res = null; // only retain callers that are explicit call sites or // Thread.start() Iterator<Edge> edgeIter = new EdgeFilter().wrap(cg.edgesOutOf(u)); while (edgeIter.hasNext()) { Edge edge = edgeIter.next(); SootMethod m = edge.getTgt().method(); if (includePhantomCallees || m.hasActiveBody()) { if (res == null) { res = new ArrayList<SootMethod>(); } res.add(m); } else if (IDESolver.DEBUG) { logger.error(String.format("Method %s is referenced but has no body!", m.getSignature(), new Exception())); } } if (res != null) { res.trimToSize(); return res; } else { return Collections.emptySet(); } } }; @SynchronizedBy("by use of synchronized LoadingCache class") protected final LoadingCache<Unit, Collection<SootMethod>> unitToCallees = IDESolver.DEFAULT_CACHE_BUILDER.build(loaderUnitToCallees); protected CacheLoader<SootMethod, Collection<Unit>> loaderMethodToCallers = new CacheLoader<SootMethod, Collection<Unit>>() { @Override public Collection<Unit> load(SootMethod m) throws Exception { ArrayList<Unit> res = new ArrayList<Unit>(); // only retain callers that are explicit call sites or // Thread.start() Iterator<Edge> edgeIter = new EdgeFilter().wrap(cg.edgesInto(m)); while (edgeIter.hasNext()) { Edge edge = edgeIter.next(); res.add(edge.srcUnit()); } res.trimToSize(); return res; } }; @SynchronizedBy("by use of synchronized LoadingCache class") protected final LoadingCache<SootMethod, Collection<Unit>> methodToCallers = IDESolver.DEFAULT_CACHE_BUILDER.build(loaderMethodToCallers); public JimpleBasedInterproceduralCFG() { this(true); } public JimpleBasedInterproceduralCFG(boolean enableExceptions) { this(enableExceptions, false); } public JimpleBasedInterproceduralCFG(boolean enableExceptions, boolean includeReflectiveCalls) { super(enableExceptions); this.includeReflectiveCalls = includeReflectiveCalls; cg = Scene.v().getCallGraph(); initializeUnitToOwner(); } protected void initializeUnitToOwner() { for (Iterator<MethodOrMethodContext> iter = Scene.v().getReachableMethods().listener(); iter.hasNext();) { SootMethod m = iter.next().method(); initializeUnitToOwner(m); } } @Override public Collection<SootMethod> getCalleesOfCallAt(Unit u) { return unitToCallees.getUnchecked(u); } @Override public Collection<Unit> getCallersOf(SootMethod m) { return methodToCallers.getUnchecked(m); } /** * Sets whether methods that operate on the callgraph shall also return phantom methods as potential callees * * @param includePhantomCallees * True if phantom methods shall be returned as potential callees, otherwise false */ public void setIncludePhantomCallees(boolean includePhantomCallees) { this.includePhantomCallees = includePhantomCallees; } }
6,034
32.904494
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/ide/icfg/OnTheFlyJimpleBasedICFG.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.SynchronizedBy; import heros.solver.IDESolver; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import soot.ArrayType; import soot.Body; import soot.FastHierarchy; import soot.Local; import soot.NullType; import soot.PackManager; import soot.RefType; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.SourceLocator; import soot.Transform; import soot.Unit; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InterfaceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.Stmt; import soot.jimple.VirtualInvokeExpr; import soot.jimple.toolkits.pointer.LocalMustNotAliasAnalysis; import soot.options.Options; /** * This is an implementation of AbstractJimpleBasedICFG that computes the ICFG on-the-fly. In other words, it can be used * without pre-computing a call graph. Instead this implementation resolves calls through Class Hierarchy Analysis (CHA), as * implemented through FastHierarchy. The CHA is supported by LocalMustNotAliasAnalysis, which is used to determine cases * where the concrete type of an object at an InvokeVirtual or InvokeInterface callsite is known. In these cases the call can * be resolved concretely, i.e., to a single target. * * To be sound, for InvokeInterface calls that cannot be resolved concretely, OnTheFlyJimpleBasedICFG requires that all * classes on the classpath be loaded at least to signatures. This must be done before the FastHierarchy is computed such * that the hierarchy is intact. Clients should call {@link #loadAllClassesOnClassPathToSignatures()} to load all required * classes to this level. * * @see FastHierarchy#resolveConcreteDispatch(SootClass, SootMethod) * @see FastHierarchy#resolveAbstractDispatch(SootClass, SootMethod) */ public class OnTheFlyJimpleBasedICFG extends AbstractJimpleBasedICFG { @SynchronizedBy("by use of synchronized LoadingCache class") protected final LoadingCache<Body, LocalMustNotAliasAnalysis> bodyToLMNAA = IDESolver.DEFAULT_CACHE_BUILDER.build(new CacheLoader<Body, LocalMustNotAliasAnalysis>() { @Override public LocalMustNotAliasAnalysis load(Body body) throws Exception { return new LocalMustNotAliasAnalysis(getOrCreateUnitGraph(body), body); } }); @SynchronizedBy("by use of synchronized LoadingCache class") protected final LoadingCache<Unit, Set<SootMethod>> unitToCallees = IDESolver.DEFAULT_CACHE_BUILDER.build(new CacheLoader<Unit, Set<SootMethod>>() { @Override public Set<SootMethod> load(Unit u) throws Exception { Stmt stmt = (Stmt) u; InvokeExpr ie = stmt.getInvokeExpr(); FastHierarchy fastHierarchy = Scene.v().getFastHierarchy(); // FIXME Handle Thread.start etc. if (ie instanceof InstanceInvokeExpr) { if (ie instanceof SpecialInvokeExpr) { // special return Collections.singleton(ie.getMethod()); } else { // virtual and interface InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; Local base = (Local) iie.getBase(); RefType concreteType = bodyToLMNAA.getUnchecked(getBodyOf(u)).concreteType(base, stmt); if (concreteType != null) { // the base variable definitely points to a single concrete type SootMethod singleTargetMethod = fastHierarchy.resolveConcreteDispatch(concreteType.getSootClass(), iie.getMethod()); return Collections.singleton(singleTargetMethod); } else { SootClass baseTypeClass; if (base.getType() instanceof RefType) { RefType refType = (RefType) base.getType(); baseTypeClass = refType.getSootClass(); } else if (base.getType() instanceof ArrayType) { baseTypeClass = Scene.v().getSootClass("java.lang.Object"); } else if (base.getType() instanceof NullType) { // if the base is definitely null then there is no call target return Collections.emptySet(); } else { throw new InternalError("Unexpected base type:" + base.getType()); } return fastHierarchy.resolveAbstractDispatch(baseTypeClass, iie.getMethod()); } } } else { // static return Collections.singleton(ie.getMethod()); } } }); @SynchronizedBy("explicit lock on data structure") protected Map<SootMethod, Set<Unit>> methodToCallers = new HashMap<SootMethod, Set<Unit>>(); public OnTheFlyJimpleBasedICFG(SootMethod... entryPoints) { this(Arrays.asList(entryPoints)); } public OnTheFlyJimpleBasedICFG(Collection<SootMethod> entryPoints) { for (SootMethod m : entryPoints) { initForMethod(m); } } protected Body initForMethod(SootMethod m) { assert Scene.v().hasFastHierarchy(); Body b = null; if (m.isConcrete()) { SootClass declaringClass = m.getDeclaringClass(); ensureClassHasBodies(declaringClass); synchronized (Scene.v()) { b = m.retrieveActiveBody(); } if (b != null) { for (Unit u : b.getUnits()) { if (!setOwnerStatement(u, b)) { // if the unit was registered already then so were all units; // simply skip the rest break; } } } } assert Scene.v().hasFastHierarchy(); return b; } private synchronized void ensureClassHasBodies(SootClass cl) { assert Scene.v().hasFastHierarchy(); if (cl.resolvingLevel() < SootClass.BODIES) { Scene.v().forceResolve(cl.getName(), SootClass.BODIES); Scene.v().getOrMakeFastHierarchy(); } assert Scene.v().hasFastHierarchy(); } @Override public Set<SootMethod> getCalleesOfCallAt(Unit u) { Set<SootMethod> targets = unitToCallees.getUnchecked(u); for (SootMethod m : targets) { addCallerForMethod(u, m); initForMethod(m); } return targets; } private void addCallerForMethod(Unit callSite, SootMethod target) { synchronized (methodToCallers) { Set<Unit> callers = methodToCallers.get(target); if (callers == null) { callers = new HashSet<Unit>(); methodToCallers.put(target, callers); } callers.add(callSite); } } @Override public Set<Unit> getCallersOf(SootMethod m) { Set<Unit> callers = methodToCallers.get(m); return callers == null ? Collections.<Unit>emptySet() : callers; // throw new UnsupportedOperationException("This class is not suited for unbalanced problems"); } public static void loadAllClassesOnClassPathToSignatures() { for (String path : SourceLocator.explodeClassPath(Scene.v().getSootClassPath())) { for (String cl : SourceLocator.v().getClassesUnder(path)) { Scene.v().forceResolve(cl, SootClass.SIGNATURES); } } } public static void main(String[] args) { PackManager.v().getPack("wjtp").add(new Transform("wjtp.onflyicfg", new SceneTransformer() { @Override protected void internalTransform(String phaseName, Map<String, String> options) { if (Scene.v().hasCallGraph()) { throw new RuntimeException("call graph present!"); } loadAllClassesOnClassPathToSignatures(); SootMethod mainMethod = Scene.v().getMainMethod(); OnTheFlyJimpleBasedICFG icfg = new OnTheFlyJimpleBasedICFG(mainMethod); Set<SootMethod> worklist = new LinkedHashSet<SootMethod>(); Set<SootMethod> visited = new HashSet<SootMethod>(); worklist.add(mainMethod); int monomorphic = 0, polymorphic = 0; while (!worklist.isEmpty()) { Iterator<SootMethod> iter = worklist.iterator(); SootMethod currMethod = iter.next(); iter.remove(); visited.add(currMethod); System.err.println(currMethod); // MUST call this method to initialize ICFG for every method Body body = currMethod.getActiveBody(); if (body == null) { continue; } for (Unit u : body.getUnits()) { Stmt s = (Stmt) u; if (s.containsInvokeExpr()) { Set<SootMethod> calleesOfCallAt = icfg.getCalleesOfCallAt(s); if (s.getInvokeExpr() instanceof VirtualInvokeExpr || s.getInvokeExpr() instanceof InterfaceInvokeExpr) { if (calleesOfCallAt.size() <= 1) { monomorphic++; } else { polymorphic++; } System.err.println("mono: " + monomorphic + " poly: " + polymorphic); } for (SootMethod callee : calleesOfCallAt) { if (!visited.contains(callee)) { System.err.println(callee); // worklist.add(callee); } } } } } } })); Options.v().set_on_the_fly(true); soot.Main.main(args); } }
10,348
36.632727
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/ide/icfg/dotexport/ICFGDotVisualizer.java
package soot.jimple.toolkits.ide.icfg.dotexport; /*- * #%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 heros.InterproceduralCFG; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.SootMethod; import soot.Unit; import soot.util.dot.DotGraph; public class ICFGDotVisualizer { private static final Logger logger = LoggerFactory.getLogger(ICFGDotVisualizer.class); private DotGraph dotIcfg = new DotGraph(""); private ArrayList<Unit> visited = new ArrayList<Unit>(); String fileName; Unit startPoint; InterproceduralCFG<Unit, SootMethod> icfg; /** * This class will save your ICFG in DOT format by traversing the ICFG Depth-first! * * @param fileName: * Name of the file to save ICFG in DOT extension * @param startPoint: * This is of type Unit and is the starting point of the graph (eg. main method) * @param InterproceduralCFG<Unit, * SootMethod>: Object of InterproceduralCFG which represents the entire ICFG */ public ICFGDotVisualizer(String fileName, Unit startPoint, InterproceduralCFG<Unit, SootMethod> icfg) { this.fileName = fileName; this.startPoint = startPoint; this.icfg = icfg; if (this.fileName == null || this.fileName == "") { System.out.println("Please provide a vaid filename"); } if (this.startPoint == null) { System.out.println("startPoint is null!"); } if (this.icfg == null) { System.out.println("ICFG is null!"); } } /** * For the given file name, export the ICFG into DOT format. All parameters initialized through the constructor */ public void exportToDot() { if (this.startPoint != null && this.icfg != null && this.fileName != null) { graphTraverse(this.startPoint, this.icfg); dotIcfg.plot(this.fileName); logger.debug("" + fileName + DotGraph.DOT_EXTENSION); } else { System.out.println("Parameters not properly initialized!"); } } private void graphTraverse(Unit startPoint, InterproceduralCFG<Unit, SootMethod> icfg) { List<Unit> currentSuccessors = icfg.getSuccsOf(startPoint); if (currentSuccessors.size() == 0) { System.out.println("Traversal complete"); return; } else { for (Unit succ : currentSuccessors) { System.out.println("Succesor: " + succ.toString()); if (!visited.contains(succ)) { dotIcfg.drawEdge(startPoint.toString(), succ.toString()); visited.add(succ); graphTraverse(succ, icfg); } else { dotIcfg.drawEdge(startPoint.toString(), succ.toString()); } } } } }
3,454
30.990741
113
java
soot
soot-master/src/main/java/soot/jimple/toolkits/ide/libsumm/FixedMethods.java
package soot.jimple.toolkits.ide.libsumm; /*- * #%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.Scene; import soot.SootClass; import soot.SootMethod; import soot.jimple.InvokeExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticInvokeExpr; /** * Determines whether, according to the type hierarchy, a method call is fixed, i.e., cannot be overwritten by client code. */ // TODO implement caching for class and method info public class FixedMethods { public final static boolean ASSUME_PACKAGES_SEALED = false; /** * Returns true if a method call is fixed, i.e., assuming that all classes in the Scene resemble library code, then client * code cannot possible overwrite the called method. This is trivially true for InvokeStatic and InvokeSpecial, but can * also hold for virtual invokes if all possible call targets in the library cannot be overwritten. * * @see #clientOverwriteableOverwrites(SootMethod) */ public static boolean isFixed(InvokeExpr ie) { return ie instanceof StaticInvokeExpr || ie instanceof SpecialInvokeExpr || !clientOverwriteableOverwrites(ie.getMethod()); } /** * Returns true if this method itself is visible to the client and overwriteable or if the same holds for any of the * methods in the library that overwrite the argument method. * * @see #clientOverwriteable(SootMethod) */ private static boolean clientOverwriteableOverwrites(SootMethod m) { if (clientOverwriteable(m)) { return true; } SootClass c = m.getDeclaringClass(); // TODO could use PTA and call graph to filter subclasses further for (SootClass cPrime : Scene.v().getFastHierarchy().getSubclassesOf(c)) { SootMethod mPrime = cPrime.getMethodUnsafe(m.getSubSignature()); if (mPrime != null) { if (clientOverwriteable(mPrime)) { return true; } } } return false; } /** * Returns true if the given method itself is visible to the client and overwriteable. This is true if neither the method * nor its declaring class are final, if the method is visible and if the declaring class can be instantiated. * * @see #visible(SootMethod) * @see #clientCanInstantiate(SootClass) */ private static boolean clientOverwriteable(SootMethod m) { SootClass c = m.getDeclaringClass(); if (!c.isFinal() && !m.isFinal() && visible(m) && clientCanInstantiate(c)) { return true; } return false; } /** * Returns true if clients can instantiate the given class. This holds if the given class is actually an interface, or if * it contains a visible constructor. If the class is an inner class, then the enclosing classes must be instantiable as * well. */ private static boolean clientCanInstantiate(SootClass cPrime) { // subtypes of interface types can always be instantiated if (cPrime.isInterface()) { return true; } for (SootMethod m : cPrime.getMethods()) { if (m.getName().equals(SootMethod.constructorName)) { if (visible(m)) { return true; } } } return false; } /** * Returns true if the given method is visible to client code. */ private static boolean visible(SootMethod mPrime) { SootClass cPrime = mPrime.getDeclaringClass(); return (cPrime.isPublic() || cPrime.isProtected() || (!cPrime.isPrivate() && !ASSUME_PACKAGES_SEALED)) && (mPrime.isPublic() || mPrime.isProtected() || (!mPrime.isPrivate() && !ASSUME_PACKAGES_SEALED)); } }
4,316
34.677686
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/ide/libsumm/Main.java
package soot.jimple.toolkits.ide.libsumm; /*- * #%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.Map; import soot.Body; import soot.BodyTransformer; import soot.PackManager; import soot.Transform; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; public class Main { static int yes = 0, no = 0; /** * @param args */ public static void main(String[] args) { PackManager.v().getPack("jtp").add(new Transform("jtp.fixedie", new BodyTransformer() { @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { for (Unit u : b.getUnits()) { Stmt s = (Stmt) u; if (s.containsInvokeExpr()) { InvokeExpr ie = s.getInvokeExpr(); if (FixedMethods.isFixed(ie)) { System.err.println("+++ " + ie); yes++; } else { System.err.println(" - " + ie); no++; } } } } })); soot.Main.main(args); System.err.println("+++ " + yes); System.err.println(" - " + no); } }
1,898
26.926471
95
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/AbstractDataSource.java
package soot.jimple.toolkits.infoflow; /*- * #%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.Collections; import java.util.List; import soot.NullType; import soot.Type; import soot.UnitPrinter; import soot.Value; import soot.ValueBox; import soot.util.Switch; // Wraps any object as a Value public class AbstractDataSource implements Value { Object sourcename; public AbstractDataSource(Object sourcename) { this.sourcename = sourcename; } @Override public List<ValueBox> getUseBoxes() { return Collections.emptyList(); } /** Clones the object. Not implemented here. */ public Object clone() { return new AbstractDataSource(sourcename); } /** * Returns true if this object is structurally equivalent to c. AbstractDataSources are equal and equivalent if their * sourcename is the same */ public boolean equivTo(Object c) { if (sourcename instanceof Value) { return (c instanceof AbstractDataSource && ((Value) sourcename).equivTo(((AbstractDataSource) c).sourcename)); } return (c instanceof AbstractDataSource && ((AbstractDataSource) c).sourcename.equals(sourcename)); } public boolean equals(Object c) { return (c instanceof AbstractDataSource && ((AbstractDataSource) c).sourcename.equals(sourcename)); } /** Returns a hash code consistent with structural equality for this object. */ public int equivHashCode() { if (sourcename instanceof Value) { return ((Value) sourcename).equivHashCode(); } return sourcename.hashCode(); } public void toString(UnitPrinter up) { } public Type getType() { return NullType.v(); } public void apply(Switch sw) { throw new RuntimeException("Not Implemented"); } public String toString() { return "sourceof<" + sourcename.toString() + ">"; } }
2,599
27.26087
119
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/CachedEquivalentValue.java
package soot.jimple.toolkits.infoflow; /*- * #%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.WeakHashMap; import soot.EquivalentValue; import soot.Value; /** * An {@link EquivalentValue} with cached hash code and equals-relation. * * @author Eric Bodden */ public class CachedEquivalentValue extends EquivalentValue { protected int code = Integer.MAX_VALUE; protected WeakHashMap<Value, Boolean> isEquivalent = new WeakHashMap<Value, Boolean>(); public CachedEquivalentValue(Value e) { super(e); } public int hashCode() { if (code == Integer.MAX_VALUE) { code = super.hashCode(); } return code; } public boolean equals(Object o) { if (this.getClass() != o.getClass()) { return false; } EquivalentValue ev = (EquivalentValue) o; Value v = ev.getValue(); Boolean b = isEquivalent.get(v); if (b == null) { b = super.equals(o); isEquivalent.put(v, b); } return b; } }
1,725
24.761194
89
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/CallChain.java
package soot.jimple.toolkits.infoflow; /*- * #%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.Iterator; import java.util.LinkedList; import java.util.List; import soot.SootMethod; import soot.jimple.toolkits.callgraph.Edge; /** * CallChain written by Richard L. Halpert 2007-03-07 Stores a list of edges, and has a "next pointer" to a continuation of * the list */ public class CallChain { // List edges; Edge edge; CallChain next; public CallChain(Edge edge, CallChain next) { this.edge = edge; if (next != null && next.edge == null && next.next == null) { this.next = null; } else { this.next = next; } } // reconstructs the whole chain public List<Edge> getEdges() { List<Edge> ret = new LinkedList<Edge>(); if (edge != null) { ret.add(edge); } CallChain current = next; while (current != null) { ret.add(current.edge); current = current.next; } return ret; } public int size() { return 1 + (next == null ? 0 : next.size()); } public Iterator<Edge> iterator() { return getEdges().iterator(); } public boolean contains(Edge e) { return (edge == e) || (next != null && next.contains(e)); } public boolean containsMethod(SootMethod sm) { return (edge != null && edge.tgt() == sm) || (next != null && next.containsMethod(sm)); } // returns a shallow clone of this list... // which requires a deep clone of the CallChain objects in it public CallChain cloneAndExtend(CallChain extension) { if (next == null) { return new CallChain(edge, extension); } return new CallChain(edge, next.cloneAndExtend(extension)); } public Object clone() { if (next == null) { return new CallChain(edge, null); } return new CallChain(edge, (CallChain) next.clone()); } public boolean equals(Object o) { if (o instanceof CallChain) { CallChain other = (CallChain) o; if (edge == other.edge && ((next == null && other.next == null) || (next != null && other.next != null && next.equals(other.next)))) { return true; } } return false; } }
2,935
25.45045
123
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/CallLocalityContext.java
package soot.jimple.toolkits.infoflow; /*- * #%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.ArrayList; import java.util.List; import soot.EquivalentValue; import soot.RefLikeType; import soot.jimple.InstanceFieldRef; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.StaticFieldRef; import soot.jimple.ThisRef; /** * CallLocalityContext written by Richard L. Halpert 2007-03-05 Acts as a container for the locality information collected * about a call site by one of the Local Objects Analyses. */ public class CallLocalityContext { List<EquivalentValue> nodes; List<Boolean> isNodeLocal; public CallLocalityContext(List<EquivalentValue> nodes) { this.nodes = new ArrayList<EquivalentValue>(); this.nodes.addAll(nodes); isNodeLocal = new ArrayList<Boolean>(nodes.size()); for (int i = 0; i < nodes.size(); i++) { isNodeLocal.add(i, Boolean.FALSE); } } public void setFieldLocal(EquivalentValue fieldRef) { for (int i = 0; i < nodes.size(); i++) { if (fieldRef.equals(nodes.get(i))) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.TRUE); return; } } nodes.add(fieldRef); isNodeLocal.add(Boolean.TRUE); // throw new RuntimeException("Field " + fieldRef + " is not present in CallLocalityContext\n" + toString()); // return false; } public void setFieldShared(EquivalentValue fieldRef) { for (int i = 0; i < nodes.size(); i++) { if (fieldRef.equals(nodes.get(i))) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.FALSE); return; } } nodes.add(fieldRef); isNodeLocal.add(Boolean.FALSE); // throw new RuntimeException("Field " + fieldRef + " is not present in CallLocalityContext\n" + toString()); // return false; } public void setAllFieldsLocal() { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof InstanceFieldRef) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.TRUE); } } } public void setAllFieldsShared() { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof InstanceFieldRef) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.FALSE); } } } public void setParamLocal(int index) { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof ParameterRef) { ParameterRef pr = (ParameterRef) r; if (pr.getIndex() == index) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.TRUE); } } } } public void setParamShared(int index) { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof ParameterRef) { ParameterRef pr = (ParameterRef) r; if (pr.getIndex() == index) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.FALSE); } } } } public void setAllParamsLocal() { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof ParameterRef) { ParameterRef pr = (ParameterRef) r; if (pr.getIndex() != -1) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.TRUE); } } } } public void setAllParamsShared() { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof ParameterRef) { ParameterRef pr = (ParameterRef) r; if (pr.getIndex() != -1) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.FALSE); } } } } public void setThisLocal() { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof ThisRef) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.TRUE); } } } public void setThisShared() { for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof ThisRef) { isNodeLocal.remove(i); isNodeLocal.add(i, Boolean.FALSE); } } } public void setReturnLocal() { setParamLocal(-1); } public void setReturnShared() { setParamShared(-1); } public List<Object> getLocalRefs() { List<Object> ret = new ArrayList<Object>(); for (int i = 0; i < nodes.size(); i++) { if (isNodeLocal.get(i).booleanValue()) { ret.add(nodes.get(i)); } } return ret; } public List<Object> getSharedRefs() { List<Object> ret = new ArrayList<Object>(); for (int i = 0; i < nodes.size(); i++) { if (!isNodeLocal.get(i).booleanValue()) { ret.add(nodes.get(i)); } } return ret; } public boolean isFieldLocal(EquivalentValue fieldRef) { for (int i = 0; i < nodes.size(); i++) { if (fieldRef.equals(nodes.get(i))) { return isNodeLocal.get(i).booleanValue(); } } return false; // catches static fields that were not included in the original context // throw new RuntimeException("Field " + fieldRef + " is not present in CallLocalityContext\n" + toString()); // return false; } public boolean containsField(EquivalentValue fieldRef) { for (int i = 0; i < nodes.size(); i++) { if (fieldRef.equals(nodes.get(i))) { return true; } } return false; } // merges two contexts into one... shared fields in either context are shared in the merged context // return true if merge causes this context to change public boolean merge(CallLocalityContext other) { boolean isChanged = false; if (other.nodes.size() > nodes.size()) { isChanged = true; for (int i = nodes.size(); i < other.nodes.size(); i++) { nodes.add(other.nodes.get(i)); isNodeLocal.add(other.isNodeLocal.get(i)); } } for (int i = 0; i < other.nodes.size(); i++) { Boolean temp = new Boolean(isNodeLocal.get(i).booleanValue() && other.isNodeLocal.get(i).booleanValue()); if (!temp.equals(isNodeLocal.get(i))) { isChanged = true; } isNodeLocal.remove(i); isNodeLocal.add(i, temp); } return isChanged; } public boolean equals(Object o) { if (o instanceof CallLocalityContext) { CallLocalityContext other = (CallLocalityContext) o; return isNodeLocal.equals(other.isNodeLocal);// && nodes.equals(other.nodes); } return false; } public int hashCode() { return isNodeLocal.hashCode(); } public boolean isAllShared(boolean refsOnly) { for (int i = 0; i < nodes.size(); i++) { if ((!refsOnly) && isNodeLocal.get(i).booleanValue()) { return false; } else if (((EquivalentValue) nodes.get(i)).getValue().getType() instanceof RefLikeType && isNodeLocal.get(i).booleanValue()) { return false; } } return true; } public String toString() { String fieldrefs = ""; String staticrefs = ""; String paramrefs = ""; // includes returnref String thisref = ""; if (nodes.size() == 0) { return "Call Locality Context: NO NODES\n"; } for (int i = 0; i < nodes.size(); i++) { Ref r = (Ref) ((EquivalentValue) nodes.get(i)).getValue(); if (r instanceof InstanceFieldRef) { fieldrefs = fieldrefs + r + ": " + (isNodeLocal.get(i).booleanValue() ? "local" : "shared") + "\n"; } else if (r instanceof StaticFieldRef) { staticrefs = staticrefs + r + ": " + (isNodeLocal.get(i).booleanValue() ? "local" : "shared") + "\n"; } else if (r instanceof ParameterRef) { paramrefs = paramrefs + r + ": " + (isNodeLocal.get(i).booleanValue() ? "local" : "shared") + "\n"; } else if (r instanceof ThisRef) { thisref = thisref + r + ": " + (isNodeLocal.get(i).booleanValue() ? "local" : "shared") + "\n"; } else { return "Call Locality Context: HAS STRANGE NODE " + r + "\n"; } } return "Call Locality Context: \n" + fieldrefs + paramrefs + thisref + staticrefs; } public String toShortString() { String ret = "["; for (int i = 0; i < nodes.size(); i++) { ret = ret + (isNodeLocal.get(i).booleanValue() ? "L" : "S"); } return ret + "]"; } }
9,330
29.79538
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/ClassInfoFlowAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.EquivalentValue; import soot.Local; import soot.RefLikeType; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.VoidType; import soot.jimple.FieldRef; import soot.jimple.IdentityRef; import soot.jimple.IdentityStmt; import soot.jimple.InstanceFieldRef; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.HashMutableDirectedGraph; import soot.toolkits.graph.MemoryEfficientGraph; import soot.toolkits.graph.MutableDirectedGraph; import soot.toolkits.graph.UnitGraph; // ClassInfoFlowAnalysis written by Richard L. Halpert, 2007-02-22 // Constructs data flow tables for each method of a class. Ignores indirect flow. // These tables conservatively approximate how data flows from parameters, // fields, and globals to parameters, fields, globals, and the return value. // Note that a ref-type parameter (or field or global) might allow access to a // large data structure, but that entire structure will be represented only by // the parameter's one node in the data flow graph. public class ClassInfoFlowAnalysis { private static final Logger logger = LoggerFactory.getLogger(ClassInfoFlowAnalysis.class); SootClass sootClass; InfoFlowAnalysis dfa; // used to access the data flow analyses of other classes Map<SootMethod, SmartMethodInfoFlowAnalysis> methodToInfoFlowAnalysis; Map<SootMethod, HashMutableDirectedGraph<EquivalentValue>> methodToInfoFlowSummary; public static int methodCount = 0; public ClassInfoFlowAnalysis(SootClass sootClass, InfoFlowAnalysis dfa) { this.sootClass = sootClass; this.dfa = dfa; methodToInfoFlowAnalysis = new HashMap<SootMethod, SmartMethodInfoFlowAnalysis>(); methodToInfoFlowSummary = new HashMap<SootMethod, HashMutableDirectedGraph<EquivalentValue>>(); // doSimpleConservativeDataFlowAnalysis(); } public SmartMethodInfoFlowAnalysis getMethodInfoFlowAnalysis(SootMethod method) { if (!methodToInfoFlowAnalysis.containsKey(method)) { methodCount++; // First do simple version that doesn't follow invoke expressions // The "smart" version will be computed later, but since it may // request its own DataFlowGraph, we need this simple version first. if (!methodToInfoFlowSummary.containsKey(method)) { HashMutableDirectedGraph<EquivalentValue> dataFlowGraph = simpleConservativeInfoFlowAnalysis(method); methodToInfoFlowSummary.put(method, dataFlowGraph); } // Then do smart version that does follow invoke expressions, if possible if (method.isConcrete()) { Body b = method.retrieveActiveBody(); UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); SmartMethodInfoFlowAnalysis smdfa = new SmartMethodInfoFlowAnalysis(g, dfa); methodToInfoFlowAnalysis.put(method, smdfa); methodToInfoFlowSummary.remove(method); methodToInfoFlowSummary.put(method, smdfa.getMethodInfoFlowSummary()); return smdfa; // logger.debug(""+method + " has SMART infoFlowGraph: "); // printDataFlowGraph(mdfa.getMethodDataFlowGraph()); } } return methodToInfoFlowAnalysis.get(method); } public MutableDirectedGraph<EquivalentValue> getMethodInfoFlowSummary(SootMethod method) { return getMethodInfoFlowSummary(method, true); } public HashMutableDirectedGraph<EquivalentValue> getMethodInfoFlowSummary(SootMethod method, boolean doFullAnalysis) { if (!methodToInfoFlowSummary.containsKey(method)) { methodCount++; // First do simple version that doesn't follow invoke expressions // The "smart" version will be computed later, but since it may // request its own DataFlowGraph, we need this simple version first. HashMutableDirectedGraph<EquivalentValue> dataFlowGraph = simpleConservativeInfoFlowAnalysis(method); methodToInfoFlowSummary.put(method, dataFlowGraph); // Then do smart version that does follow invoke expressions, if possible if (method.isConcrete() && doFullAnalysis)// && method.getDeclaringClass().isApplicationClass()) { Body b = method.retrieveActiveBody(); UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); SmartMethodInfoFlowAnalysis smdfa = new SmartMethodInfoFlowAnalysis(g, dfa); methodToInfoFlowAnalysis.put(method, smdfa); methodToInfoFlowSummary.remove(method); methodToInfoFlowSummary.put(method, smdfa.getMethodInfoFlowSummary()); // logger.debug(""+method + " has SMART infoFlowGraph: "); // printDataFlowGraph(mdfa.getMethodDataFlowGraph()); } } return methodToInfoFlowSummary.get(method); } /* * public void doFixedPointDataFlowAnalysis() { Iterator it = sootClass.getMethods().iterator(); while(it.hasNext()) { * SootMethod method = (SootMethod) it.next(); * * if(method.isConcrete()) { Body b = method.retrieveActiveBody(); UnitGraph g = new ExceptionalUnitGraph(b); * SmartMethodInfoFlowAnalysis smdfa = new SmartMethodInfoFlowAnalysis(g, dfa, true); * if(methodToInfoFlowSummary.containsKey(method)) methodToInfoFlowSummary.remove(method); else methodCount++; * methodToInfoFlowSummary.put(method, smdfa.getMethodDataFlowSummary()); * * // logger.debug(""+method + " has FLOW SENSITIVE infoFlowGraph: "); // * printDataFlowGraph(mdfa.getMethodDataFlowGraph()); } else { if(methodToInfoFlowSummary.containsKey(method)) * methodToInfoFlowSummary.remove(method); else methodCount++; methodToInfoFlowSummary.put(method, * triviallyConservativeDataFlowAnalysis(method)); * * // logger.debug(""+method + " has TRIVIALLY CONSERVATIVE infoFlowGraph: "); // printDataFlowGraph((MutableDirectedGraph) * methodToInfoFlowSummary.get(method)); } } } // */ /* * private void doSimpleConservativeDataFlowAnalysis() { Iterator it = sootClass.getMethods().iterator(); * while(it.hasNext()) { SootMethod method = (SootMethod) it.next(); MutableDirectedGraph infoFlowGraph = * simpleConservativeDataFlowAnalysis(method); if(methodToInfoFlowSummary.containsKey(method)) * methodToInfoFlowSummary.remove(method); else methodCount++; methodToInfoFlowSummary.put(method, infoFlowGraph); * * // logger.debug(""+method + " has infoFlowGraph: "); // printDataFlowGraph(infoFlowGraph); } } // */ /** Does not require any fixed point calculation */ private HashMutableDirectedGraph<EquivalentValue> simpleConservativeInfoFlowAnalysis(SootMethod sm) { // Constructs a graph representing the data flow between fields, parameters, and the // return value of this method. The graph nodes are EquivalentValue wrapped Refs. // This version is rather stupid... it just assumes all values flow to all others, // except for the return value, which is flowed to by all, but flows to none. // This version is also broken... it can't handle the ThisRef without // flow sensitivity. // If this method cannot have a body, then we can't analyze it... if (!sm.isConcrete()) { return triviallyConservativeInfoFlowAnalysis(sm); } Body b = sm.retrieveActiveBody(); UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); HashSet<EquivalentValue> fieldsStaticsParamsAccessed = new HashSet<EquivalentValue>(); // Get list of fields, globals, and parameters that are accessed for (Unit u : g) { Stmt s = (Stmt) u; if (s instanceof IdentityStmt) { IdentityStmt is = (IdentityStmt) s; IdentityRef ir = (IdentityRef) is.getRightOp(); if (ir instanceof ParameterRef) { ParameterRef pr = (ParameterRef) ir; fieldsStaticsParamsAccessed.add(InfoFlowAnalysis.getNodeForParameterRef(sm, pr.getIndex())); } } if (s.containsFieldRef()) { FieldRef ref = s.getFieldRef(); if (ref instanceof StaticFieldRef) { // This should be added to the list of fields accessed // static fields "belong to everyone" StaticFieldRef sfr = (StaticFieldRef) ref; fieldsStaticsParamsAccessed.add(InfoFlowAnalysis.getNodeForFieldRef(sm, sfr.getField())); } else if (ref instanceof InstanceFieldRef) { // If this field is a field of this class, // then this should be added to the list of fields accessed InstanceFieldRef ifr = (InstanceFieldRef) ref; Value base = ifr.getBase(); if (base instanceof Local) { if (dfa.includesInnerFields() || ((!sm.isStatic()) && base.equivTo(b.getThisLocal()))) { fieldsStaticsParamsAccessed.add(InfoFlowAnalysis.getNodeForFieldRef(sm, ifr.getField())); } } } } } // Each accessed field, global, and parameter becomes a node in the graph HashMutableDirectedGraph<EquivalentValue> dataFlowGraph = new MemoryEfficientGraph<EquivalentValue>(); Iterator<EquivalentValue> accessedIt1 = fieldsStaticsParamsAccessed.iterator(); while (accessedIt1.hasNext()) { EquivalentValue o = accessedIt1.next(); dataFlowGraph.addNode(o); } // Add all of the nodes necessary to ensure that this is a complete data flow graph // Add every parameter of this method for (int i = 0; i < sm.getParameterCount(); i++) { EquivalentValue parameterRefEqVal = InfoFlowAnalysis.getNodeForParameterRef(sm, i); if (!dataFlowGraph.containsNode(parameterRefEqVal)) { dataFlowGraph.addNode(parameterRefEqVal); } } // Add every relevant field of this class (static methods don't get non-static fields) for (SootField sf : sm.getDeclaringClass().getFields()) { if (sf.isStatic() || !sm.isStatic()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf); if (!dataFlowGraph.containsNode(fieldRefEqVal)) { dataFlowGraph.addNode(fieldRefEqVal); } } } // Add every field of this class's superclasses SootClass superclass = sm.getDeclaringClass(); if (superclass.hasSuperclass()) { superclass = sm.getDeclaringClass().getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { for (SootField scField : superclass.getFields()) { if (scField.isStatic() || !sm.isStatic()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, scField); if (!dataFlowGraph.containsNode(fieldRefEqVal)) { dataFlowGraph.addNode(fieldRefEqVal); } } } superclass = superclass.getSuperclass(); } // The return value also becomes a node in the graph ParameterRef returnValueRef = null; if (sm.getReturnType() != VoidType.v()) { returnValueRef = new ParameterRef(sm.getReturnType(), -1); dataFlowGraph.addNode(InfoFlowAnalysis.getNodeForReturnRef(sm)); } // ThisRef thisRef = null; if (!sm.isStatic()) { // thisRef = new ThisRef(sootClass.getType()); dataFlowGraph.addNode(InfoFlowAnalysis.getNodeForThisRef(sm)); fieldsStaticsParamsAccessed.add(InfoFlowAnalysis.getNodeForThisRef(sm)); } // Create an edge from each node (except the return value) to every other node (including the return value) // non-Ref-type nodes are ignored accessedIt1 = fieldsStaticsParamsAccessed.iterator(); while (accessedIt1.hasNext()) { EquivalentValue r = accessedIt1.next(); Ref rRef = (Ref) r.getValue(); if (!(rRef.getType() instanceof RefLikeType) && !dfa.includesPrimitiveInfoFlow()) { continue; } Iterator<EquivalentValue> accessedIt2 = fieldsStaticsParamsAccessed.iterator(); while (accessedIt2.hasNext()) { EquivalentValue s = accessedIt2.next(); Ref sRef = (Ref) s.getValue(); if (rRef instanceof ThisRef && sRef instanceof InstanceFieldRef) { ; // don't add this edge } else if (sRef instanceof ThisRef && rRef instanceof InstanceFieldRef) { ; // don't add this edge } else if (sRef instanceof ParameterRef && dfa.includesInnerFields()) { ; // don't add edges to parameters if we are including inner fields } else if (sRef.getType() instanceof RefLikeType) { dataFlowGraph.addEdge(r, s); } } if (returnValueRef != null && (returnValueRef.getType() instanceof RefLikeType || dfa.includesPrimitiveInfoFlow())) { dataFlowGraph.addEdge(r, InfoFlowAnalysis.getNodeForReturnRef(sm)); } } return dataFlowGraph; } /** Does not require the method to have a body */ public HashMutableDirectedGraph<EquivalentValue> triviallyConservativeInfoFlowAnalysis(SootMethod sm) { HashSet<EquivalentValue> fieldsStaticsParamsAccessed = new HashSet<EquivalentValue>(); // Add all of the nodes necessary to ensure that this is a complete data flow graph // Add every parameter of this method for (int i = 0; i < sm.getParameterCount(); i++) { EquivalentValue parameterRefEqVal = InfoFlowAnalysis.getNodeForParameterRef(sm, i); fieldsStaticsParamsAccessed.add(parameterRefEqVal); } // Add every relevant field of this class (static methods don't get non-static fields) for (Iterator<SootField> it = sm.getDeclaringClass().getFields().iterator(); it.hasNext();) { SootField sf = it.next(); if (sf.isStatic() || !sm.isStatic()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf); fieldsStaticsParamsAccessed.add(fieldRefEqVal); } } // Add every field of this class's superclasses SootClass superclass = sm.getDeclaringClass(); if (superclass.hasSuperclass()) { superclass = sm.getDeclaringClass().getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { Iterator<SootField> scFieldsIt = superclass.getFields().iterator(); while (scFieldsIt.hasNext()) { SootField scField = scFieldsIt.next(); if (scField.isStatic() || !sm.isStatic()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, scField); fieldsStaticsParamsAccessed.add(fieldRefEqVal); } } superclass = superclass.getSuperclass(); } // Don't add any static fields outside of the class... unsafe??? // Each field, global, and parameter becomes a node in the graph HashMutableDirectedGraph<EquivalentValue> dataFlowGraph = new MemoryEfficientGraph<EquivalentValue>(); Iterator<EquivalentValue> accessedIt1 = fieldsStaticsParamsAccessed.iterator(); while (accessedIt1.hasNext()) { EquivalentValue o = accessedIt1.next(); dataFlowGraph.addNode(o); } // The return value also becomes a node in the graph ParameterRef returnValueRef = null; if (sm.getReturnType() != VoidType.v()) { returnValueRef = new ParameterRef(sm.getReturnType(), -1); dataFlowGraph.addNode(InfoFlowAnalysis.getNodeForReturnRef(sm)); } if (!sm.isStatic()) { dataFlowGraph.addNode(InfoFlowAnalysis.getNodeForThisRef(sm)); fieldsStaticsParamsAccessed.add(InfoFlowAnalysis.getNodeForThisRef(sm)); } // Create an edge from each node (except the return value) to every other node (including the return value) // non-Ref-type nodes are ignored accessedIt1 = fieldsStaticsParamsAccessed.iterator(); while (accessedIt1.hasNext()) { EquivalentValue r = accessedIt1.next(); Ref rRef = (Ref) r.getValue(); if (!(rRef.getType() instanceof RefLikeType) && !dfa.includesPrimitiveInfoFlow()) { continue; } Iterator<EquivalentValue> accessedIt2 = fieldsStaticsParamsAccessed.iterator(); while (accessedIt2.hasNext()) { EquivalentValue s = accessedIt2.next(); Ref sRef = (Ref) s.getValue(); if (rRef instanceof ThisRef && sRef instanceof InstanceFieldRef) { ; // don't add this edge } else if (sRef instanceof ThisRef && rRef instanceof InstanceFieldRef) { ; // don't add this edge } else if (sRef.getType() instanceof RefLikeType) { dataFlowGraph.addEdge(r, s); } } if (returnValueRef != null && (returnValueRef.getType() instanceof RefLikeType || dfa.includesPrimitiveInfoFlow())) { dataFlowGraph.addEdge(r, InfoFlowAnalysis.getNodeForReturnRef(sm)); } } return dataFlowGraph; } }
17,708
42.834158
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/ClassLocalObjectsAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.EquivalentValue; import soot.RefLikeType; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootFieldRef; import soot.SootMethod; import soot.Value; import soot.jimple.DefinitionStmt; import soot.jimple.FieldRef; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.ExceptionalUnitGraphFactory; import soot.toolkits.graph.MutableDirectedGraph; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.Pair; // ClassLocalObjectsAnalysis written by Richard L. Halpert, 2007-02-23 // Finds objects that are local to the given scope. // NOTE THAT THIS ANALYSIS'S RESULTS DO NOT APPLY TO SUBCLASSES OF THE GIVEN CLASS public class ClassLocalObjectsAnalysis { private static final Logger logger = LoggerFactory.getLogger(ClassLocalObjectsAnalysis.class); boolean printdfgs; LocalObjectsAnalysis loa; InfoFlowAnalysis dfa; InfoFlowAnalysis primitiveDfa; UseFinder uf; SootClass sootClass; Map<SootMethod, SmartMethodLocalObjectsAnalysis> methodToMethodLocalObjectsAnalysis; Map<SootMethod, CallLocalityContext> methodToContext; List<SootMethod> allMethods; // methods that are called at least once from outside of this class (ie need to be public, protected, or package-private) List<SootMethod> externalMethods; // methods that are only ever called by other methods in this class (ie could be marked private) List<SootMethod> internalMethods; // methods that should be used as starting points when determining if a value in a method called from this class is local // or shared // for thread-local objects, this would contain just the run method. For structure-local, it should contain all external // methods List<SootMethod> entryMethods; List<SootField> allFields; List<SootField> externalFields; List<SootField> internalFields; ArrayList<SootField> localFields; ArrayList<SootField> sharedFields; ArrayList<SootField> localInnerFields; ArrayList<SootField> sharedInnerFields; public ClassLocalObjectsAnalysis(LocalObjectsAnalysis loa, InfoFlowAnalysis dfa, UseFinder uf, SootClass sootClass) { this(loa, dfa, null, uf, sootClass, null); } public ClassLocalObjectsAnalysis(LocalObjectsAnalysis loa, InfoFlowAnalysis dfa, InfoFlowAnalysis primitiveDfa, UseFinder uf, SootClass sootClass, List<SootMethod> entryMethods) { printdfgs = dfa.printDebug(); this.loa = loa; this.dfa = dfa; this.primitiveDfa = primitiveDfa; this.uf = uf; this.sootClass = sootClass; this.methodToMethodLocalObjectsAnalysis = new HashMap<SootMethod, SmartMethodLocalObjectsAnalysis>(); this.methodToContext = null; this.allMethods = null; this.externalMethods = null; this.internalMethods = null; this.entryMethods = entryMethods; this.allFields = null; this.externalFields = null; this.internalFields = null; this.localFields = null; this.sharedFields = null; this.localInnerFields = null; this.sharedInnerFields = null; if (true) // verbose) { logger.debug("[local-objects] Analyzing local objects for " + sootClass); logger.debug("[local-objects] preparing class " + new Date()); } prepare(); if (true) // verbose) { logger.debug("[local-objects] analyzing class " + new Date()); } doAnalysis(); if (true) // verbose) { logger.debug("[local-objects] propagating over call graph " + new Date()); } propagate(); if (true) { logger.debug("[local-objects] finished at " + new Date()); logger.debug("[local-objects] (#analyzed/#encountered): " + SmartMethodInfoFlowAnalysis.counter + "/" + ClassInfoFlowAnalysis.methodCount); } } private void prepare() { // Get list of all methods allMethods = getAllReachableMethods(sootClass); // Get list of external methods externalMethods = uf.getExtMethods(sootClass); SootClass superclass = sootClass; if (superclass.hasSuperclass()) { superclass = superclass.getSuperclass(); } while (superclass.hasSuperclass()) { if (superclass.isApplicationClass()) { externalMethods.addAll(uf.getExtMethods(superclass)); } superclass = superclass.getSuperclass(); } // Get list of internal methods internalMethods = new ArrayList<SootMethod>(); for (SootMethod method : allMethods) { if (!externalMethods.contains(method)) { internalMethods.add(method); } } // Get list of all fields allFields = getAllFields(sootClass); // Get list of external fields externalFields = uf.getExtFields(sootClass); superclass = sootClass; if (superclass.hasSuperclass()) { superclass = superclass.getSuperclass(); } while (superclass.hasSuperclass()) { if (superclass.isApplicationClass()) { externalFields.addAll(uf.getExtFields(superclass)); } superclass = superclass.getSuperclass(); } // Get list of internal fields internalFields = new ArrayList<SootField>(); for (SootField field : allFields) { if (!externalFields.contains(field)) { internalFields.add(field); } } } // Returns a list of reachable methods in class sc and its superclasses public static List<SootMethod> getAllReachableMethods(SootClass sc) { ReachableMethods rm = Scene.v().getReachableMethods(); // Get list of reachable methods declared in this class List<SootMethod> allMethods = new ArrayList<SootMethod>(); Iterator methodsIt = sc.methodIterator(); while (methodsIt.hasNext()) { SootMethod method = (SootMethod) methodsIt.next(); if (rm.contains(method)) { allMethods.add(method); } } // Add reachable methods declared in superclasses SootClass superclass = sc; if (superclass.hasSuperclass()) { superclass = superclass.getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { Iterator scMethodsIt = superclass.methodIterator(); while (scMethodsIt.hasNext()) { SootMethod scMethod = (SootMethod) scMethodsIt.next(); if (rm.contains(scMethod)) { allMethods.add(scMethod); } } superclass = superclass.getSuperclass(); } return allMethods; } // Returns a list of fields in class sc and its superclasses public static List<SootField> getAllFields(SootClass sc) { // Get list of reachable methods declared in this class // Also get list of fields declared in this class List<SootField> allFields = new ArrayList<SootField>(); for (SootField field : sc.getFields()) { allFields.add(field); } // Add reachable methods and fields declared in superclasses SootClass superclass = sc; if (superclass.hasSuperclass()) { superclass = superclass.getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { for (SootField scField : superclass.getFields()) { allFields.add(scField); } superclass = superclass.getSuperclass(); } return allFields; } private void doAnalysis() { // Combine the DFA results for each of this class's methods, using safe // approximations for which parameters, fields, and globals are shared // or local. // Separate fields into shared and local. Initially fields are known to be // shared if they have any external accesses, or if they're static. // Methods are iterated over, moving fields to shared if shared data flows to them. // This is repeated until no fields move for a complete iteration. // Populate localFields and sharedFields with fields of this class localFields = new ArrayList<SootField>(); sharedFields = new ArrayList<SootField>(); Iterator<SootField> fieldsIt = allFields.iterator(); while (fieldsIt.hasNext()) { SootField field = fieldsIt.next(); if (fieldIsInitiallyLocal(field)) { localFields.add(field); } else { sharedFields.add(field); } } // Add inner fields to localFields and sharedFields, if present localInnerFields = new ArrayList<SootField>(); sharedInnerFields = new ArrayList<SootField>(); Iterator<SootMethod> methodsIt = allMethods.iterator(); while (methodsIt.hasNext()) { SootMethod method = methodsIt.next(); // Get data flow summary MutableDirectedGraph dataFlowSummary; if (primitiveDfa != null) { dataFlowSummary = primitiveDfa.getMethodInfoFlowSummary(method); if (printdfgs && method.getDeclaringClass().isApplicationClass()) { logger.debug("Attempting to print graphs (will succeed only if ./dfg/ is a valid path)"); DirectedGraph primitiveGraph = primitiveDfa.getMethodInfoFlowAnalysis(method).getMethodAbbreviatedInfoFlowGraph(); InfoFlowAnalysis.printGraphToDotFile( "dfg/" + method.getDeclaringClass().getShortName() + "_" + method.getName() + "_primitive", primitiveGraph, method.getName() + "_primitive", false); DirectedGraph nonPrimitiveGraph = dfa.getMethodInfoFlowAnalysis(method).getMethodAbbreviatedInfoFlowGraph(); InfoFlowAnalysis.printGraphToDotFile("dfg/" + method.getDeclaringClass().getShortName() + "_" + method.getName(), nonPrimitiveGraph, method.getName(), false); } } else { dataFlowSummary = dfa.getMethodInfoFlowSummary(method); if (printdfgs && method.getDeclaringClass().isApplicationClass()) { logger.debug("Attempting to print graph (will succeed only if ./dfg/ is a valid path)"); DirectedGraph nonPrimitiveGraph = dfa.getMethodInfoFlowAnalysis(method).getMethodAbbreviatedInfoFlowGraph(); InfoFlowAnalysis.printGraphToDotFile("dfg/" + method.getDeclaringClass().getShortName() + "_" + method.getName(), nonPrimitiveGraph, method.getName(), false); } } // Iterate through nodes Iterator<Object> nodesIt = dataFlowSummary.getNodes().iterator(); while (nodesIt.hasNext()) { EquivalentValue node = (EquivalentValue) nodesIt.next(); if (node.getValue() instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) node.getValue(); if (!localFields.contains(ifr.getField()) && !sharedFields.contains(ifr.getField()) && !localInnerFields.contains(ifr.getField())) // && // !sharedInnerFields.contains(ifr.getField())) { // this field is read or written, but is not in the lists of fields! localInnerFields.add(ifr.getField()); } } } } // Propagate (aka iterate iterate iterate iterate! hope it's not too slow) boolean changed = true; while (changed) { changed = false; // logger.debug("Starting iteration:"); methodsIt = allMethods.iterator(); while (methodsIt.hasNext()) { SootMethod method = methodsIt.next(); // we can't learn anything from non-concrete methods, and statics can't write non-static fields if (method.isStatic() || !method.isConcrete()) { continue; } ListIterator<SootField> localFieldsIt = ((List<SootField>) localFields).listIterator(); while (localFieldsIt.hasNext()) { SootField localField = localFieldsIt.next(); List sourcesAndSinks = new ArrayList(); MutableDirectedGraph dataFlowSummary; if (primitiveDfa != null) { dataFlowSummary = primitiveDfa.getMethodInfoFlowSummary(method); } else { dataFlowSummary = dfa.getMethodInfoFlowSummary(method); } EquivalentValue node = InfoFlowAnalysis.getNodeForFieldRef(method, localField); if (dataFlowSummary.containsNode(node)) { sourcesAndSinks.addAll(dataFlowSummary.getSuccsOf(node)); sourcesAndSinks.addAll(dataFlowSummary.getPredsOf(node)); } Iterator sourcesAndSinksIt = sourcesAndSinks.iterator(); if (localField.getDeclaringClass().isApplicationClass() && sourcesAndSinksIt.hasNext()) { // if(!printedMethodHeading) // { // logger.debug(" Method: " + method.toString()); // printedMethodHeading = true; // } // logger.debug(" Field: " + localField.toString()); } while (sourcesAndSinksIt.hasNext()) { EquivalentValue sourceOrSink = (EquivalentValue) sourcesAndSinksIt.next(); Ref sourceOrSinkRef = (Ref) sourceOrSink.getValue(); boolean fieldBecomesShared = false; if (sourceOrSinkRef instanceof ParameterRef) // or return ref { fieldBecomesShared = !parameterIsLocal(method, sourceOrSink, true); } else if (sourceOrSinkRef instanceof ThisRef) // or return ref { fieldBecomesShared = !thisIsLocal(method, sourceOrSink); } else if (sourceOrSinkRef instanceof InstanceFieldRef) { fieldBecomesShared = sharedFields.contains(((FieldRef) sourceOrSinkRef).getField()) || sharedInnerFields.contains(((FieldRef) sourceOrSinkRef).getField()); } else if (sourceOrSinkRef instanceof StaticFieldRef) { fieldBecomesShared = true; } else { throw new RuntimeException("Unknown type of Ref in Data Flow Graph:"); } if (fieldBecomesShared) { // if(localField.getDeclaringClass().isApplicationClass()) // logger.debug(" Source/Sink: " + sourceOrSinkRef.toString() + " is SHARED"); localFieldsIt.remove(); sharedFields.add(localField); changed = true; break; // other sources don't matter now... it only takes one to taint the field } else { // if(localField.getDeclaringClass().isApplicationClass()) // logger.debug(" Source: " + sourceRef.toString() + " is local"); } } } ListIterator<SootField> localInnerFieldsIt = ((List<SootField>) localInnerFields).listIterator(); // boolean printedMethodHeading = false; while (!changed && localInnerFieldsIt.hasNext()) { SootField localInnerField = localInnerFieldsIt.next(); List sourcesAndSinks = new ArrayList(); MutableDirectedGraph dataFlowSummary; if (primitiveDfa != null) { dataFlowSummary = primitiveDfa.getMethodInfoFlowSummary(method); } else { dataFlowSummary = dfa.getMethodInfoFlowSummary(method); } EquivalentValue node = InfoFlowAnalysis.getNodeForFieldRef(method, localInnerField); if (dataFlowSummary.containsNode(node)) { sourcesAndSinks.addAll(dataFlowSummary.getSuccsOf(node)); sourcesAndSinks.addAll(dataFlowSummary.getPredsOf(node)); } Iterator sourcesAndSinksIt = sourcesAndSinks.iterator(); if (localInnerField.getDeclaringClass().isApplicationClass() && sourcesAndSinksIt.hasNext()) { // if(!printedMethodHeading) // { // logger.debug(" Method: " + method.toString()); // printedMethodHeading = true; // } // logger.debug(" Field: " + localField.toString()); } while (sourcesAndSinksIt.hasNext()) { EquivalentValue sourceOrSink = (EquivalentValue) sourcesAndSinksIt.next(); Ref sourceOrSinkRef = (Ref) sourceOrSink.getValue(); boolean fieldBecomesShared = false; if (sourceOrSinkRef instanceof ParameterRef) // or return ref { fieldBecomesShared = !parameterIsLocal(method, sourceOrSink, true); } else if (sourceOrSinkRef instanceof ThisRef) // or return ref { fieldBecomesShared = !thisIsLocal(method, sourceOrSink); } else if (sourceOrSinkRef instanceof InstanceFieldRef) { fieldBecomesShared = sharedFields.contains(((FieldRef) sourceOrSinkRef).getField()) || sharedInnerFields.contains(((FieldRef) sourceOrSinkRef).getField()); } else if (sourceOrSinkRef instanceof StaticFieldRef) { fieldBecomesShared = true; } else { throw new RuntimeException("Unknown type of Ref in Data Flow Graph:"); } if (fieldBecomesShared) { // if(localField.getDeclaringClass().isApplicationClass()) // logger.debug(" Source/Sink: " + sourceOrSinkRef.toString() + " is SHARED"); localInnerFieldsIt.remove(); sharedInnerFields.add(localInnerField); changed = true; break; // other sources don't matter now... it only takes one to taint the field } else { // if(localField.getDeclaringClass().isApplicationClass()) // logger.debug(" Source: " + sourceRef.toString() + " is local"); } } } } } // Print debug output if (dfa.printDebug()) { logger.debug(" Found local/shared fields for " + sootClass.toString()); logger.debug(" Local fields: "); Iterator<SootField> localsToPrintIt = localFields.iterator(); while (localsToPrintIt.hasNext()) { SootField localToPrint = localsToPrintIt.next(); if (localToPrint.getDeclaringClass().isApplicationClass()) { logger.debug(" " + localToPrint); } } logger.debug(" Shared fields: "); Iterator<SootField> sharedsToPrintIt = sharedFields.iterator(); while (sharedsToPrintIt.hasNext()) { SootField sharedToPrint = sharedsToPrintIt.next(); if (sharedToPrint.getDeclaringClass().isApplicationClass()) { logger.debug(" " + sharedToPrint); } } logger.debug(" Local inner fields: "); localsToPrintIt = localInnerFields.iterator(); while (localsToPrintIt.hasNext()) { SootField localToPrint = localsToPrintIt.next(); if (localToPrint.getDeclaringClass().isApplicationClass()) { logger.debug(" " + localToPrint); } } logger.debug(" Shared inner fields: "); sharedsToPrintIt = sharedInnerFields.iterator(); while (sharedsToPrintIt.hasNext()) { SootField sharedToPrint = sharedsToPrintIt.next(); if (sharedToPrint.getDeclaringClass().isApplicationClass()) { logger.debug(" " + sharedToPrint); } } } } private void propagate() { // Initialize worklist ArrayList<SootMethod> worklist = new ArrayList<SootMethod>(); worklist.addAll(entryMethods); // Initialize set of contexts methodToContext = new HashMap<SootMethod, CallLocalityContext>(); // TODO: add the ability to share a map with another // CLOA to save memory (be // careful of context-sensitive call graph) for (SootMethod method : worklist) { methodToContext.put(method, getContextFor(method)); } // Propagate Date start = new Date(); if (dfa.printDebug()) { logger.debug("CLOA: Starting Propagation at " + start); } while (worklist.size() > 0) { ArrayList<SootMethod> newWorklist = new ArrayList<SootMethod>(); for (SootMethod containingMethod : worklist) { CallLocalityContext containingContext = methodToContext.get(containingMethod); if (dfa.printDebug()) { logger.debug(" " + containingMethod.getName() + " " + containingContext.toShortString()); } // Calculate the context for each invoke stmt in the containingMethod Map<Stmt, CallLocalityContext> invokeToContext = new HashMap<Stmt, CallLocalityContext>(); for (Iterator edgesIt = Scene.v().getCallGraph().edgesOutOf(containingMethod); edgesIt.hasNext();) { Edge e = (Edge) edgesIt.next(); if (!e.src().getDeclaringClass().isApplicationClass() || e.srcStmt() == null) { continue; } CallLocalityContext invokeContext; if (!invokeToContext.containsKey(e.srcStmt())) { invokeContext = getContextFor(e, containingMethod, containingContext); invokeToContext.put(e.srcStmt(), invokeContext); } else { invokeContext = invokeToContext.get(e.srcStmt()); } if (!methodToContext.containsKey(e.tgt())) { methodToContext.put(e.tgt(), invokeContext); newWorklist.add(e.tgt()); } else { // logger.debug(" Merging Contexts for " + e.tgt()); boolean causedChange = methodToContext.get(e.tgt()).merge(invokeContext); // The contexts being merged could be // from different DFAs. If // so, primitive version might be // bigger. if (causedChange) { newWorklist.add(e.tgt()); } } } } worklist = newWorklist; } long longTime = ((new Date()).getTime() - start.getTime()) / 100; float time = (longTime) / 10.0f; if (dfa.printDebug()) { logger.debug("CLOA: Ending Propagation after " + time + "s"); } } public CallLocalityContext getMergedContext(SootMethod method) { if (methodToContext.containsKey(method)) { return methodToContext.get(method); } return null; } private CallLocalityContext getContextFor(Edge e, SootMethod containingMethod, CallLocalityContext containingContext) { // get new called method and calling context InvokeExpr ie; if (e.srcStmt().containsInvokeExpr()) { ie = e.srcStmt().getInvokeExpr(); } else { ie = null; } SootMethod callingMethod = e.tgt(); CallLocalityContext callingContext = new CallLocalityContext(dfa.getMethodInfoFlowSummary(callingMethod).getNodes()); // just // keeps // a // map // from // NODE // to // SHARED/LOCAL // We will use the containing context that we have to determine if base/args are local if (callingMethod.isConcrete()) { Body b = containingMethod.retrieveActiveBody(); // check base if (ie != null && ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; if (!containingMethod.isStatic() && iie.getBase().equivTo(b.getThisLocal())) { // calling another method on same object... basically copy the previous context Iterator<Object> localRefsIt = containingContext.getLocalRefs().iterator(); while (localRefsIt.hasNext()) { EquivalentValue rEqVal = (EquivalentValue) localRefsIt.next(); Ref r = (Ref) rEqVal.getValue(); if (r instanceof InstanceFieldRef) { EquivalentValue newRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(callingMethod, ((FieldRef) r).getFieldRef().resolve()); if (callingContext.containsField(newRefEqVal)) { callingContext.setFieldLocal(newRefEqVal); // must make a new eqval for the method getting called } } else if (r instanceof ThisRef) { callingContext.setThisLocal(); } } } else if (SmartMethodLocalObjectsAnalysis.isObjectLocal(dfa, containingMethod, containingContext, iie.getBase())) { // calling a method on a local object callingContext.setAllFieldsLocal(); callingContext.setThisLocal(); } else { // calling a method on a shared object callingContext.setAllFieldsShared(); callingContext.setThisShared(); } } else { callingContext.setAllFieldsShared(); callingContext.setThisShared(); } // check args if (ie == null) { callingContext.setAllParamsShared(); } else { for (int param = 0; param < ie.getArgCount(); param++) { if (SmartMethodLocalObjectsAnalysis.isObjectLocal(dfa, containingMethod, containingContext, ie.getArg(param))) { callingContext.setParamLocal(param); } else { callingContext.setParamShared(param); } } } } else { // The only conservative solution for a bodyless method is to assume everything is shared callingContext.setAllFieldsShared(); callingContext.setThisShared(); callingContext.setAllParamsShared(); } return callingContext; } public CallLocalityContext getContextFor(SootMethod sm) { return getContextFor(sm, false); } private CallLocalityContext getContextFor(SootMethod sm, boolean includePrimitiveDataFlowIfAvailable) { CallLocalityContext context; if (includePrimitiveDataFlowIfAvailable) { context = new CallLocalityContext(primitiveDfa.getMethodInfoFlowSummary(sm).getNodes()); } else { context = new CallLocalityContext(dfa.getMethodInfoFlowSummary(sm).getNodes()); } // Set context for every parameter that is shared for (int i = 0; i < sm.getParameterCount(); i++) // no need to worry about return value... { EquivalentValue paramEqVal = InfoFlowAnalysis.getNodeForParameterRef(sm, i); if (parameterIsLocal(sm, paramEqVal, includePrimitiveDataFlowIfAvailable)) { context.setParamLocal(i); } else { context.setParamShared(i); } } for (SootField sf : getLocalFields()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf); context.setFieldLocal(fieldRefEqVal); } for (SootField sf : getSharedFields()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf); context.setFieldShared(fieldRefEqVal); } return context; } public boolean isObjectLocal(Value localOrRef, SootMethod sm) { return isObjectLocal(localOrRef, sm, false); } private boolean isObjectLocal(Value localOrRef, SootMethod sm, boolean includePrimitiveDataFlowIfAvailable) { if (localOrRef instanceof StaticFieldRef) { return false; } if (dfa.printDebug()) { logger.debug(" CLOA testing if " + localOrRef + " is local in " + sm); } SmartMethodLocalObjectsAnalysis smloa = getMethodLocalObjectsAnalysis(sm, includePrimitiveDataFlowIfAvailable); if (localOrRef instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) localOrRef; if (ifr.getBase().equivTo(smloa.getThisLocal())) { return isFieldLocal(ifr.getFieldRef().resolve()); } else { // if referred object is local, then find out if field is local in that object if (isObjectLocal(ifr.getBase(), sm, includePrimitiveDataFlowIfAvailable)) { boolean retval = loa.isFieldLocalToParent(ifr.getFieldRef().resolve()); if (dfa.printDebug()) { logger.debug(" " + (retval ? "local" : "shared")); } return retval; } else { if (dfa.printDebug()) { logger.debug(" shared"); } return false; } } } // TODO Prepare a CallLocalityContext! CallLocalityContext context = getContextFor(sm); boolean retval = smloa.isObjectLocal(localOrRef, context); if (dfa.printDebug()) { logger.debug(" " + (retval ? "local" : "shared")); } return retval; } public SmartMethodLocalObjectsAnalysis getMethodLocalObjectsAnalysis(SootMethod sm) { return getMethodLocalObjectsAnalysis(sm, false); } private SmartMethodLocalObjectsAnalysis getMethodLocalObjectsAnalysis(SootMethod sm, boolean includePrimitiveDataFlowIfAvailable) { if (includePrimitiveDataFlowIfAvailable && primitiveDfa != null) { Body b = sm.retrieveActiveBody(); UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); return new SmartMethodLocalObjectsAnalysis(g, primitiveDfa); } else if (!methodToMethodLocalObjectsAnalysis.containsKey(sm)) { // Analyze this method Body b = sm.retrieveActiveBody(); UnitGraph g = ExceptionalUnitGraphFactory.createExceptionalUnitGraph(b); SmartMethodLocalObjectsAnalysis smloa = new SmartMethodLocalObjectsAnalysis(g, dfa); methodToMethodLocalObjectsAnalysis.put(sm, smloa); } return methodToMethodLocalObjectsAnalysis.get(sm); } private boolean fieldIsInitiallyLocal(SootField field) { if (field.isStatic()) { // Static fields are always shared return false; } else if (field.isPrivate()) { // Private fields may be local return true; } else { return !externalFields.contains(field); } } protected List<SootField> getSharedFields() { return (List<SootField>) sharedFields.clone(); } protected List<SootField> getLocalFields() { return (List<SootField>) localFields.clone(); } public List<SootField> getInnerSharedFields() { return sharedInnerFields; } protected boolean isFieldLocal(SootField field) { return localFields.contains(field); } protected boolean isFieldLocal(EquivalentValue fieldRef) { return localFields.contains(((SootFieldRef) fieldRef.getValue()).resolve()); } public boolean parameterIsLocal(SootMethod method, EquivalentValue parameterRef) { return parameterIsLocal(method, parameterRef, false); } protected boolean parameterIsLocal(SootMethod method, EquivalentValue parameterRef, boolean includePrimitiveDataFlowIfAvailable) { if (dfa.printDebug() && method.getDeclaringClass().isApplicationClass()) { logger.debug(" Checking PARAM " + parameterRef + " for " + method); } // Check if param is primitive or ref type ParameterRef param = (ParameterRef) parameterRef.getValue(); if (!(param.getType() instanceof RefLikeType) && (!dfa.includesPrimitiveInfoFlow() || method.getName().equals("<init>"))) // TODO // fix { if (dfa.printDebug() && method.getDeclaringClass().isApplicationClass()) { logger.debug(" PARAM is local (primitive)"); } return true; // primitive params are always considered local } // Check if method is externally called List extClassCalls = uf.getExtCalls(sootClass); Iterator extClassCallsIt = extClassCalls.iterator(); while (extClassCallsIt.hasNext()) { Pair extCall = (Pair) extClassCallsIt.next(); Stmt s = (Stmt) extCall.getO2(); if (s.getInvokeExpr().getMethodRef().resolve() == method) { if (dfa.printDebug() && method.getDeclaringClass().isApplicationClass()) { logger.debug(" PARAM is shared (external access)"); } return false; // If so, assume it's params are shared } } // For each internal call, check if arg is local or shared List intClassCalls = uf.getIntCalls(sootClass); Iterator intClassCallsIt = intClassCalls.iterator(); // returns all internal accesses while (intClassCallsIt.hasNext()) { Pair intCall = (Pair) intClassCallsIt.next(); SootMethod containingMethod = (SootMethod) intCall.getO1(); Stmt s = (Stmt) intCall.getO2(); InvokeExpr ie = s.getInvokeExpr(); if (ie.getMethodRef().resolve() == method) { if (((ParameterRef) parameterRef.getValue()).getIndex() >= 0) { if (!isObjectLocal(ie.getArg(((ParameterRef) parameterRef.getValue()).getIndex()), containingMethod, includePrimitiveDataFlowIfAvailable)) // WORST // CASE // SCENARIO // HERE // IS // INFINITE // RECURSION! { if (dfa.printDebug() && method.getDeclaringClass().isApplicationClass()) { logger.debug(" PARAM is shared (internal propagation)"); } return false; // if arg is shared for any internal call, then param is shared } } else { if (s instanceof DefinitionStmt) { Value obj = ((DefinitionStmt) s).getLeftOp(); if (!isObjectLocal(obj, containingMethod, includePrimitiveDataFlowIfAvailable)) // WORST CASE SCENARIO HERE IS // INFINITE RECURSION! { if (dfa.printDebug() && method.getDeclaringClass().isApplicationClass()) { logger.debug(" PARAM is shared (internal propagation)"); } return false; // if arg is shared for any internal call, then param is shared } } } } } if (dfa.printDebug() && method.getDeclaringClass().isApplicationClass()) { logger.debug(" PARAM is local SO FAR (internal propagation)"); } return true; // if argument is always local, then parameter is local } // TODO: SOUND/UNSOUND??? protected boolean thisIsLocal(SootMethod method, EquivalentValue thisRef) { return true; } }
35,386
39.166856
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/FakeJimpleLocal.java
package soot.jimple.toolkits.infoflow; /*- * #%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.Type; import soot.jimple.internal.JimpleLocal; // A wrapper for a JimpleLocal that defines equivalence and equality // as having the same name and type. This is useful for comparing // InstanceFieldRefs and ArrayRefs from different parts of a program // (without removing the FieldRef part, which is not a Jimple Value). // FakeJimpleLocal can also hold a real JimpleLocal // and some additional object, which together can make it easier to // later reconstruct the original piece of Jimple code, or to construct // a new meaningful piece of Jimple code base on this one. public class FakeJimpleLocal extends JimpleLocal { Local realLocal; Object info; // whatever you want to attach to it... /** Constructs a FakeJimpleLocal of the given name and type. */ public FakeJimpleLocal(String name, Type t, Local realLocal) { this(name, t, realLocal, null); } public FakeJimpleLocal(String name, Type t, Local realLocal, Object info) { super(name, t); this.realLocal = realLocal; this.info = info; } /** Returns true if the given object is structurally equal to this one. */ public boolean equivTo(Object o) { if (o == null) { return false; } if (o instanceof JimpleLocal) { if (getName() != null && getType() != null) { return getName().equals(((Local) o).getName()) && getType().equals(((Local) o).getType()); } else if (getName() != null) { return getName().equals(((Local) o).getName()) && ((Local) o).getType() == null; } else if (getType() != null) { return ((Local) o).getName() == null && getType().equals(((Local) o).getType()); } else { return ((Local) o).getName() == null && ((Local) o).getType() == null; } } return false; } public boolean equals(Object o) { return equivTo(o); } /** Returns a clone of the current JimpleLocal. */ public Object clone() { return new FakeJimpleLocal(getName(), getType(), realLocal, info); } public Local getRealLocal() { return realLocal; } public Object getInfo() { return info; } public void setInfo(Object o) { info = o; } }
3,034
31.634409
98
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/InfoFlowAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.EquivalentValue; import soot.Local; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.SootMethodRef; import soot.Value; import soot.jimple.FieldRef; import soot.jimple.InvokeExpr; import soot.jimple.Jimple; import soot.jimple.ParameterRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.HashMutableDirectedGraph; import soot.toolkits.graph.MutableDirectedGraph; import soot.util.dot.DotGraph; import soot.util.dot.DotGraphConstants; // InfoFlowAnalysis written by Richard L. Halpert, 2007-02-24 // Constructs data flow tables for each method of every application class. Ignores indirect flow. // These tables conservatively approximate how data flows from parameters, // fields, and globals to parameters, fields, globals, and the return value. // Note that a ref-type parameter (or field or global) might allow access to a // large data structure, but that entire structure will be represented only by // the parameter's one node in the data flow graph. // Provides a high level interface to access the data flow information. public class InfoFlowAnalysis { private static final Logger logger = LoggerFactory.getLogger(InfoFlowAnalysis.class); boolean includePrimitiveInfoFlow; boolean includeInnerFields; boolean printDebug; Map<SootClass, ClassInfoFlowAnalysis> classToClassInfoFlowAnalysis; public InfoFlowAnalysis(boolean includePrimitiveDataFlow, boolean includeInnerFields) { this(includePrimitiveDataFlow, includeInnerFields, false); } public InfoFlowAnalysis(boolean includePrimitiveDataFlow, boolean includeInnerFields, boolean printDebug) { this.includePrimitiveInfoFlow = includePrimitiveDataFlow; this.includeInnerFields = includeInnerFields; this.printDebug = printDebug; classToClassInfoFlowAnalysis = new HashMap<SootClass, ClassInfoFlowAnalysis>(); } public boolean includesPrimitiveInfoFlow() { return includePrimitiveInfoFlow; } public boolean includesInnerFields() { return includeInnerFields; } public boolean printDebug() { return printDebug; } /* * public void doApplicationClassesAnalysis() { Iterator appClassesIt = Scene.v().getApplicationClasses().iterator(); while * (appClassesIt.hasNext()) { SootClass appClass = (SootClass) appClassesIt.next(); * * // Create the needed flow analysis object ClassInfoFlowAnalysis cdfa = new ClassInfoFlowAnalysis(appClass, this); * * // Put the preliminary flow-insensitive results here in case they // are needed by the flow-sensitive version. This * method will be // reentrant if any method we are analyzing is reentrant, so we // must do this to prevent an infinite * recursive loop. classToClassInfoFlowAnalysis.put(appClass, cdfa); } * * Iterator appClassesIt2 = Scene.v().getApplicationClasses().iterator(); while (appClassesIt2.hasNext()) { SootClass * appClass = (SootClass) appClassesIt2.next(); // Now calculate the flow-sensitive version. If this classes methods // are * reentrant, it will call this method and receive the flow // insensitive version that is already cached. * ClassInfoFlowAnalysis cdfa = (ClassInfoFlowAnalysis) classToClassInfoFlowAnalysis.get(appClass); * cdfa.doFixedPointDataFlowAnalysis(); } } */ private ClassInfoFlowAnalysis getClassInfoFlowAnalysis(SootClass sc) { if (!classToClassInfoFlowAnalysis.containsKey(sc)) { ClassInfoFlowAnalysis cdfa = new ClassInfoFlowAnalysis(sc, this); classToClassInfoFlowAnalysis.put(sc, cdfa); } return classToClassInfoFlowAnalysis.get(sc); } public SmartMethodInfoFlowAnalysis getMethodInfoFlowAnalysis(SootMethod sm) { ClassInfoFlowAnalysis cdfa = getClassInfoFlowAnalysis(sm.getDeclaringClass()); return cdfa.getMethodInfoFlowAnalysis(sm); } /** * Returns a BACKED MutableDirectedGraph whose nodes are EquivalentValue wrapped Refs. It's perfectly safe to modify this * graph, just so long as new nodes are EquivalentValue wrapped Refs. */ public HashMutableDirectedGraph<EquivalentValue> getMethodInfoFlowSummary(SootMethod sm) { return getMethodInfoFlowSummary(sm, true); } public HashMutableDirectedGraph<EquivalentValue> getMethodInfoFlowSummary(SootMethod sm, boolean doFullAnalysis) { ClassInfoFlowAnalysis cdfa = getClassInfoFlowAnalysis(sm.getDeclaringClass()); return cdfa.getMethodInfoFlowSummary(sm, doFullAnalysis); } /** * Returns an unmodifiable list of EquivalentValue wrapped Refs that source flows to when method sm is called. */ /* * public List getSinksOf(SootMethod sm, EquivalentValue source) { ClassInfoFlowAnalysis cdfa = * getClassDataFlowAnalysis(sm.getDeclaringClass()); MutableDirectedGraph g = cdfa.getMethodDataFlowGraph(sm); List sinks = * null; if(g.containsNode(source)) sinks = g.getSuccsOf(source); else sinks = new ArrayList(); return sinks; } */ /** * Returns an unmodifiable list of EquivalentValue wrapped Refs that sink flows from when method sm is called. */ /* * public List getSourcesOf(SootMethod sm, EquivalentValue sink) { ClassInfoFlowAnalysis cdfa = * getClassDataFlowAnalysis(sm.getDeclaringClass()); MutableDirectedGraph g = cdfa.getMethodDataFlowGraph(sm); List sources * = null; if(g.containsNode(sink)) sources = g.getPredsOf(sink); else sources = new ArrayList(); return sources; } */ // Returns an EquivalentValue wrapped Ref based on sfr // that is suitable for comparison to the nodes of a Data Flow Graph public static EquivalentValue getNodeForFieldRef(SootMethod sm, SootField sf) { return getNodeForFieldRef(sm, sf, null); } public static EquivalentValue getNodeForFieldRef(SootMethod sm, SootField sf, Local realLocal) { if (sf.isStatic()) { return new CachedEquivalentValue(Jimple.v().newStaticFieldRef(sf.makeRef())); } else { // Jimple.v().newThisRef(sf.getDeclaringClass().getType()) if (sm.isConcrete() && !sm.isStatic() && sm.getDeclaringClass() == sf.getDeclaringClass() && realLocal == null) { JimpleLocal fakethis = new FakeJimpleLocal("fakethis", sf.getDeclaringClass().getType(), sm.retrieveActiveBody().getThisLocal()); return new CachedEquivalentValue(Jimple.v().newInstanceFieldRef(fakethis, sf.makeRef())); // fake thisLocal } else { // Pretends to be a this.<somefield> ref for a method without a body, // for a static method, or for an inner field JimpleLocal fakethis = new FakeJimpleLocal("fakethis", sf.getDeclaringClass().getType(), realLocal); return new CachedEquivalentValue(Jimple.v().newInstanceFieldRef(fakethis, sf.makeRef())); // fake thisLocal } } } // Returns an EquivalentValue wrapped Ref for @parameter i // that is suitable for comparison to the nodes of a Data Flow Graph public static EquivalentValue getNodeForParameterRef(SootMethod sm, int i) { return new CachedEquivalentValue(new ParameterRef(sm.getParameterType(i), i)); } // Returns an EquivalentValue wrapped Ref for the return value // that is suitable for comparison to the nodes of a Data Flow Graph public static EquivalentValue getNodeForReturnRef(SootMethod sm) { return new CachedEquivalentValue(new ParameterRef(sm.getReturnType(), -1)); } // Returns an EquivalentValue wrapped ThisRef // that is suitable for comparison to the nodes of a Data Flow Graph public static EquivalentValue getNodeForThisRef(SootMethod sm) { return new CachedEquivalentValue(new ThisRef(sm.getDeclaringClass().getType())); } protected HashMutableDirectedGraph<EquivalentValue> getInvokeInfoFlowSummary(InvokeExpr ie, Stmt is, SootMethod context) { // get the data flow graph for each possible target of ie, // then combine them conservatively and return the result. HashMutableDirectedGraph<EquivalentValue> ret = null; SootMethodRef methodRef = ie.getMethodRef(); String subSig = methodRef.resolve().getSubSignature(); CallGraph cg = Scene.v().getCallGraph(); for (Iterator<Edge> edges = cg.edgesOutOf(is); edges.hasNext();) { Edge e = edges.next(); SootMethod target = e.getTgt().method(); // Verify that this target is an implementation of the method we intend to call, // and not just a class initializer or other unintended control flow. if (target.getSubSignature().equals(subSig)) { HashMutableDirectedGraph<EquivalentValue> ifs = getMethodInfoFlowSummary(target, context.getDeclaringClass().isApplicationClass()); if (ret == null) { ret = ifs; } else { for (EquivalentValue node : ifs.getNodes()) { if (!ret.containsNode(node)) { ret.addNode(node); } for (EquivalentValue succ : ifs.getSuccsOf(node)) { ret.addEdge(node, succ); } } } } } return ret; // return getMethodInfoFlowSummary(methodRef.resolve(), context.getDeclaringClass().isApplicationClass()); } protected MutableDirectedGraph<EquivalentValue> getInvokeAbbreviatedInfoFlowGraph(InvokeExpr ie, SootMethod context) { // get the data flow graph for each possible target of ie, // then combine them conservatively and return the result. SootMethodRef methodRef = ie.getMethodRef(); return getMethodInfoFlowAnalysis(methodRef.resolve()).getMethodAbbreviatedInfoFlowGraph(); } public static void printInfoFlowSummary(DirectedGraph<EquivalentValue> g) { if (g.size() > 0) { logger.debug(" " + " --> "); } for (EquivalentValue node : g) { List<EquivalentValue> sources = g.getPredsOf(node); if (sources.isEmpty()) { continue; } logger.debug(" [ "); int sourcesnamelength = 0; int lastnamelength = 0; int idx = 0; for (EquivalentValue t : sources) { Value v = t.getValue(); if (v instanceof FieldRef) { FieldRef fr = (FieldRef) v; String name = fr.getFieldRef().name(); lastnamelength = name.length(); if (lastnamelength > sourcesnamelength) { sourcesnamelength = lastnamelength; } logger.debug("" + name); } else if (v instanceof ParameterRef) { ParameterRef pr = (ParameterRef) v; lastnamelength = 11; if (lastnamelength > sourcesnamelength) { sourcesnamelength = lastnamelength; } logger.debug("@parameter" + pr.getIndex()); } else { String name = v.toString(); lastnamelength = name.length(); if (lastnamelength > sourcesnamelength) { sourcesnamelength = lastnamelength; } logger.debug("" + name); } if ((idx++) < sources.size()) { logger.debug("\n "); } } for (int i = 0; i < sourcesnamelength - lastnamelength; i++) { logger.debug(" "); } logger.debug(" ] --> " + node.toString()); } } public static void printGraphToDotFile(String filename, DirectedGraph<EquivalentValue> graph, String graphname, boolean onePage) { // this makes the node name unique nodecount = 0; // reset node counter first. // file name is the method name + .dot DotGraph canvas = new DotGraph(filename); if (!onePage) { canvas.setPageSize(8.5, 11.0); } canvas.setNodeShape(DotGraphConstants.NODE_SHAPE_BOX); canvas.setGraphLabel(graphname); for (EquivalentValue node : graph) { canvas.drawNode(getNodeName(node)); canvas.getNode(getNodeName(node)).setLabel(getNodeLabel(node)); for (EquivalentValue s : graph.getSuccsOf(node)) { canvas.drawNode(getNodeName(s)); canvas.getNode(getNodeName(s)).setLabel(getNodeLabel(s)); canvas.drawEdge(getNodeName(node), getNodeName(s)); } } canvas.plot(filename + ".dot"); } static int nodecount = 0; // static Map nodeToNodeName = new HashMap(); public static String getNodeName(Object o) { // if(!nodeToNodeName.containsKey(o)) // Since this uses all different kinds of objects, we // // were getting weird collisions, causing wrong graphs. // nodeToNodeName.put(o, "N" + (nodecount++)); // // return (String) nodeToNodeName.get(o); return getNodeLabel(o); } public static String getNodeLabel(Object o) { Value node = ((EquivalentValue) o).getValue(); /* * if(node instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) node; if(ifr.getBase() instanceof * FakeJimpleLocal) return ifr.getField().getDeclaringClass().getShortName() + "." + ifr.getFieldRef().name(); else * return ifr.getField().getDeclaringClass().getShortName() + "." + ifr.getFieldRef().name(); } else */ if (node instanceof FieldRef) { FieldRef fr = (FieldRef) node; return fr.getField().getDeclaringClass().getShortName() + "." + fr.getFieldRef().name(); } return node.toString(); } }
14,265
40.350725
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/LocalObjectsAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.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.EquivalentValue; import soot.Local; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Value; import soot.jimple.FieldRef; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.graph.MutableDirectedGraph; import soot.toolkits.scalar.Pair; // LocalObjectsAnalysis written by Richard L. Halpert, 2007-02-24 // Constructs data flow tables for each method of every application class. Ignores indirect flow. // These tables conservatively approximate how data flows from parameters, // fields, and globals to parameters, fields, globals, and the return value. // Note that a ref-type parameter (or field or global) might allow access to a // large data structure, but that entire structure will be represented only by // the parameter's one node in the data flow graph. // Provides a high level interface to access the data flow information. public class LocalObjectsAnalysis { private static final Logger logger = LoggerFactory.getLogger(LocalObjectsAnalysis.class); public InfoFlowAnalysis dfa; UseFinder uf; CallGraph cg; Map<SootClass, ClassLocalObjectsAnalysis> classToClassLocalObjectsAnalysis; Map<SootMethod, SmartMethodLocalObjectsAnalysis> mloaCache; public LocalObjectsAnalysis(InfoFlowAnalysis dfa) { this.dfa = dfa; this.uf = new UseFinder(); this.cg = Scene.v().getCallGraph(); classToClassLocalObjectsAnalysis = new HashMap<SootClass, ClassLocalObjectsAnalysis>(); mloaCache = new HashMap<SootMethod, SmartMethodLocalObjectsAnalysis>(); } public ClassLocalObjectsAnalysis getClassLocalObjectsAnalysis(SootClass sc) { if (!classToClassLocalObjectsAnalysis.containsKey(sc)) { ClassLocalObjectsAnalysis cloa = newClassLocalObjectsAnalysis(this, dfa, uf, sc); classToClassLocalObjectsAnalysis.put(sc, cloa); } return classToClassLocalObjectsAnalysis.get(sc); } // meant to be overridden by specialty local objects analyses protected ClassLocalObjectsAnalysis newClassLocalObjectsAnalysis(LocalObjectsAnalysis loa, InfoFlowAnalysis dfa, UseFinder uf, SootClass sc) { return new ClassLocalObjectsAnalysis(loa, dfa, uf, sc); } public boolean isObjectLocalToParent(Value localOrRef, SootMethod sm) { // Handle obvious case if (localOrRef instanceof StaticFieldRef) { return false; } ClassLocalObjectsAnalysis cloa = getClassLocalObjectsAnalysis(sm.getDeclaringClass()); return cloa.isObjectLocal(localOrRef, sm); } public boolean isFieldLocalToParent(SootField sf) // To parent class! { // Handle obvious case if (sf.isStatic()) { return false; } ClassLocalObjectsAnalysis cloa = getClassLocalObjectsAnalysis(sf.getDeclaringClass()); return cloa.isFieldLocal(sf); } public boolean isObjectLocalToContext(Value localOrRef, SootMethod sm, SootMethod context) { // Handle special case if (sm == context) { // logger.debug(" Directly Reachable: "); boolean isLocal = isObjectLocalToParent(localOrRef, sm); if (dfa.printDebug()) { logger.debug(" " + (isLocal ? "LOCAL (Directly Reachable from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")" : "SHARED (Directly Reachable from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")")); } return isLocal; } // Handle obvious case if (localOrRef instanceof StaticFieldRef) { if (dfa.printDebug()) { logger.debug(" SHARED (Static from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } return false; } // Handle uncheckable case if (!sm.isConcrete()) { // no way to tell... and how do we have access to a Local anyways??? throw new RuntimeException("Attempted to check if a local variable in a non-concrete method is shared/local."); } // For Resulting Merged Context, check if localOrRef is local Body b = sm.retrieveActiveBody(); // sm is guaranteed concrete (see above) // Check if localOrRef is Local in smContext /* * SmartMethodLocalObjectsAnalysis mloa = null; // Pair mloaKey = new Pair(sm, mergedContext); if( * mloaCache.containsKey(sm) ) { mloa = (SmartMethodLocalObjectsAnalysis) mloaCache.get(sm); // * logger.debug(" Retrieved mloa From Cache: "); } else { UnitGraph g = new ExceptionalUnitGraph(b); mloa = new * SmartMethodLocalObjectsAnalysis(g, dfa); // logger.debug(" Caching mloa (smdfa " + * SmartMethodInfoFlowAnalysis.counter + // " smloa " + SmartMethodLocalObjectsAnalysis.counter + ") for " + sm.getName() * + " on goal:"); mloaCache.put(sm, mloa); } // */ CallLocalityContext mergedContext = getClassLocalObjectsAnalysis(context.getDeclaringClass()).getMergedContext(sm); if (mergedContext == null) { if (dfa.printDebug()) { logger.debug(" ------ (Unreachable from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } return true; // it's not non-local... } // with the completed mergedContext... // localOrRef can actually be a field ref if (localOrRef instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) localOrRef; Local thisLocal = null; try { thisLocal = b.getThisLocal(); } catch (RuntimeException re) { /* Couldn't get thisLocal */ } if (ifr.getBase() == thisLocal) { boolean isLocal = mergedContext.isFieldLocal(InfoFlowAnalysis.getNodeForFieldRef(sm, ifr.getField())); if (dfa.printDebug()) { if (isLocal) { logger.debug(" LOCAL (this .localField from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } else { logger.debug(" SHARED (this .sharedField from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } } return isLocal; } else { boolean isLocal = SmartMethodLocalObjectsAnalysis.isObjectLocal(dfa, sm, mergedContext, ifr.getBase()); if (isLocal) { ClassLocalObjectsAnalysis cloa = getClassLocalObjectsAnalysis(context.getDeclaringClass()); isLocal = !cloa.getInnerSharedFields().contains(ifr.getField()); if (dfa.printDebug()) { if (isLocal) { logger.debug(" LOCAL (local .localField from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } else { logger.debug(" SHARED (local .sharedField from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } } return isLocal; } else { if (dfa.printDebug()) { logger.debug(" SHARED (shared.someField from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } return isLocal; } } } boolean isLocal = SmartMethodLocalObjectsAnalysis.isObjectLocal(dfa, sm, mergedContext, localOrRef); if (dfa.printDebug()) { if (isLocal) { logger.debug(" LOCAL ( local from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } else { logger.debug(" SHARED (shared from " + context.getDeclaringClass().getShortName() + "." + context.getName() + ")"); } } return isLocal; } /* * BROKEN public boolean isFieldLocalToContext(SootField sf, SootMethod sm, SootClass context) { * logger.debug(" Checking if " + sf + " in " + sm + " is local to " + context + ":"); * * if(sm.getDeclaringClass() == context) // special case { boolean isLocal = isFieldLocalToParent(sf); * logger.debug(" Directly Reachable: " + (isLocal ? "LOCAL" : "SHARED")); return isLocal; } * * // The rest of the time, we must find all call chains from context to sm // if it's local on all of them, then return * true. * * // Find Call Chains (separate chains for separate possible virtual call targets) // TODO right now we discard reentrant * call chains... but this is UNSAFE // TODO right now we are stupid about virtual calls... but this is UNSAFE * * // for each method in the context class (OR JUST FROM THE RUN METHOD IF IT'S A THREAD?) List classMethods = * getAllMethodsForClass(context); // gets methods in context class and superclasses List callChains = new ArrayList(); * List startingMethods = new ArrayList(); Iterator classMethodsIt = classMethods.iterator(); * while(classMethodsIt.hasNext()) { SootMethod classMethod = (SootMethod) classMethodsIt.next(); List methodCallChains = * getCallChainsBetween(classMethod, sm); Iterator methodCallChainsIt = methodCallChains.iterator(); * while(methodCallChainsIt.hasNext()) { callChains.add(methodCallChainsIt.next()); startingMethods.add(classMethod); // * need to add this once for each method call chain being added } } * * if(callChains.size() == 0) { logger.debug(" Unreachable: treat as local."); return true; // it's not non-local... } * logger.debug(" Found " + callChains.size() + " Call Chains..."); // for(int i = 0; i < callChains.size(); i++) // * logger.debug(" " + callChains.get(i)); * * // Check Call Chains for(int i = 0; i < callChains.size(); i++) { List callChain = (List) callChains.get(i); * if(!isFieldLocalToContextViaCallChain(sf, sm, context, (SootMethod) startingMethods.get(i), callChain)) { * logger.debug(" SHARED"); return false; } } logger.debug(" LOCAL"); return true; } */ Map<SootMethod, ReachableMethods> rmCache = new HashMap<SootMethod, ReachableMethods>(); public CallChain getNextCallChainBetween(SootMethod start, SootMethod goal, List previouslyFound) { // callChains.add(new LinkedList()); // Represents the one way to get from goal to goal (which is to already be there) // Is this worthwhile? Fast? Slow? Broken? Applicable inside the recursive method? // If method is unreachable, don't bother trying to make chains // CACHEABLE? ReachableMethods rm = null; if (rmCache.containsKey(start)) { rm = rmCache.get(start); } else { List<MethodOrMethodContext> entryPoints = new ArrayList<MethodOrMethodContext>(); entryPoints.add(start); rm = new ReachableMethods(cg, entryPoints); rm.update(); rmCache.put(start, rm); } if (rm.contains(goal)) { // Set methodsInAnyChain = new HashSet(); // methodsInAnyChain.add(goal); return getNextCallChainBetween(rm, start, goal, null, null, previouslyFound); } return null; // new ArrayList(); } Map callChainsCache = new HashMap(); public CallChain getNextCallChainBetween(ReachableMethods rm, SootMethod start, SootMethod end, Edge endToPath, CallChain path, List previouslyFound) { Pair cacheKey = new Pair(start, end); if (callChainsCache.containsKey(cacheKey)) { // logger.debug("C"); return null; // return (CallChain) callChainsCache.get(cacheKey); } path = new CallChain(endToPath, path); // initially, path and endToPath can be null if (start == end) { // if(previouslyFound.contains(path)) // don't return a call chain that was already returned in a previous run // { // logger.debug("P"); // return null; // } // logger.debug("F"); return path; // List ret = new ArrayList(); // ret.add(path); // logger.debug("F"); // return ret; } if (!rm.contains(end)) { // logger.debug("U"); return null; // new ArrayList(); // no paths } // List paths = new ArrayList(); // no paths Iterator edgeIt = cg.edgesInto(end); while (edgeIt.hasNext()) { Edge e = (Edge) edgeIt.next(); SootMethod node = e.src(); if (!path.containsMethod(node) && e.isExplicit() && e.srcStmt().containsInvokeExpr()) { // logger.debug("R"); CallChain newpath = getNextCallChainBetween(rm, start, node, e, path, previouslyFound); // node is supposed to be a // method if (newpath != null) { // logger.debug("|"); if (!previouslyFound.contains(newpath)) { return newpath; } } // Iterator newpathsIt = newpaths.iterator(); // while(newpathsIt.hasNext()) // { // paths.addAll(newpaths); // } } else { // logger.debug("S"); } } // logger.debug("(" + paths.size() + ")"); // if(paths.size() < 100) if (previouslyFound.size() == 0) { callChainsCache.put(cacheKey, null); } // logger.debug("|"); return null; } /* * // callChains go from current to goal public void getCallChainsBetween(SootMethod start, SootMethod current, SootMethod * goal, ReachableMethods rm, List callChains, Set methodsInAnyChain) { List oldCallChains = new ArrayList(); * oldCallChains.addAll(callChains); callChains.clear(); * * Pair cacheKey = new Pair(start, current); if(callChainsCache.containsKey(cacheKey)) { List cachedChains = (List) * callChainsCache.get(cacheKey); * * Iterator cachedChainsIt = cachedChains.iterator(); while(cachedChainsIt.hasNext()) { CallChain cachedChain = (CallChain) * cachedChainsIt.next(); Iterator oldCallChainsIt = oldCallChains.iterator(); while(oldCallChainsIt.hasNext()) { CallChain * oldChain = (CallChain) oldCallChainsIt.next(); callChains.add(cachedChain.cloneAndExtend(oldChain)); } } * * // We now have chains from start to goal * * logger.debug("C"); return; } * * // For each edge into goal, clone the existing call chains and add that edge to the beginning, then call self with new * goal Iterator edgeIt = cg.edgesInto(current); while(edgeIt.hasNext()) { Edge e = (Edge) edgeIt.next(); // Stmt * currentCallerStmt = e.srcStmt(); SootMethod currentCaller = e.src(); * * // If the source of this edge is unreachable, ignore it if( !rm.contains(currentCaller) ) { logger.debug("U"); continue; * } * * // If this would introduce an SCC, skip it (TODO: Deal with it, instead) boolean currentCallerIsAlreadyInAChain = false; * Iterator oldCallChainsIt = oldCallChains.iterator(); while(oldCallChainsIt.hasNext()) { CallChain oldCallChain = * (CallChain) oldCallChainsIt.next(); if(oldCallChain.containsMethod(currentCaller)) { currentCallerIsAlreadyInAChain = * true; break; } } * * if( ( currentCaller == goal ) || currentCallerIsAlreadyInAChain) // methodsInAnyChain.contains(goalCaller) ) { * logger.debug("S"); continue; // if this goalCaller would be an SCC, ignore it } * * // If this is the type of edge that we'd like to include in our call chains if(e.isExplicit())// && * goalCallerStmt.containsInvokeExpr()) { // Make a copy of all call chains // List newCallChains = * cloneCallChains(oldCallChains); List newCallChains = new ArrayList(); * * if(oldCallChains.size() == 0) { newCallChains.add(new CallChain(e, null)); } else { // Add this edge to each call chain * oldCallChainsIt = oldCallChains.iterator(); while(oldCallChainsIt.hasNext()) { CallChain oldCallChain = (CallChain) * oldCallChainsIt.next(); newCallChains.add(new CallChain(e, oldCallChain)); } } * * // methodsInAnyChain.add(goalCaller); * * // If the call chains don't now start from start, then get ones that do (recursively) if(currentCaller != start) { * logger.debug("R"); * * // Call self to extend these new call chains all the way to start getCallChainsBetween(start, currentCaller, goal, rm, * newCallChains, methodsInAnyChain); } else { logger.debug("F"); } * * // Add all the new call chains to our set callChains.addAll(newCallChains); } } logger.debug("(" + callChains.size() + * ")"); if(callChains.size() > 0) callChainsCache.put(new Pair(start, goal), callChains); } */ /* * // returns a 1-deep clone of a List of Lists private List cloneCallChains(List callChains) { List ret = new ArrayList(); * Iterator callChainsIt = callChains.iterator(); while(callChainsIt.hasNext()) ret.add( ((LinkedList) * callChainsIt.next()).clone() ); // add a clone of each call chain return ret; } */ /* * public List getCallChainsBetween(SootMethod start, SootMethod goal) { logger.debug("Q"); List callChains = new * ArrayList(); Iterator edgeIt = cg.edgesInto(goal); while(edgeIt.hasNext()) { Edge e = (Edge) edgeIt.next(); Stmt * goalCallerStmt = e.srcStmt(); SootMethod goalCaller = e.src(); if(e.isExplicit() && goalCallerStmt.containsInvokeExpr()) * // if not, we're not interested { List edgeCallChains = null; if(goalCaller == start) { edgeCallChains = new * ArrayList(); edgeCallChains.add(new LinkedList()); } else { edgeCallChains = getCallChainsBetween(start, goalCaller); } * * Pair pair = new Pair(new EquivalentValue(goalCallerStmt.getInvokeExpr()), goal); Iterator edgeCallChainsIt = * edgeCallChains.iterator(); while(edgeCallChainsIt.hasNext()) { List edgeCallChain = (List) edgeCallChainsIt.next(); if( * !edgeCallChain.contains(pair) ) // SCC, we must ignore, sadly... TODO FIX THIS { edgeCallChain.add(pair); * callChains.add(edgeCallChain); } } } } return callChains; } */ // returns a list of all methods that can be invoked on an object of type sc public List<SootMethod> getAllMethodsForClass(SootClass sootClass) { // Determine which methods are reachable in this program ReachableMethods rm = Scene.v().getReachableMethods(); // Get list of reachable methods declared in this class // Also get list of fields declared in this class List<SootMethod> scopeMethods = new ArrayList<SootMethod>(); Iterator scopeMethodsIt = sootClass.methodIterator(); while (scopeMethodsIt.hasNext()) { SootMethod scopeMethod = (SootMethod) scopeMethodsIt.next(); if (rm.contains(scopeMethod)) { scopeMethods.add(scopeMethod); } } // Add reachable methods and fields declared in superclasses SootClass superclass = sootClass; if (superclass.hasSuperclass()) { superclass = sootClass.getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { Iterator scMethodsIt = superclass.methodIterator(); while (scMethodsIt.hasNext()) { SootMethod scMethod = (SootMethod) scMethodsIt.next(); if (rm.contains(scMethod)) { scopeMethods.add(scMethod); } } superclass = superclass.getSuperclass(); } return scopeMethods; } public boolean hasNonLocalEffects(SootMethod containingMethod, InvokeExpr ie, SootMethod context) { SootMethod target = ie.getMethodRef().resolve(); MutableDirectedGraph dataFlowGraph = dfa.getMethodInfoFlowSummary(target); // TODO actually we want a graph that is // sensitive to scalar data, too // For a static invoke, check if any fields or any shared params are read/written if (ie instanceof StaticInvokeExpr) { Iterator graphIt = dataFlowGraph.iterator(); while (graphIt.hasNext()) { EquivalentValue nodeEqVal = (EquivalentValue) graphIt.next(); Ref node = (Ref) nodeEqVal.getValue(); if (node instanceof FieldRef) { if (dataFlowGraph.getPredsOf(nodeEqVal).size() > 0 || dataFlowGraph.getSuccsOf(nodeEqVal).size() > 0) { return true; } } else if (node instanceof ParameterRef) { if (dataFlowGraph.getPredsOf(nodeEqVal).size() > 0 || dataFlowGraph.getSuccsOf(nodeEqVal).size() > 0) { ParameterRef pr = (ParameterRef) node; if (pr.getIndex() != -1) { if (!isObjectLocalToContext(ie.getArg(pr.getIndex()), containingMethod, context)) { return true; } } } } } } else if (ie instanceof InstanceInvokeExpr) { // For a instance invoke on local object, check if any static fields or any shared params are read/written InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; if (isObjectLocalToContext(iie.getBase(), containingMethod, context)) { Iterator graphIt = dataFlowGraph.iterator(); while (graphIt.hasNext()) { EquivalentValue nodeEqVal = (EquivalentValue) graphIt.next(); Ref node = (Ref) nodeEqVal.getValue(); if (node instanceof StaticFieldRef) { if (dataFlowGraph.getPredsOf(nodeEqVal).size() > 0 || dataFlowGraph.getSuccsOf(nodeEqVal).size() > 0) { return true; } } else if (node instanceof ParameterRef) { if (dataFlowGraph.getPredsOf(nodeEqVal).size() > 0 || dataFlowGraph.getSuccsOf(nodeEqVal).size() > 0) { ParameterRef pr = (ParameterRef) node; if (pr.getIndex() != -1) { if (!isObjectLocalToContext(ie.getArg(pr.getIndex()), containingMethod, context)) { return true; } } } } } } // For a instance invoke on shared object, check if any fields or any shared params are read/written else { Iterator graphIt = dataFlowGraph.iterator(); while (graphIt.hasNext()) { EquivalentValue nodeEqVal = (EquivalentValue) graphIt.next(); Ref node = (Ref) nodeEqVal.getValue(); if (node instanceof FieldRef) { if (dataFlowGraph.getPredsOf(nodeEqVal).size() > 0 || dataFlowGraph.getSuccsOf(nodeEqVal).size() > 0) { return true; } } else if (node instanceof ParameterRef) { if (dataFlowGraph.getPredsOf(nodeEqVal).size() > 0 || dataFlowGraph.getSuccsOf(nodeEqVal).size() > 0) { ParameterRef pr = (ParameterRef) node; if (pr.getIndex() != -1) { if (!isObjectLocalToContext(ie.getArg(pr.getIndex()), containingMethod, context)) { return true; } } } } } } } return false; } }
23,998
44.026266
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/SimpleMethodInfoFlowAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.ArrayList; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.EquivalentValue; import soot.Local; import soot.RefLikeType; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Type; 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.CastExpr; import soot.jimple.Constant; import soot.jimple.IdentityRef; import soot.jimple.IdentityStmt; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InstanceOfExpr; import soot.jimple.InvokeExpr; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.ReturnStmt; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.UnopExpr; import soot.jimple.internal.JCaughtExceptionRef; import soot.toolkits.graph.MemoryEfficientGraph; import soot.toolkits.graph.MutableDirectedGraph; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ArraySparseSet; import soot.toolkits.scalar.FlowSet; import soot.toolkits.scalar.ForwardFlowAnalysis; import soot.toolkits.scalar.Pair; // SimpleMethodInfoFlowAnalysis written by Richard L. Halpert, 2007-02-25 // Constructs a data flow table for the given method. Ignores indirect flow. // These tables conservatively approximate how data flows from parameters, // fields, and globals to parameters, fields, globals, and the return value. // Note that a ref-type parameter (or field or global) might allow access to a // large data structure, but that entire structure will be represented only by // the parameter's one node in the data flow graph. public class SimpleMethodInfoFlowAnalysis extends ForwardFlowAnalysis<Unit, FlowSet<Pair<EquivalentValue, EquivalentValue>>> { private static final Logger logger = LoggerFactory.getLogger(SimpleMethodInfoFlowAnalysis.class); SootMethod sm; Value thisLocal; InfoFlowAnalysis dfa; boolean refOnly; MutableDirectedGraph<EquivalentValue> infoFlowGraph; Ref returnRef; FlowSet<Pair<EquivalentValue, EquivalentValue>> entrySet; FlowSet<Pair<EquivalentValue, EquivalentValue>> emptySet; boolean printMessages; public static int counter = 0; public SimpleMethodInfoFlowAnalysis(UnitGraph g, InfoFlowAnalysis dfa, boolean ignoreNonRefTypeFlow) { this(g, dfa, ignoreNonRefTypeFlow, true); counter++; // Add all of the nodes necessary to ensure that this is a complete data flow graph // Add every parameter of this method for (int i = 0; i < sm.getParameterCount(); i++) { EquivalentValue parameterRefEqVal = InfoFlowAnalysis.getNodeForParameterRef(sm, i); if (!infoFlowGraph.containsNode(parameterRefEqVal)) { infoFlowGraph.addNode(parameterRefEqVal); } } // Add every field of this class for (SootField sf : sm.getDeclaringClass().getFields()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf); if (!infoFlowGraph.containsNode(fieldRefEqVal)) { infoFlowGraph.addNode(fieldRefEqVal); } } // Add every field of this class's superclasses SootClass superclass = sm.getDeclaringClass(); if (superclass.hasSuperclass()) { superclass = sm.getDeclaringClass().getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { for (SootField scField : superclass.getFields()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, scField); if (!infoFlowGraph.containsNode(fieldRefEqVal)) { infoFlowGraph.addNode(fieldRefEqVal); } } superclass = superclass.getSuperclass(); } // Add thisref of this class EquivalentValue thisRefEqVal = InfoFlowAnalysis.getNodeForThisRef(sm); if (!infoFlowGraph.containsNode(thisRefEqVal)) { infoFlowGraph.addNode(thisRefEqVal); } // Add returnref of this method EquivalentValue returnRefEqVal = new CachedEquivalentValue(returnRef); if (!infoFlowGraph.containsNode(returnRefEqVal)) { infoFlowGraph.addNode(returnRefEqVal); } if (printMessages) { logger.debug("STARTING ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } doFlowInsensitiveAnalysis(); if (printMessages) { logger.debug("ENDING ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } } /** A constructor that doesn't run the analysis */ protected SimpleMethodInfoFlowAnalysis(UnitGraph g, InfoFlowAnalysis dfa, boolean ignoreNonRefTypeFlow, boolean dummyDontRunAnalysisYet) { super(g); this.sm = g.getBody().getMethod(); if (sm.isStatic()) { this.thisLocal = null; } else { this.thisLocal = g.getBody().getThisLocal(); } this.dfa = dfa; this.refOnly = ignoreNonRefTypeFlow; this.infoFlowGraph = new MemoryEfficientGraph<EquivalentValue>(); this.returnRef = new ParameterRef(g.getBody().getMethod().getReturnType(), -1); // it's a dummy parameter ref this.entrySet = new ArraySparseSet<Pair<EquivalentValue, EquivalentValue>>(); this.emptySet = new ArraySparseSet<Pair<EquivalentValue, EquivalentValue>>(); printMessages = false; } public void doFlowInsensitiveAnalysis() { FlowSet<Pair<EquivalentValue, EquivalentValue>> fs = newInitialFlow(); boolean flowSetChanged = true; while (flowSetChanged) { int sizebefore = fs.size(); Iterator<Unit> unitIt = graph.iterator(); while (unitIt.hasNext()) { Unit u = unitIt.next(); flowThrough(fs, u, fs); } if (fs.size() > sizebefore) { flowSetChanged = true; } else { flowSetChanged = false; } } } public MutableDirectedGraph<EquivalentValue> getMethodInfoFlowSummary() { return infoFlowGraph; } protected void merge(FlowSet<Pair<EquivalentValue, EquivalentValue>> in1, FlowSet<Pair<EquivalentValue, EquivalentValue>> in2, FlowSet<Pair<EquivalentValue, EquivalentValue>> out) { in1.union(in2, out); } protected boolean isNonRefType(Type type) { return !(type instanceof RefLikeType); } protected boolean ignoreThisDataType(Type type) { return refOnly && isNonRefType(type); } // Interesting sources are summarized (and possibly printed) public boolean isInterestingSource(Value source) { return (source instanceof Ref); } // Trackable sources are added to the flow set public boolean isTrackableSource(Value source) { return isInterestingSource(source) || (source instanceof Ref); } // Interesting sinks are possibly printed public boolean isInterestingSink(Value sink) { return (sink instanceof Ref); } // Trackable sinks are added to the flow set public boolean isTrackableSink(Value sink) { return isInterestingSink(sink) || (sink instanceof Ref) || (sink instanceof Local); } private ArrayList<Value> getDirectSources(Value v, FlowSet<Pair<EquivalentValue, EquivalentValue>> fs) { ArrayList<Value> ret = new ArrayList<Value>(); // of "interesting sources" EquivalentValue vEqVal = new CachedEquivalentValue(v); Iterator<Pair<EquivalentValue, EquivalentValue>> fsIt = fs.iterator(); while (fsIt.hasNext()) { Pair<EquivalentValue, EquivalentValue> pair = fsIt.next(); if (pair.getO1().equals(vEqVal)) { ret.add(pair.getO2().getValue()); } } return ret; } // For when data flows to a local protected void handleFlowsToValue(Value sink, Value initialSource, FlowSet<Pair<EquivalentValue, EquivalentValue>> fs) { if (!isTrackableSink(sink)) { return; } List<Value> sources = getDirectSources(initialSource, fs); // list of Refs... returns all other sources if (isTrackableSource(initialSource)) { sources.add(initialSource); } Iterator<Value> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { Value source = sourcesIt.next(); EquivalentValue sinkEqVal = new CachedEquivalentValue(sink); EquivalentValue sourceEqVal = new CachedEquivalentValue(source); if (sinkEqVal.equals(sourceEqVal)) { continue; } Pair<EquivalentValue, EquivalentValue> pair = new Pair<EquivalentValue, EquivalentValue>(sinkEqVal, sourceEqVal); if (!fs.contains(pair)) { fs.add(pair); if (isInterestingSource(source) && isInterestingSink(sink)) { if (!infoFlowGraph.containsNode(sinkEqVal)) { infoFlowGraph.addNode(sinkEqVal); } if (!infoFlowGraph.containsNode(sourceEqVal)) { infoFlowGraph.addNode(sourceEqVal); } infoFlowGraph.addEdge(sourceEqVal, sinkEqVal); if (printMessages) { logger.debug(" Found " + source + " flows to " + sink); } } } } } // for when data flows to the data structure pointed to by a local protected void handleFlowsToDataStructure(Value base, Value initialSource, FlowSet<Pair<EquivalentValue, EquivalentValue>> fs) { List<Value> sinks = getDirectSources(base, fs); if (isTrackableSink(base)) { sinks.add(base); } List<Value> sources = getDirectSources(initialSource, fs); if (isTrackableSource(initialSource)) { sources.add(initialSource); } Iterator<Value> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { Value source = sourcesIt.next(); EquivalentValue sourceEqVal = new CachedEquivalentValue(source); Iterator<Value> sinksIt = sinks.iterator(); while (sinksIt.hasNext()) { Value sink = sinksIt.next(); if (!isTrackableSink(sink)) { continue; } EquivalentValue sinkEqVal = new CachedEquivalentValue(sink); if (sinkEqVal.equals(sourceEqVal)) { continue; } Pair<EquivalentValue, EquivalentValue> pair = new Pair<EquivalentValue, EquivalentValue>(sinkEqVal, sourceEqVal); if (!fs.contains(pair)) { fs.add(pair); if (isInterestingSource(source) && isInterestingSink(sink)) { if (!infoFlowGraph.containsNode(sinkEqVal)) { infoFlowGraph.addNode(sinkEqVal); } if (!infoFlowGraph.containsNode(sourceEqVal)) { infoFlowGraph.addNode(sourceEqVal); } infoFlowGraph.addEdge(sourceEqVal, sinkEqVal); if (printMessages) { logger.debug(" Found " + source + " flows to " + sink); } } } } } } // handles the invoke expression AND returns a list of the return value's sources // for each node // if the node is a parameter // source = argument <Immediate> // if the node is a static field // source = node <StaticFieldRef> // if the node is a field // source = receiver object <Local> // if the node is the return value // continue // for each sink // if the sink is a parameter // handleFlowsToDataStructure(sink, source, fs) // if the sink is a static field // handleFlowsToValue(sink, source, fs) // if the sink is a field // handleFlowsToDataStructure(receiver object, source, fs) // if the sink is the return value // add node to list of return value sources protected List<Value> handleInvokeExpr(InvokeExpr ie, Stmt is, FlowSet<Pair<EquivalentValue, EquivalentValue>> fs) { // get the data flow graph MutableDirectedGraph<EquivalentValue> dataFlowGraph = dfa.getInvokeInfoFlowSummary(ie, is, sm); // must return a graph // whose nodes are // Refs!!! // if( ie.getMethodRef().resolve().getSubSignature().equals(new String("boolean remove(java.lang.Object)")) ) // { // logger.debug("*!*!*!*!*!<boolean remove(java.lang.Object)> has FLOW SENSITIVE infoFlowGraph: "); // ClassInfoFlowAnalysis.printDataFlowGraph(infoFlowGraph); // } List<Value> returnValueSources = new ArrayList<Value>(); Iterator<EquivalentValue> nodeIt = dataFlowGraph.getNodes().iterator(); while (nodeIt.hasNext()) { EquivalentValue nodeEqVal = nodeIt.next(); if (!(nodeEqVal.getValue() instanceof Ref)) { throw new RuntimeException( "Illegal node type in data flow graph:" + nodeEqVal.getValue() + " should be an object of type Ref."); } Ref node = (Ref) nodeEqVal.getValue(); Value source = null; if (node instanceof ParameterRef) { ParameterRef param = (ParameterRef) node; if (param.getIndex() == -1) { continue; } source = ie.getArg(param.getIndex()); // Immediate } else if (node instanceof StaticFieldRef) { source = node; // StaticFieldRef } else if (ie instanceof InstanceInvokeExpr && node instanceof InstanceFieldRef) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; source = iie.getBase(); // Local } Iterator<EquivalentValue> sinksIt = dataFlowGraph.getSuccsOf(nodeEqVal).iterator(); while (sinksIt.hasNext()) { EquivalentValue sinkEqVal = sinksIt.next(); Ref sink = (Ref) sinkEqVal.getValue(); if (sink instanceof ParameterRef) { ParameterRef param = (ParameterRef) sink; if (param.getIndex() == -1) { returnValueSources.add(source); } else { handleFlowsToDataStructure(ie.getArg(param.getIndex()), source, fs); } } else if (sink instanceof StaticFieldRef) { handleFlowsToValue(sink, source, fs); } else if (ie instanceof InstanceInvokeExpr && sink instanceof InstanceFieldRef) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; handleFlowsToDataStructure(iie.getBase(), source, fs); } } } // return the list of return value sources return returnValueSources; } protected void flowThrough(FlowSet<Pair<EquivalentValue, EquivalentValue>> in, Unit unit, FlowSet<Pair<EquivalentValue, EquivalentValue>> out) { Stmt stmt = (Stmt) unit; if (in != out) { in.copy(out); } FlowSet<Pair<EquivalentValue, EquivalentValue>> changedFlow = out; // Calculate the minimum subset of the flow set that we need to consider - OBSELETE optimization // FlowSet changedFlow = new ArraySparseSet(); // FlowSet oldFlow = new ArraySparseSet(); // out.copy(oldFlow); // in.union(out, out); // out.difference(oldFlow, changedFlow); /* * Iterator changedFlowIt = changedFlow.iterator(); while(changedFlowIt.hasNext()) { Pair pair = (Pair) * changedFlowIt.next(); EquivalentValue defEqVal = (EquivalentValue) pair.getO1(); Value def = defEqVal.getValue(); * boolean defIsUsed = false; Iterator usesIt = stmt.getUseBoxes().iterator(); while(usesIt.hasNext()) { Value use = * ((ValueBox) usesIt.next()).getValue(); if(use.equivTo(def)) defIsUsed = true; } if(!defIsUsed) * changedFlow.remove(pair); } */ // Bail out if there's nothing to consider, unless this might be the first run // if(changedFlow.isEmpty() && !oldFlow.equals(emptySet)) // return; if (stmt instanceof IdentityStmt) // assigns an IdentityRef to a Local { IdentityStmt is = (IdentityStmt) stmt; IdentityRef ir = (IdentityRef) is.getRightOp(); if (ir instanceof JCaughtExceptionRef) { // TODO: What the heck do we do with this??? } else if (ir instanceof ParameterRef) { if (!ignoreThisDataType(ir.getType())) { // <Local, ParameterRef and sources> handleFlowsToValue(is.getLeftOp(), ir, changedFlow); } } else if (ir instanceof ThisRef) { if (!ignoreThisDataType(ir.getType())) { // <Local, ThisRef and sources> handleFlowsToValue(is.getLeftOp(), ir, changedFlow); } } } else if (stmt instanceof ReturnStmt) // assigns an Immediate to the "returnRef" { ReturnStmt rs = (ReturnStmt) stmt; Value rv = rs.getOp(); if (rv instanceof Constant) { // No (interesting) data flow } else if (rv instanceof Local) { if (!ignoreThisDataType(rv.getType())) { // <ReturnRef, sources of Local> handleFlowsToValue(returnRef, rv, changedFlow); } } } else if (stmt instanceof AssignStmt) // assigns a Value to a Variable { AssignStmt as = (AssignStmt) stmt; Value lv = as.getLeftOp(); Value rv = as.getRightOp(); Value sink = null; boolean flowsToDataStructure = false; if (lv instanceof Local) // data flows into the Local { sink = lv; } else if (lv instanceof ArrayRef) // data flows into the base's data structure { ArrayRef ar = (ArrayRef) lv; sink = ar.getBase(); flowsToDataStructure = true; } else if (lv instanceof StaticFieldRef) // data flows into the field ref { sink = lv; } else if (lv instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) lv; if (ifr.getBase() == thisLocal) // data flows into the field ref { sink = lv; } else // data flows into the base's data structure { sink = ifr.getBase(); flowsToDataStructure = true; } } List<Value> sources = new ArrayList<Value>(); boolean interestingFlow = true; if (rv instanceof Local) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof Constant) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof ArrayRef) // data flows from the base's data structure { ArrayRef ar = (ArrayRef) rv; sources.add(ar.getBase()); interestingFlow = !ignoreThisDataType(ar.getType()); } else if (rv instanceof StaticFieldRef) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) rv; if (ifr.getBase() == thisLocal) // data flows from the field ref { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else // data flows from the base's data structure { sources.add(ifr.getBase()); interestingFlow = !ignoreThisDataType(ifr.getType()); } } else if (rv instanceof AnyNewExpr) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof BinopExpr) { BinopExpr be = (BinopExpr) rv; sources.add(be.getOp1()); sources.add(be.getOp2()); interestingFlow = !ignoreThisDataType(be.getType()); } else if (rv instanceof CastExpr) { CastExpr ce = (CastExpr) rv; sources.add(ce.getOp()); interestingFlow = !ignoreThisDataType(ce.getType()); } else if (rv instanceof InstanceOfExpr) { InstanceOfExpr ioe = (InstanceOfExpr) rv; sources.add(ioe.getOp()); interestingFlow = !ignoreThisDataType(ioe.getType()); } else if (rv instanceof UnopExpr) { UnopExpr ue = (UnopExpr) rv; sources.add(ue.getOp()); interestingFlow = !ignoreThisDataType(ue.getType()); } else if (rv instanceof InvokeExpr) { InvokeExpr ie = (InvokeExpr) rv; sources.addAll(handleInvokeExpr(ie, as, changedFlow)); interestingFlow = !ignoreThisDataType(ie.getType()); } if (interestingFlow) { if (flowsToDataStructure) { for (Value source : sources) { handleFlowsToDataStructure(sink, source, changedFlow); } } else { for (Value source : sources) { handleFlowsToValue(sink, source, changedFlow); } } } } else if (stmt.containsInvokeExpr()) // flows data between receiver object, parameters, globals, and return value { handleInvokeExpr(stmt.getInvokeExpr(), stmt, changedFlow); } // changedFlow.union(out, out); - OBSELETE optimization } protected void copy(FlowSet<Pair<EquivalentValue, EquivalentValue>> source, FlowSet<Pair<EquivalentValue, EquivalentValue>> dest) { source.copy(dest); } protected FlowSet<Pair<EquivalentValue, EquivalentValue>> entryInitialFlow() { return entrySet.clone(); } protected FlowSet<Pair<EquivalentValue, EquivalentValue>> newInitialFlow() { return emptySet.clone(); } public void addToEntryInitialFlow(Value source, Value sink) { EquivalentValue sinkEqVal = new CachedEquivalentValue(sink); EquivalentValue sourceEqVal = new CachedEquivalentValue(source); if (sinkEqVal.equals(sourceEqVal)) { return; } Pair<EquivalentValue, EquivalentValue> pair = new Pair<EquivalentValue, EquivalentValue>(sinkEqVal, sourceEqVal); if (!entrySet.contains(pair)) { entrySet.add(pair); } } public void addToNewInitialFlow(Value source, Value sink) { EquivalentValue sinkEqVal = new CachedEquivalentValue(sink); EquivalentValue sourceEqVal = new CachedEquivalentValue(source); if (sinkEqVal.equals(sourceEqVal)) { return; } Pair<EquivalentValue, EquivalentValue> pair = new Pair<EquivalentValue, EquivalentValue>(sinkEqVal, sourceEqVal); if (!emptySet.contains(pair)) { emptySet.add(pair); } } public Value getThisLocal() { return thisLocal; } }
22,664
35.793831
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/SimpleMethodLocalObjectsAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.EquivalentValue; import soot.SootField; import soot.SootMethod; import soot.Value; import soot.toolkits.graph.UnitGraph; // SimpleMethodLocalObjectsAnalysis written by Richard L. Halpert, 2007-02-23 // Finds objects that are local to the scope of the LocalObjectsScopeAnalysis // that is provided. // This is a specialized version of SimpleMethodInfoFlowAnalysis, in which the data // source is the abstract "shared" data source. public class SimpleMethodLocalObjectsAnalysis extends SimpleMethodInfoFlowAnalysis { private static final Logger logger = LoggerFactory.getLogger(SimpleMethodLocalObjectsAnalysis.class); public static int mlocounter = 0; public SimpleMethodLocalObjectsAnalysis(UnitGraph g, ClassLocalObjectsAnalysis cloa, InfoFlowAnalysis dfa) { super(g, dfa, true, true); // special version doesn't run analysis yet mlocounter++; printMessages = false; SootMethod method = g.getBody().getMethod(); AbstractDataSource sharedDataSource = new AbstractDataSource(new String("SHARED")); // Add a source for every parameter that is shared for (int i = 0; i < method.getParameterCount(); i++) // no need to worry about return value... { EquivalentValue paramEqVal = InfoFlowAnalysis.getNodeForParameterRef(method, i); if (!cloa.parameterIsLocal(method, paramEqVal)) { addToEntryInitialFlow(sharedDataSource, paramEqVal.getValue()); addToNewInitialFlow(sharedDataSource, paramEqVal.getValue()); } } for (SootField sf : cloa.getSharedFields()) { EquivalentValue fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(method, sf); addToEntryInitialFlow(sharedDataSource, fieldRefEqVal.getValue()); addToNewInitialFlow(sharedDataSource, fieldRefEqVal.getValue()); } if (printMessages) { logger.debug("----- STARTING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } doFlowInsensitiveAnalysis(); if (printMessages) { logger.debug("----- ENDING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } } public SimpleMethodLocalObjectsAnalysis(UnitGraph g, CallLocalityContext context, InfoFlowAnalysis dfa) { super(g, dfa, true, true); // special version doesn't run analysis yet mlocounter++; printMessages = false; SootMethod method = g.getBody().getMethod(); AbstractDataSource sharedDataSource = new AbstractDataSource(new String("SHARED")); List<Object> sharedRefs = context.getSharedRefs(); Iterator<Object> sharedRefEqValIt = sharedRefs.iterator(); // returns a list of (correctly structured) EquivalentValue // wrapped refs that should be // treated as shared while (sharedRefEqValIt.hasNext()) { EquivalentValue refEqVal = (EquivalentValue) sharedRefEqValIt.next(); addToEntryInitialFlow(sharedDataSource, refEqVal.getValue()); addToNewInitialFlow(sharedDataSource, refEqVal.getValue()); } if (printMessages) { logger.debug("----- STARTING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); logger.debug(" " + context.toString().replaceAll("\n", "\n ")); logger.debug("found " + sharedRefs.size() + " shared refs in context."); } doFlowInsensitiveAnalysis(); if (printMessages) { logger.debug("----- ENDING SHARED/LOCAL ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } } // Interesting sources are summarized (and possibly printed) public boolean isInterestingSource(Value source) { return (source instanceof AbstractDataSource); } // Interesting sinks are possibly printed public boolean isInterestingSink(Value sink) { return true; // (sink instanceof Local); // we're interested in all values } // public boolean isObjectLocal(Value local) // to this analysis of this method (which depends on context) { EquivalentValue source = new CachedEquivalentValue(new AbstractDataSource(new String("SHARED"))); if (infoFlowGraph.containsNode(source)) { List sinks = infoFlowGraph.getSuccsOf(source); if (printMessages) { logger.debug(" Requested value " + local + " is " + (!sinks.contains(new CachedEquivalentValue(local)) ? "Local" : "Shared") + " in " + sm + " "); } return !sinks.contains(new CachedEquivalentValue(local)); } else { if (printMessages) { logger.debug(" Requested value " + local + " is Local (LIKE ALL VALUES) in " + sm + " "); } return true; // no shared data in this method } } }
5,660
38.3125
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/SmartMethodInfoFlowAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.EquivalentValue; import soot.Local; import soot.RefLikeType; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.Value; import soot.VoidType; import soot.jimple.AnyNewExpr; import soot.jimple.ArrayRef; import soot.jimple.AssignStmt; import soot.jimple.BinopExpr; import soot.jimple.CastExpr; import soot.jimple.Constant; import soot.jimple.IdentityRef; import soot.jimple.IdentityStmt; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InstanceOfExpr; import soot.jimple.InvokeExpr; import soot.jimple.ParameterRef; import soot.jimple.Ref; import soot.jimple.ReturnStmt; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.UnopExpr; import soot.jimple.internal.JCaughtExceptionRef; import soot.toolkits.graph.HashMutableDirectedGraph; import soot.toolkits.graph.MemoryEfficientGraph; import soot.toolkits.graph.MutableDirectedGraph; import soot.toolkits.graph.UnitGraph; // SimpleMethodInfoFlowAnalysis written by Richard L. Halpert, 2007-02-25 // Constructs a data flow table for the given method. Ignores indirect flow. // These tables conservatively approximate how data flows from parameters, // fields, and globals to parameters, fields, globals, and the return value. // Note that a ref-type parameter (or field or global) might allow access to a // large data structure, but that entire structure will be represented only by // the parameter's one node in the data flow graph. public class SmartMethodInfoFlowAnalysis { private static final Logger logger = LoggerFactory.getLogger(SmartMethodInfoFlowAnalysis.class); UnitGraph graph; SootMethod sm; Value thisLocal; InfoFlowAnalysis dfa; boolean refOnly; // determines if primitive type data flow is included boolean includeInnerFields; // determines if flow to a field of an object (other than this) is treated like flow to that // object HashMutableDirectedGraph<EquivalentValue> abbreviatedInfoFlowGraph; HashMutableDirectedGraph<EquivalentValue> infoFlowSummary; Ref returnRef; boolean printMessages; public static int counter = 0; public SmartMethodInfoFlowAnalysis(UnitGraph g, InfoFlowAnalysis dfa) { graph = g; this.sm = g.getBody().getMethod(); if (sm.isStatic()) { this.thisLocal = null; } else { this.thisLocal = g.getBody().getThisLocal(); } this.dfa = dfa; this.refOnly = !dfa.includesPrimitiveInfoFlow(); this.includeInnerFields = dfa.includesInnerFields(); this.abbreviatedInfoFlowGraph = new MemoryEfficientGraph<EquivalentValue>(); this.infoFlowSummary = new MemoryEfficientGraph<EquivalentValue>(); this.returnRef = new ParameterRef(g.getBody().getMethod().getReturnType(), -1); // it's a dummy parameter ref // this.entrySet = new ArraySparseSet(); // this.emptySet = new ArraySparseSet(); printMessages = false; // dfa.printDebug(); counter++; // Add all of the nodes necessary to ensure that this is a complete data flow graph // Add every parameter of this method for (int i = 0; i < sm.getParameterCount(); i++) { EquivalentValue parameterRefEqVal = InfoFlowAnalysis.getNodeForParameterRef(sm, i); if (!infoFlowSummary.containsNode(parameterRefEqVal)) { infoFlowSummary.addNode(parameterRefEqVal); } } // Add every relevant field of this class (static methods don't get non-static fields) for (Iterator<SootField> it = sm.getDeclaringClass().getFields().iterator(); it.hasNext();) { SootField sf = it.next(); if (sf.isStatic() || !sm.isStatic()) { EquivalentValue fieldRefEqVal; if (!sm.isStatic()) { fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf, sm.retrieveActiveBody().getThisLocal()); } else { fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, sf); } if (!infoFlowSummary.containsNode(fieldRefEqVal)) { infoFlowSummary.addNode(fieldRefEqVal); } } } // Add every field of this class's superclasses SootClass superclass = sm.getDeclaringClass(); if (superclass.hasSuperclass()) { superclass = sm.getDeclaringClass().getSuperclass(); } while (superclass.hasSuperclass()) // we don't want to process Object { for (SootField scField : superclass.getFields()) { if (scField.isStatic() || !sm.isStatic()) { EquivalentValue fieldRefEqVal; if (!sm.isStatic()) { fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, scField, sm.retrieveActiveBody().getThisLocal()); } else { fieldRefEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, scField); } if (!infoFlowSummary.containsNode(fieldRefEqVal)) { infoFlowSummary.addNode(fieldRefEqVal); } } } superclass = superclass.getSuperclass(); } // Add thisref of this class if (!sm.isStatic()) { EquivalentValue thisRefEqVal = InfoFlowAnalysis.getNodeForThisRef(sm); if (!infoFlowSummary.containsNode(thisRefEqVal)) { infoFlowSummary.addNode(thisRefEqVal); } } // Add returnref of this method EquivalentValue returnRefEqVal = new CachedEquivalentValue(returnRef); if (returnRef.getType() != VoidType.v() && !infoFlowSummary.containsNode(returnRefEqVal)) { infoFlowSummary.addNode(returnRefEqVal); } // Do the analysis Date start = new Date(); int counterSoFar = counter; if (printMessages) { logger.debug("STARTING SMART ANALYSIS FOR " + g.getBody().getMethod() + " -----"); } // S=#Statements, R=#Refs, L=#Locals, where generally (S ~= L), (L >> R) // Generates a data flow graph of refs and locals where "flows to data structure" is represented in a single node generateAbbreviatedInfoFlowGraph(); // O(S) // Generates a data flow graph of refs where "flows to data structure" has been resolved generateInfoFlowSummary(); // O( R*(L+R) ) if (printMessages) { long longTime = ((new Date()).getTime() - start.getTime()); float time = (longTime) / 1000.0f; logger.debug("ENDING SMART ANALYSIS FOR " + g.getBody().getMethod() + " ----- " + (counter - counterSoFar + 1) + " analyses took: " + time + "s"); logger.debug(" AbbreviatedDataFlowGraph:"); InfoFlowAnalysis.printInfoFlowSummary(abbreviatedInfoFlowGraph); logger.debug(" DataFlowSummary:"); InfoFlowAnalysis.printInfoFlowSummary(infoFlowSummary); } } public void generateAbbreviatedInfoFlowGraph() { Iterator<Unit> stmtIt = graph.iterator(); while (stmtIt.hasNext()) { Stmt s = (Stmt) stmtIt.next(); addFlowToCdfg(s); } } public void generateInfoFlowSummary() { Iterator<EquivalentValue> nodeIt = infoFlowSummary.iterator(); while (nodeIt.hasNext()) { EquivalentValue node = nodeIt.next(); List<EquivalentValue> sources = sourcesOf(node); Iterator<EquivalentValue> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { EquivalentValue source = sourcesIt.next(); if (source.getValue() instanceof Ref) { infoFlowSummary.addEdge(source, node); } } } } public List<EquivalentValue> sourcesOf(EquivalentValue node) { return sourcesOf(node, new HashSet<EquivalentValue>(), new HashSet<EquivalentValue>()); } private List<EquivalentValue> sourcesOf(EquivalentValue node, Set<EquivalentValue> visitedSources, Set<EquivalentValue> visitedSinks) { visitedSources.add(node); List<EquivalentValue> ret = new LinkedList<EquivalentValue>(); if (!abbreviatedInfoFlowGraph.containsNode(node)) { return ret; } // get direct sources Set<EquivalentValue> preds = abbreviatedInfoFlowGraph.getPredsOfAsSet(node); Iterator<EquivalentValue> predsIt = preds.iterator(); while (predsIt.hasNext()) { EquivalentValue pred = predsIt.next(); if (!visitedSources.contains(pred)) { ret.add(pred); ret.addAll(sourcesOf(pred, visitedSources, visitedSinks)); } } // get sources of (sources of sinks, of which we are one) List<EquivalentValue> sinks = sinksOf(node, visitedSources, visitedSinks); Iterator<EquivalentValue> sinksIt = sinks.iterator(); while (sinksIt.hasNext()) { EquivalentValue sink = sinksIt.next(); if (!visitedSources.contains(sink)) { EquivalentValue flowsToSourcesOf = new CachedEquivalentValue(new AbstractDataSource(sink.getValue())); if (abbreviatedInfoFlowGraph.getPredsOfAsSet(sink).contains(flowsToSourcesOf)) { ret.addAll(sourcesOf(flowsToSourcesOf, visitedSources, visitedSinks)); } } } return ret; } public List<EquivalentValue> sinksOf(EquivalentValue node) { return sinksOf(node, new HashSet<EquivalentValue>(), new HashSet<EquivalentValue>()); } private List<EquivalentValue> sinksOf(EquivalentValue node, Set<EquivalentValue> visitedSources, Set<EquivalentValue> visitedSinks) { List<EquivalentValue> ret = new LinkedList<EquivalentValue>(); // if(visitedSinks.contains(node)) // return ret; visitedSinks.add(node); if (!abbreviatedInfoFlowGraph.containsNode(node)) { return ret; } // get direct sinks Set<EquivalentValue> succs = abbreviatedInfoFlowGraph.getSuccsOfAsSet(node); Iterator<EquivalentValue> succsIt = succs.iterator(); while (succsIt.hasNext()) { EquivalentValue succ = succsIt.next(); if (!visitedSinks.contains(succ)) { ret.add(succ); ret.addAll(sinksOf(succ, visitedSources, visitedSinks)); } } // get sources of (sources of sinks, of which we are one) succsIt = succs.iterator(); while (succsIt.hasNext()) { EquivalentValue succ = succsIt.next(); if (succ.getValue() instanceof AbstractDataSource) { // It will have ONE successor, who will be the value whose sources it represents Set vHolder = abbreviatedInfoFlowGraph.getSuccsOfAsSet(succ); EquivalentValue v = (EquivalentValue) vHolder.iterator().next(); // get the one and only if (!visitedSinks.contains(v)) { // Set<EquivalentValue> ret.addAll(sourcesOf(v, visitedSinks, visitedSinks)); // these nodes are really to be marked as sinks, not sources } } } return ret; } public HashMutableDirectedGraph<EquivalentValue> getMethodInfoFlowSummary() { return infoFlowSummary; } public HashMutableDirectedGraph<EquivalentValue> getMethodAbbreviatedInfoFlowGraph() { return abbreviatedInfoFlowGraph; } protected boolean isNonRefType(Type type) { return !(type instanceof RefLikeType); } protected boolean ignoreThisDataType(Type type) { return refOnly && isNonRefType(type); } // For when data flows to a local protected void handleFlowsToValue(Value sink, Value source) { EquivalentValue sinkEqVal; EquivalentValue sourceEqVal; if (sink instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) sink; sinkEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, ifr.getField(), (Local) ifr.getBase()); // deals with inner fields } else { sinkEqVal = new CachedEquivalentValue(sink); } if (source instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) source; sourceEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, ifr.getField(), (Local) ifr.getBase()); // deals with inner // fields } else { sourceEqVal = new CachedEquivalentValue(source); } if (source instanceof Ref && !infoFlowSummary.containsNode(sourceEqVal)) { infoFlowSummary.addNode(sourceEqVal); } if (sink instanceof Ref && !infoFlowSummary.containsNode(sinkEqVal)) { infoFlowSummary.addNode(sinkEqVal); } if (!abbreviatedInfoFlowGraph.containsNode(sinkEqVal)) { abbreviatedInfoFlowGraph.addNode(sinkEqVal); } if (!abbreviatedInfoFlowGraph.containsNode(sourceEqVal)) { abbreviatedInfoFlowGraph.addNode(sourceEqVal); } abbreviatedInfoFlowGraph.addEdge(sourceEqVal, sinkEqVal); } // for when data flows to the data structure pointed to by a local protected void handleFlowsToDataStructure(Value base, Value source) { EquivalentValue sourcesOfBaseEqVal = new CachedEquivalentValue(new AbstractDataSource(base)); EquivalentValue baseEqVal = new CachedEquivalentValue(base); EquivalentValue sourceEqVal; if (source instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) source; sourceEqVal = InfoFlowAnalysis.getNodeForFieldRef(sm, ifr.getField(), (Local) ifr.getBase()); // deals with inner // fields } else { sourceEqVal = new CachedEquivalentValue(source); } if (source instanceof Ref && !infoFlowSummary.containsNode(sourceEqVal)) { infoFlowSummary.addNode(sourceEqVal); } if (!abbreviatedInfoFlowGraph.containsNode(baseEqVal)) { abbreviatedInfoFlowGraph.addNode(baseEqVal); } if (!abbreviatedInfoFlowGraph.containsNode(sourceEqVal)) { abbreviatedInfoFlowGraph.addNode(sourceEqVal); } if (!abbreviatedInfoFlowGraph.containsNode(sourcesOfBaseEqVal)) { abbreviatedInfoFlowGraph.addNode(sourcesOfBaseEqVal); } abbreviatedInfoFlowGraph.addEdge(sourceEqVal, sourcesOfBaseEqVal); abbreviatedInfoFlowGraph.addEdge(sourcesOfBaseEqVal, baseEqVal); // for convenience } // For inner fields... we have base flow to field as a service specifically // for the sake of LocalObjects... yes, this is a hack! protected void handleInnerField(Value innerFieldRef) { /* * InstanceFieldRef ifr = (InstanceFieldRef) innerFieldRef; * * EquivalentValue baseEqVal = new CachedEquivalentValue(ifr.getBase()); EquivalentValue fieldRefEqVal = * dfa.getEquivalentValueFieldRef(sm, ifr.getField()); // deals with inner fields * * if(!abbreviatedInfoFlowGraph.containsNode(baseEqVal)) abbreviatedInfoFlowGraph.addNode(baseEqVal); * if(!abbreviatedInfoFlowGraph.containsNode(fieldRefEqVal)) abbreviatedInfoFlowGraph.addNode(fieldRefEqVal); * * abbreviatedInfoFlowGraph.addEdge(baseEqVal, fieldRefEqVal); */ } // handles the invoke expression AND returns a list of the return value's sources // for each node // if the node is a parameter // source = argument <Immediate> // if the node is a static field // source = node <StaticFieldRef> // if the node is a field // source = receiver object <Local> // if the node is the return value // continue // for each sink // if the sink is a parameter // handleFlowsToDataStructure(sink, source, fs) // if the sink is a static field // handleFlowsToValue(sink, source, fs) // if the sink is a field // handleFlowsToDataStructure(receiver object, source, fs) // if the sink is the return value // add node to list of return value sources protected List<Value> handleInvokeExpr(InvokeExpr ie, Stmt is) { // get the data flow graph HashMutableDirectedGraph<EquivalentValue> dataFlowSummary = dfa.getInvokeInfoFlowSummary(ie, is, sm); // must return a // graph whose // nodes are // Refs!!! if (false) // DEBUG!!! { SootMethod method = ie.getMethodRef().resolve(); if (method.getDeclaringClass().isApplicationClass()) { logger.debug("Attempting to print graph (will succeed only if ./dfg/ is a valid path)"); MutableDirectedGraph<EquivalentValue> abbreviatedDataFlowGraph = dfa.getInvokeAbbreviatedInfoFlowGraph(ie, sm); InfoFlowAnalysis.printGraphToDotFile( "dfg/" + method.getDeclaringClass().getShortName() + "_" + method.getName() + (refOnly ? "" : "_primitive"), abbreviatedDataFlowGraph, method.getName() + (refOnly ? "" : "_primitive"), false); } } // if( ie.getMethodRef().resolve().getSubSignature().equals(new String("boolean remove(java.lang.Object)")) ) // { // logger.debug("*!*!*!*!*!<boolean remove(java.lang.Object)> has FLOW SENSITIVE infoFlowSummary: "); // ClassInfoFlowAnalysis.printDataFlowGraph(infoFlowSummary); // } List<Value> returnValueSources = new ArrayList(); Iterator<EquivalentValue> nodeIt = dataFlowSummary.getNodes().iterator(); while (nodeIt.hasNext()) { EquivalentValue nodeEqVal = nodeIt.next(); if (!(nodeEqVal.getValue() instanceof Ref)) { throw new RuntimeException( "Illegal node type in data flow summary:" + nodeEqVal.getValue() + " should be an object of type Ref."); } Ref node = (Ref) nodeEqVal.getValue(); List<Value> sources = new ArrayList(); // Value source = null; if (node instanceof ParameterRef) { ParameterRef param = (ParameterRef) node; if (param.getIndex() == -1) { continue; } sources.add(ie.getArg(param.getIndex())); // source = ; // Immediate } else if (node instanceof StaticFieldRef) { sources.add(node); // source = node; // StaticFieldRef } else if (node instanceof InstanceFieldRef && ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; if (iie.getBase() == thisLocal) { sources.add(node); // source = node; } else if (includeInnerFields) { if (false) // isNonRefType(node.getType()) ) // TODO: double check this policy { // primitives flow from the parent object InstanceFieldRef ifr = (InstanceFieldRef) node; if (ifr.getBase() instanceof FakeJimpleLocal) { ; // sources.add(((FakeJimpleLocal) ifr.getBase()).getRealLocal()); } else { sources.add(ifr.getBase()); } } else { // objects flow from both InstanceFieldRef ifr = (InstanceFieldRef) node; if (ifr.getBase() instanceof FakeJimpleLocal) { ; // sources.add(((FakeJimpleLocal) ifr.getBase()).getRealLocal()); } else { sources.add(ifr.getBase()); } sources.add(node); } // source = node; // handleInnerField(source); } else { sources.add(iie.getBase()); // source = iie.getBase(); // Local } } else if (node instanceof InstanceFieldRef && includeInnerFields) { if (false) // isNonRefType(node.getType()) ) // TODO: double check this policy { // primitives flow from the parent object InstanceFieldRef ifr = (InstanceFieldRef) node; if (ifr.getBase() instanceof FakeJimpleLocal) { ; // sources.add(((FakeJimpleLocal) ifr.getBase()).getRealLocal()); } else { sources.add(ifr.getBase()); } } else { // objects flow from both InstanceFieldRef ifr = (InstanceFieldRef) node; if (ifr.getBase() instanceof FakeJimpleLocal) { ; // sources.add(((FakeJimpleLocal) ifr.getBase()).getRealLocal()); } else { sources.add(ifr.getBase()); } sources.add(node); } // source = node; // handleInnerField(source); } else if (node instanceof ThisRef && ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; sources.add(iie.getBase()); // source = iie.getBase(); // Local } else { throw new RuntimeException("Unknown Node Type in Data Flow Graph: node " + node + " in InvokeExpr " + ie); } Iterator<EquivalentValue> sinksIt = dataFlowSummary.getSuccsOfAsSet(nodeEqVal).iterator(); while (sinksIt.hasNext()) { EquivalentValue sinkEqVal = sinksIt.next(); Ref sink = (Ref) sinkEqVal.getValue(); if (sink instanceof ParameterRef) { ParameterRef param = (ParameterRef) sink; if (param.getIndex() == -1) { returnValueSources.addAll(sources); } else { for (Iterator<Value> sourcesIt = sources.iterator(); sourcesIt.hasNext();) { Value source = sourcesIt.next(); handleFlowsToDataStructure(ie.getArg(param.getIndex()), source); } } } else if (sink instanceof StaticFieldRef) { for (Iterator<Value> sourcesIt = sources.iterator(); sourcesIt.hasNext();) { Value source = sourcesIt.next(); handleFlowsToValue(sink, source); } } else if (sink instanceof InstanceFieldRef && ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; if (iie.getBase() == thisLocal) { for (Iterator<Value> sourcesIt = sources.iterator(); sourcesIt.hasNext();) { Value source = sourcesIt.next(); handleFlowsToValue(sink, source); } } else if (includeInnerFields) { for (Iterator<Value> sourcesIt = sources.iterator(); sourcesIt.hasNext();) { Value source = sourcesIt.next(); if (false) // isNonRefType(sink.getType()) ) // TODO: double check this policy { // primitives flow to the parent object InstanceFieldRef ifr = (InstanceFieldRef) sink; if (ifr.getBase() instanceof FakeJimpleLocal) { ; // handleFlowsToDataStructure(((FakeJimpleLocal) ifr.getBase()).getRealLocal(), source); } else { handleFlowsToDataStructure(ifr.getBase(), source); } } else { // objects flow to the field handleFlowsToValue(sink, source); } handleInnerField(sink); } } else { for (Iterator<Value> sourcesIt = sources.iterator(); sourcesIt.hasNext();) { Value source = sourcesIt.next(); handleFlowsToDataStructure(iie.getBase(), source); } } } else if (sink instanceof InstanceFieldRef && includeInnerFields) { for (Iterator<Value> sourcesIt = sources.iterator(); sourcesIt.hasNext();) { Value source = sourcesIt.next(); if (false) // isNonRefType(sink.getType()) ) // TODO: double check this policy { // primitives flow to the parent object InstanceFieldRef ifr = (InstanceFieldRef) sink; if (ifr.getBase() instanceof FakeJimpleLocal) { ; // handleFlowsToDataStructure(((FakeJimpleLocal) ifr.getBase()).getRealLocal(), source); } else { handleFlowsToDataStructure(ifr.getBase(), source); } } else { handleFlowsToValue(sink, source); } handleInnerField(sink); } } } } // return the list of return value sources return returnValueSources; } protected void addFlowToCdfg(Stmt stmt) { if (stmt instanceof IdentityStmt) // assigns an IdentityRef to a Local { IdentityStmt is = (IdentityStmt) stmt; IdentityRef ir = (IdentityRef) is.getRightOp(); if (ir instanceof JCaughtExceptionRef) { // TODO: What the heck do we do with this??? } else if (ir instanceof ParameterRef) { if (!ignoreThisDataType(ir.getType())) { // <Local, ParameterRef and sources> handleFlowsToValue(is.getLeftOp(), ir); } } else if (ir instanceof ThisRef) { if (!ignoreThisDataType(ir.getType())) { // <Local, ThisRef and sources> handleFlowsToValue(is.getLeftOp(), ir); } } } else if (stmt instanceof ReturnStmt) // assigns an Immediate to the "returnRef" { ReturnStmt rs = (ReturnStmt) stmt; Value rv = rs.getOp(); if (rv instanceof Constant) { // No (interesting) data flow } else if (rv instanceof Local) { if (!ignoreThisDataType(rv.getType())) { // <ReturnRef, sources of Local> handleFlowsToValue(returnRef, rv); } } } else if (stmt instanceof AssignStmt) // assigns a Value to a Variable { AssignStmt as = (AssignStmt) stmt; Value lv = as.getLeftOp(); Value rv = as.getRightOp(); Value sink = null; boolean flowsToDataStructure = false; if (lv instanceof Local) // data flows into the Local { sink = lv; } else if (lv instanceof ArrayRef) // data flows into the base's data structure { ArrayRef ar = (ArrayRef) lv; sink = ar.getBase(); flowsToDataStructure = true; } else if (lv instanceof StaticFieldRef) // data flows into the field ref { sink = lv; } else if (lv instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) lv; if (ifr.getBase() == thisLocal) // data flows into the field ref { sink = lv; } else if (includeInnerFields) { if (false) // isNonRefType(lv.getType()) ) // TODO: double check this policy { // primitives flow to the parent object sink = ifr.getBase(); flowsToDataStructure = true; } else { // objects flow to the field sink = lv; handleInnerField(sink); } } else // data flows into the base's data structure { sink = ifr.getBase(); flowsToDataStructure = true; } } List sources = new ArrayList(); boolean interestingFlow = true; if (rv instanceof Local) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof Constant) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof ArrayRef) // data flows from the base's data structure { ArrayRef ar = (ArrayRef) rv; sources.add(ar.getBase()); interestingFlow = !ignoreThisDataType(ar.getType()); } else if (rv instanceof StaticFieldRef) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) rv; if (ifr.getBase() == thisLocal) // data flows from the field ref { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (includeInnerFields) { if (false) // isNonRefType(rv.getType()) ) // TODO: double check this policy { // primitives flow from the parent object sources.add(ifr.getBase()); } else { // objects flow from both sources.add(ifr.getBase()); sources.add(rv); handleInnerField(rv); } interestingFlow = !ignoreThisDataType(rv.getType()); } else // data flows from the base's data structure { sources.add(ifr.getBase()); interestingFlow = !ignoreThisDataType(ifr.getType()); } } else if (rv instanceof AnyNewExpr) { sources.add(rv); interestingFlow = !ignoreThisDataType(rv.getType()); } else if (rv instanceof BinopExpr) // does this include compares and others??? yes { BinopExpr be = (BinopExpr) rv; sources.add(be.getOp1()); sources.add(be.getOp2()); interestingFlow = !ignoreThisDataType(be.getType()); } else if (rv instanceof CastExpr) { CastExpr ce = (CastExpr) rv; sources.add(ce.getOp()); interestingFlow = !ignoreThisDataType(ce.getType()); } else if (rv instanceof InstanceOfExpr) { InstanceOfExpr ioe = (InstanceOfExpr) rv; sources.add(ioe.getOp()); interestingFlow = !ignoreThisDataType(ioe.getType()); } else if (rv instanceof UnopExpr) { UnopExpr ue = (UnopExpr) rv; sources.add(ue.getOp()); interestingFlow = !ignoreThisDataType(ue.getType()); } else if (rv instanceof InvokeExpr) { InvokeExpr ie = (InvokeExpr) rv; sources.addAll(handleInvokeExpr(ie, as)); interestingFlow = !ignoreThisDataType(ie.getType()); } if (interestingFlow) { if (flowsToDataStructure) { Iterator<Value> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { Value source = sourcesIt.next(); handleFlowsToDataStructure(sink, source); } } else { Iterator<Value> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { Value source = sourcesIt.next(); // if(flowsToBoth && sink instanceof InstanceFieldRef) // handleFlowsToDataStructure(((InstanceFieldRef)sink).getBase(), source); handleFlowsToValue(sink, source); } } } } else if (stmt.containsInvokeExpr()) // flows data between receiver object, parameters, globals, and return value { handleInvokeExpr(stmt.getInvokeExpr(), stmt); } } public Value getThisLocal() { return thisLocal; } }
31,039
38.044025
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/SmartMethodLocalObjectsAnalysis.java
package soot.jimple.toolkits.infoflow; /*- * #%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.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.EquivalentValue; import soot.SootMethod; import soot.Value; import soot.jimple.Constant; import soot.jimple.FieldRef; import soot.jimple.InstanceFieldRef; import soot.jimple.Ref; import soot.toolkits.graph.UnitGraph; // SmartMethodLocalObjectsAnalysis written by Richard L. Halpert, 2007-02-23 // Uses a SmartMethodInfoFlowAnalysis to determine if a Local or FieldRef is // LOCAL or SHARED in the given method. public class SmartMethodLocalObjectsAnalysis { private static final Logger logger = LoggerFactory.getLogger(SmartMethodLocalObjectsAnalysis.class); public static int counter = 0; static boolean printMessages; SootMethod method; InfoFlowAnalysis dfa; SmartMethodInfoFlowAnalysis smdfa; public SmartMethodLocalObjectsAnalysis(SootMethod method, InfoFlowAnalysis dfa) { this.method = method; this.dfa = dfa; this.smdfa = dfa.getMethodInfoFlowAnalysis(method); printMessages = dfa.printDebug(); counter++; } public SmartMethodLocalObjectsAnalysis(UnitGraph g, InfoFlowAnalysis dfa) { this(g.getBody().getMethod(), dfa); } public Value getThisLocal() { return smdfa.getThisLocal(); } // public boolean isObjectLocal(Value local, CallLocalityContext context) // to this analysis of this method (which depends on // context) { EquivalentValue localEqVal; if (local instanceof InstanceFieldRef) { localEqVal = InfoFlowAnalysis.getNodeForFieldRef(method, ((FieldRef) local).getField()); } else { localEqVal = new CachedEquivalentValue(local); } List<EquivalentValue> sources = smdfa.sourcesOf(localEqVal); Iterator<EquivalentValue> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { EquivalentValue source = sourcesIt.next(); if (source.getValue() instanceof Ref) { if (!context.isFieldLocal(source)) { if (printMessages) { logger.debug(" Requested value " + local + " is SHARED in " + method + " "); } return false; } } else if (source.getValue() instanceof Constant) { if (printMessages) { logger.debug(" Requested value " + local + " is SHARED in " + method + " "); } return false; } } if (printMessages) { logger.debug(" Requested value " + local + " is LOCAL in " + method + " "); } return true; } public static boolean isObjectLocal(InfoFlowAnalysis dfa, SootMethod method, CallLocalityContext context, Value local) { SmartMethodInfoFlowAnalysis smdfa = dfa.getMethodInfoFlowAnalysis(method); EquivalentValue localEqVal; if (local instanceof InstanceFieldRef) { localEqVal = InfoFlowAnalysis.getNodeForFieldRef(method, ((FieldRef) local).getField()); } else { localEqVal = new CachedEquivalentValue(local); } List<EquivalentValue> sources = smdfa.sourcesOf(localEqVal); Iterator<EquivalentValue> sourcesIt = sources.iterator(); while (sourcesIt.hasNext()) { EquivalentValue source = sourcesIt.next(); if (source.getValue() instanceof Ref) { if (!context.isFieldLocal(source)) { if (printMessages) { logger.debug(" Requested value " + local + " is LOCAL in " + method + " "); } return false; } } } if (printMessages) { logger.debug(" Requested value " + local + " is SHARED in " + method + " "); } return true; } }
4,506
32.634328
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/infoflow/UseFinder.java
package soot.jimple.toolkits.infoflow; /*- * #%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.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Body; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.jimple.FieldRef; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.scalar.Pair; import soot.util.Chain; // UseFinder written by Richard L. Halpert, 2007-03-13 // Compiles a list of all uses of fields of each application class within the // application classes by looking at every application method. // Compiles a list of all calls to methods of each application class within the // application classes by using the call graph. public class UseFinder { ReachableMethods rm; Map<SootClass, List> classToExtFieldAccesses; // each field access is a Pair <containing method, stmt> Map<SootClass, ArrayList> classToIntFieldAccesses; Map<SootClass, List> classToExtCalls; // each call is a Pair <containing method, stmt> Map<SootClass, ArrayList> classToIntCalls; public UseFinder() { classToExtFieldAccesses = new HashMap<SootClass, List>(); classToIntFieldAccesses = new HashMap<SootClass, ArrayList>(); classToExtCalls = new HashMap<SootClass, List>(); classToIntCalls = new HashMap<SootClass, ArrayList>(); rm = Scene.v().getReachableMethods(); doAnalysis(); } public UseFinder(ReachableMethods rm) { classToExtFieldAccesses = new HashMap<SootClass, List>(); classToIntFieldAccesses = new HashMap<SootClass, ArrayList>(); classToExtCalls = new HashMap<SootClass, List>(); classToIntCalls = new HashMap<SootClass, ArrayList>(); this.rm = rm; doAnalysis(); } public List getExtFieldAccesses(SootClass sc) { if (classToExtFieldAccesses.containsKey(sc)) { return classToExtFieldAccesses.get(sc); } throw new RuntimeException("UseFinder does not search non-application classes: " + sc); } public List getIntFieldAccesses(SootClass sc) { if (classToIntFieldAccesses.containsKey(sc)) { return classToIntFieldAccesses.get(sc); } throw new RuntimeException("UseFinder does not search non-application classes: " + sc); } public List getExtCalls(SootClass sc) { if (classToExtCalls.containsKey(sc)) { return classToExtCalls.get(sc); } throw new RuntimeException("UseFinder does not search non-application classes: " + sc); } public List getIntCalls(SootClass sc) { if (classToIntCalls.containsKey(sc)) { return classToIntCalls.get(sc); } throw new RuntimeException("UseFinder does not search non-application classes: " + sc); } // This is an incredibly stupid way to do this... we should just use the call graph for faster/better info! public List<SootMethod> getExtMethods(SootClass sc) { if (classToExtCalls.containsKey(sc)) { List extCalls = classToExtCalls.get(sc); List<SootMethod> extMethods = new ArrayList<SootMethod>(); for (Iterator callIt = extCalls.iterator(); callIt.hasNext();) { Pair call = (Pair) callIt.next(); SootMethod calledMethod = ((Stmt) call.getO2()).getInvokeExpr().getMethod(); if (!extMethods.contains(calledMethod)) { extMethods.add(calledMethod); } } return extMethods; } throw new RuntimeException("UseFinder does not search non-application classes: " + sc); } public List<SootField> getExtFields(SootClass sc) { if (classToExtFieldAccesses.containsKey(sc)) { List extAccesses = classToExtFieldAccesses.get(sc); List<SootField> extFields = new ArrayList<SootField>(); for (Iterator accessIt = extAccesses.iterator(); accessIt.hasNext();) { Pair access = (Pair) accessIt.next(); SootField accessedField = ((Stmt) access.getO2()).getFieldRef().getField(); if (!extFields.contains(accessedField)) { extFields.add(accessedField); } } return extFields; } throw new RuntimeException("UseFinder does not search non-application classes: " + sc); } private void doAnalysis() { Chain appClasses = Scene.v().getApplicationClasses(); // Set up lists of internal and external accesses Iterator appClassesIt = appClasses.iterator(); while (appClassesIt.hasNext()) { SootClass appClass = (SootClass) appClassesIt.next(); classToIntFieldAccesses.put(appClass, new ArrayList()); classToExtFieldAccesses.put(appClass, new ArrayList()); classToIntCalls.put(appClass, new ArrayList()); classToExtCalls.put(appClass, new ArrayList()); } // Find internal and external accesses appClassesIt = appClasses.iterator(); while (appClassesIt.hasNext()) { SootClass appClass = (SootClass) appClassesIt.next(); Iterator methodsIt = appClass.getMethods().iterator(); while (methodsIt.hasNext()) { SootMethod method = (SootMethod) methodsIt.next(); if (method.isConcrete() && rm.contains(method)) { Body b = method.retrieveActiveBody(); Iterator unitsIt = b.getUnits().iterator(); while (unitsIt.hasNext()) { Stmt s = (Stmt) unitsIt.next(); if (s.containsFieldRef()) { FieldRef fr = s.getFieldRef(); if (fr.getFieldRef().resolve().getDeclaringClass() == appClass) { if (fr instanceof StaticFieldRef) { // static field ref in same class is considered internal classToIntFieldAccesses.get(appClass).add(new Pair(method, s)); } else if (fr instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) fr; if (!method.isStatic() && ifr.getBase().equivTo(b.getThisLocal())) { // this.field ref is considered internal classToIntFieldAccesses.get(appClass).add(new Pair(method, s)); } else { // o.field ref is considered external classToExtFieldAccesses.get(appClass).add(new Pair(method, s)); } } } else { // ref to some other class is considered external List<Pair> otherClassList = classToExtFieldAccesses.get(fr.getFieldRef().resolve().getDeclaringClass()); if (otherClassList == null) { otherClassList = new ArrayList<Pair>(); classToExtFieldAccesses.put(fr.getFieldRef().resolve().getDeclaringClass(), otherClassList); } otherClassList.add(new Pair(method, s)); } } if (s.containsInvokeExpr()) { InvokeExpr ie = s.getInvokeExpr(); if (ie.getMethodRef().resolve().getDeclaringClass() == appClass) // what about sub/superclasses { if (ie instanceof StaticInvokeExpr) { // static field ref in same class is considered internal classToIntCalls.get(appClass).add(new Pair(method, s)); } else if (ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; if (!method.isStatic() && iie.getBase().equivTo(b.getThisLocal())) { // this.field ref is considered internal classToIntCalls.get(appClass).add(new Pair(method, s)); } else { // o.field ref is considered external classToExtCalls.get(appClass).add(new Pair(method, s)); } } } else { // ref to some other class is considered external List<Pair> otherClassList = classToExtCalls.get(ie.getMethodRef().resolve().getDeclaringClass()); if (otherClassList == null) { otherClassList = new ArrayList<Pair>(); classToExtCalls.put(ie.getMethodRef().resolve().getDeclaringClass(), otherClassList); } otherClassList.add(new Pair(method, s)); } } } } } } } }
9,252
39.406114
120
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/AccessManager.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * 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.List; import soot.Body; import soot.ClassMember; import soot.Hierarchy; import soot.Local; import soot.LocalGenerator; import soot.Modifier; import soot.Scene; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.Value; import soot.VoidType; import soot.jimple.AssignStmt; import soot.jimple.FieldRef; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.VirtualInvokeExpr; import soot.util.Chain; /** * Methods for checking Java scope and visibility requirements. */ public class AccessManager { /** * Returns true iff target is legally accessible from container. Illegal access occurs when any of the following cases * holds: (1) target is private, but container.declaringClass() != target.declaringClass(); or, (2) target is * package-visible (i.e. default), and its package differs from that of container; or, (3) target is protected and the * package of container differs from the package of target and the container doesn't belong to target.declaringClass or any * subclass. */ public static boolean isAccessLegal(final SootMethod container, final ClassMember target) { final SootClass targetClass = target.getDeclaringClass(); if (!isAccessLegal(container, targetClass)) { return false; } final SootClass containerClass = container.getDeclaringClass(); // Condition 1 above. if (target.isPrivate() && !targetClass.getName().equals(containerClass.getName())) { return false; } // Condition 2. Check the package names. if (!target.isPrivate() && !target.isProtected() && !target.isPublic()) { // i.e. default if (!targetClass.getPackageName().equals(containerClass.getPackageName())) { return false; } } // Condition 3. if (target.isProtected()) { // protected means that you can be accessed by your children (i.e. // container is in a child of target) and classes in the same package. if (!targetClass.getPackageName().equals(containerClass.getPackageName())) { Hierarchy h = Scene.v().getActiveHierarchy(); return h.isClassSuperclassOfIncluding(targetClass, containerClass); } } return true; } /** * Returns true if an access to <code>target</code> is legal from code in <code>container</code>. */ public static boolean isAccessLegal(final SootMethod container, final SootClass target) { return target.isPublic() || container.getDeclaringClass().getPackageName().equals(target.getPackageName()); } /** * Returns true if the statement <code>stmt</code> contains an illegal access to a field or method, assuming the statement * is in method <code>container</code> * * @param container * @param stmt * @return */ public static boolean isAccessLegal(final SootMethod container, final Stmt stmt) { if (stmt.containsInvokeExpr()) { return AccessManager.isAccessLegal(container, stmt.getInvokeExpr().getMethod()); } else if (stmt instanceof AssignStmt) { AssignStmt as = (AssignStmt) stmt; Value rightOp = as.getRightOp(); if (rightOp instanceof FieldRef) { return AccessManager.isAccessLegal(container, ((FieldRef) rightOp).getField()); } Value leftOp = as.getLeftOp(); if (leftOp instanceof FieldRef) { return AccessManager.isAccessLegal(container, ((FieldRef) leftOp).getField()); } } return true; } /** * Resolves illegal accesses in the interval ]before,after[ by creating accessor methods. <code>before</code> and * <code>after</code> can be null to indicate beginning/end respectively. * * @param body * @param before * @param after */ public static void createAccessorMethods(final Body body, final Stmt before, final Stmt after) { final Chain<Unit> units = body.getUnits(); if (before != null && !units.contains(before)) { throw new RuntimeException(); } if (after != null && !units.contains(after)) { throw new RuntimeException(); } boolean bInside = (before == null); for (Unit unit : new ArrayList<Unit>(units)) { Stmt s = (Stmt) unit; if (bInside) { if (s == after) { return; } SootMethod m = body.getMethod(); if (!isAccessLegal(m, s)) { createAccessorMethod(m, s); } } else if (s == before) { bInside = true; } } } /** * Creates a name for an accessor method. * * @param member * @param setter * @return */ public static String createAccessorName(final ClassMember member, final boolean setter) { StringBuilder name = new StringBuilder("access$"); if (member instanceof SootField) { name.append(setter ? "set$" : "get$"); SootField f = (SootField) member; name.append(f.getName()); } else { SootMethod m = (SootMethod) member; name.append(m.getName()).append('$'); for (Type type : m.getParameterTypes()) { name.append(type.toString().replaceAll("\\.", "\\$\\$")).append('$'); } } return name.toString(); } /** * Turns a field access or method call into a call to an accessor method. Reuses existing accessors based on name mangling * (see createAccessorName) * * @param container * @param stmt */ public static void createAccessorMethod(final SootMethod container, final Stmt stmt) { if (!container.getActiveBody().getUnits().contains(stmt)) { throw new RuntimeException(); } if (stmt.containsInvokeExpr()) { createInvokeAccessor(container, stmt); } else if (stmt instanceof AssignStmt) { AssignStmt as = (AssignStmt) stmt; Value leftOp = as.getLeftOp(); if (leftOp instanceof FieldRef) { // set createSetAccessor(container, as, (FieldRef) leftOp); } else { Value rightOp = as.getRightOp(); if (rightOp instanceof FieldRef) { // get createGetAccessor(container, as, (FieldRef) rightOp); } else { throw new RuntimeException("Expected class member access"); } } } else { throw new RuntimeException("Expected class member access"); } } private static void createGetAccessor(final SootMethod container, final AssignStmt as, final FieldRef ref) { final Jimple jimp = Jimple.v(); final SootClass target = ref.getField().getDeclaringClass(); String name = createAccessorName(ref.getField(), false); SootMethod accessor = target.getMethodByNameUnsafe(name); if (accessor == null) { final JimpleBody accessorBody = jimp.newBody(); final Chain<Unit> accStmts = accessorBody.getUnits(); final LocalGenerator lg = Scene.v().createLocalGenerator(accessorBody); List<Type> parameterTypes; final Type targetType = target.getType(); final Local thisLocal = lg.generateLocal(targetType); if (ref instanceof InstanceFieldRef) { accStmts.addFirst(jimp.newIdentityStmt(thisLocal, jimp.newParameterRef(targetType, 0))); parameterTypes = Collections.singletonList(targetType); } else { parameterTypes = Collections.emptyList(); } final Type refFieldType = ref.getField().getType(); Local l = lg.generateLocal(refFieldType); accStmts.add( jimp.newAssignStmt(l, (ref instanceof InstanceFieldRef) ? jimp.newInstanceFieldRef(thisLocal, ref.getFieldRef()) : jimp.newStaticFieldRef(ref.getFieldRef()))); accStmts.add(jimp.newReturnStmt(l)); accessor = Scene.v().makeSootMethod(name, parameterTypes, refFieldType, Modifier.PUBLIC | Modifier.STATIC, Collections.emptyList()); accessorBody.setMethod(accessor); accessor.setActiveBody(accessorBody); target.addMethod(accessor); } List<Value> args = (ref instanceof InstanceFieldRef) ? Collections.singletonList(((InstanceFieldRef) ref).getBase()) : Collections.emptyList(); as.setRightOp(jimp.newStaticInvokeExpr(accessor.makeRef(), args)); } private static void createSetAccessor(final SootMethod container, final AssignStmt as, final FieldRef ref) { final Jimple jimp = Jimple.v(); final SootClass target = ref.getField().getDeclaringClass(); final String name = createAccessorName(ref.getField(), true); SootMethod accessor = target.getMethodByNameUnsafe(name); if (accessor == null) { final JimpleBody accessorBody = jimp.newBody(); final Chain<Unit> accStmts = accessorBody.getUnits(); final LocalGenerator lg = Scene.v().createLocalGenerator(accessorBody); Local thisLocal = lg.generateLocal(target.getType()); List<Type> parameterTypes = new ArrayList<Type>(2); int paramID = 0; if (ref instanceof InstanceFieldRef) { accStmts.add(jimp.newIdentityStmt(thisLocal, jimp.newParameterRef(target.getType(), paramID))); parameterTypes.add(target.getType()); paramID++; } parameterTypes.add(ref.getField().getType()); Local l = lg.generateLocal(ref.getField().getType()); accStmts.add(jimp.newIdentityStmt(l, jimp.newParameterRef(ref.getField().getType(), paramID))); paramID++; if (ref instanceof InstanceFieldRef) { accStmts.add(jimp.newAssignStmt(jimp.newInstanceFieldRef(thisLocal, ref.getFieldRef()), l)); } else { accStmts.add(jimp.newAssignStmt(jimp.newStaticFieldRef(ref.getFieldRef()), l)); } accStmts.addLast(jimp.newReturnVoidStmt()); accessor = Scene.v().makeSootMethod(name, parameterTypes, VoidType.v(), Modifier.PUBLIC | Modifier.STATIC, Collections.emptyList()); accessorBody.setMethod(accessor); accessor.setActiveBody(accessorBody); target.addMethod(accessor); } { ArrayList<Value> args = new ArrayList<Value>(2); if (ref instanceof InstanceFieldRef) { args.add(((InstanceFieldRef) ref).getBase()); } args.add(as.getRightOp()); Chain<Unit> containerStmts = container.getActiveBody().getUnits(); containerStmts.insertAfter(jimp.newInvokeStmt(jimp.newStaticInvokeExpr(accessor.makeRef(), args)), as); containerStmts.remove(as); } } private static void createInvokeAccessor(final SootMethod container, final Stmt stmt) { final Jimple jimp = Jimple.v(); final InvokeExpr expr = stmt.getInvokeExpr(); final SootMethod method = expr.getMethod(); final SootClass target = method.getDeclaringClass(); final String name = createAccessorName(method, true); SootMethod accessor = target.getMethodByNameUnsafe(name); if (accessor == null) { final JimpleBody accessorBody = jimp.newBody(); final Chain<Unit> accStmts = accessorBody.getUnits(); final LocalGenerator lg = Scene.v().createLocalGenerator(accessorBody); List<Type> parameterTypes = new ArrayList<Type>(); if (expr instanceof InstanceInvokeExpr) { parameterTypes.add(target.getType()); } parameterTypes.addAll(method.getParameterTypes()); List<Local> arguments = new ArrayList<Local>(); int paramID = 0; for (Type type : parameterTypes) { Local l = lg.generateLocal(type); accStmts.add(jimp.newIdentityStmt(l, jimp.newParameterRef(type, paramID))); arguments.add(l); paramID++; } final InvokeExpr accExpr; if (expr instanceof StaticInvokeExpr) { accExpr = jimp.newStaticInvokeExpr(method.makeRef(), arguments); } else if (expr instanceof VirtualInvokeExpr) { Local thisLocal = (Local) arguments.get(0); arguments.remove(0); accExpr = jimp.newVirtualInvokeExpr(thisLocal, method.makeRef(), arguments); } else if (expr instanceof SpecialInvokeExpr) { Local thisLocal = (Local) arguments.get(0); arguments.remove(0); accExpr = jimp.newSpecialInvokeExpr(thisLocal, method.makeRef(), arguments); } else { throw new RuntimeException(); } final Stmt s; final Type returnType = method.getReturnType(); if (returnType instanceof VoidType) { s = jimp.newInvokeStmt(accExpr); accStmts.add(s); accStmts.add(jimp.newReturnVoidStmt()); } else { Local resultLocal = lg.generateLocal(returnType); s = jimp.newAssignStmt(resultLocal, accExpr); accStmts.add(s); accStmts.add(jimp.newReturnStmt(resultLocal)); } accessor = Scene.v().makeSootMethod(name, parameterTypes, returnType, Modifier.PUBLIC | Modifier.STATIC, method.getExceptions()); accessorBody.setMethod(accessor); accessor.setActiveBody(accessorBody); target.addMethod(accessor); } List<Value> args = new ArrayList<Value>(); if (expr instanceof InstanceInvokeExpr) { args.add(((InstanceInvokeExpr) expr).getBase()); } args.addAll(expr.getArgs()); stmt.getInvokeExprBox().setValue(jimp.newStaticInvokeExpr(accessor.makeRef(), args)); } /** * Modifies code so that an access to <code>target</code> is legal from code in <code>container</code>. * * The "accessors" option assumes suitable accessor methods will be created after checking. */ public static boolean ensureAccess(final SootMethod container, final ClassMember target, final String options) { final SootClass targetClass = target.getDeclaringClass(); if (!ensureAccess(container, targetClass, options)) { return false; } if (isAccessLegal(container, target)) { return true; } if (!targetClass.isApplicationClass()) { return false; } if (options != null) { switch (options) { case "none": return false; case "accessors": return true; case "unsafe": target.setModifiers(target.getModifiers() | Modifier.PUBLIC); return true; } } throw new RuntimeException("Not implemented yet!"); } /** * Modifies code so that an access to <code>target</code> is legal from code in <code>container</code>. */ public static boolean ensureAccess(final SootMethod container, final SootClass target, final String options) { if (isAccessLegal(container, target)) { return true; } if (options != null) { switch (options) { case "accessors": return false; case "none": return false; case "unsafe": if (target.isApplicationClass()) { target.setModifiers(target.getModifiers() | Modifier.PUBLIC); return true; } else { return false; } } } throw new RuntimeException("Not implemented yet!"); } private AccessManager() { } }
15,909
35.159091
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/InlinerSafetyManager.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * 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.Hierarchy; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.FieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.Stmt; /** * Methods for checking safety requirements for inlining. */ public class InlinerSafetyManager { private static final boolean PRINT_FAILURE_REASONS = true; // true if safe to inline public static boolean checkSpecialInlineRestrictions(SootMethod container, SootMethod target, String options) { // Check the body of the method to inline for specialinvokes final boolean accessors = "accessors".equals(options); for (Unit u : target.getActiveBody().getUnits()) { Stmt st = (Stmt) u; if (st.containsInvokeExpr()) { InvokeExpr ie1 = st.getInvokeExpr(); if (ie1 instanceof SpecialInvokeExpr) { SootClass containerDeclaringClass = container.getDeclaringClass(); if (specialInvokePerformsLookupIn(ie1, containerDeclaringClass) || specialInvokePerformsLookupIn(ie1, target.getDeclaringClass())) { return false; } SootMethod specialTarget = ie1.getMethod(); if (specialTarget.isPrivate() && specialTarget.getDeclaringClass() != containerDeclaringClass) { // Do not inline a call which contains a specialinvoke call to a private method outside // the current class. This avoids a verifier error and we assume will not have a big // impact because we are inlining methods bottom-up, so such a call will be rare if (!accessors) { return false; } } } } } return true; } public static boolean checkAccessRestrictions(SootMethod container, SootMethod target, String modifierOptions) { // Check the body of the method to inline for method or field access restrictions for (Unit u : target.getActiveBody().getUnits()) { Stmt st = (Stmt) u; if (st.containsInvokeExpr() && !AccessManager.ensureAccess(container, st.getInvokeExpr().getMethod(), modifierOptions)) { return false; } if (st instanceof AssignStmt) { Value lhs = ((AssignStmt) st).getLeftOp(); Value rhs = ((AssignStmt) st).getRightOp(); if (lhs instanceof FieldRef && !AccessManager.ensureAccess(container, ((FieldRef) lhs).getField(), modifierOptions)) { return false; } if (rhs instanceof FieldRef && !AccessManager.ensureAccess(container, ((FieldRef) rhs).getField(), modifierOptions)) { return false; } } } return true; } /** * Returns true if this method can be inlined at the given site. Will try as hard as it can to change things to allow * inlining (modifierOptions controls what it's allowed to do: safe, unsafe and nochanges) * * Returns false otherwise. */ public static boolean ensureInlinability(SootMethod target, Stmt toInline, SootMethod container, String modifierOptions) { if (!canSafelyInlineInto(target, toInline, container)) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] failed canSafelyInlineInto checks"); } return false; } else if (!AccessManager.ensureAccess(container, target, modifierOptions)) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] failed AccessManager.ensureAccess checks"); } return false; } else if (!checkSpecialInlineRestrictions(container, target, modifierOptions)) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] failed checkSpecialInlineRestrictions checks"); } return false; } else if (!checkAccessRestrictions(container, target, modifierOptions)) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] failed checkAccessRestrictions checks"); } return false; } else { return true; } } /** * Checks the safety criteria enumerated in section 3.1.4 (Safety Criteria for Method Inlining) of Vijay's thesis. */ private static boolean canSafelyInlineInto(SootMethod inlinee, Stmt toInline, SootMethod container) { /* first, check the simple (one-line) safety criteria. */ // Rule 0: Don't inline constructors. if ("<init>".equals(inlinee.getName())) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] cannot inline constructors"); } return false; } // Rule 2: inlinee != container. if (inlinee.getSignature().equals(container.getSignature())) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] cannot inline method into itself"); } return false; } // Rule 3: inlinee is neither native nor abstract. if (inlinee.isNative() || inlinee.isAbstract()) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] cannot inline native or abstract methods"); } return false; } // Ok, that wraps up the simple criteria. Now for the more // complicated criteria. // Rule 4: Don't inline away IllegalAccessErrors of the original // source code (e.g. by moving a call to a private method // *from* a bad class *to* a good class) occuring in the // toInline statement. // Does not occur for static methods, because there is no base? InvokeExpr ie = toInline.getInvokeExpr(); if (ie instanceof InstanceInvokeExpr) { Type baseTy = ((InstanceInvokeExpr) ie).getBase().getType(); if (baseTy instanceof RefType && invokeThrowsAccessErrorIn(((RefType) baseTy).getSootClass(), inlinee, container)) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] cannot inline away IllegalAccessErrors"); } return false; } } // Rule 5: Don't inline away any class, method or field access // (in inlinee) resulting in an IllegalAccess error. // Rule 6: Don't introduce a spurious IllegalAccessError from // inlining (by twiddling modifiers). // This is better handled by a pre-phase Scene transformation. // Inliner Safety should just report the absence of such // IllegalAccessErrors after the transformation (and, conversely, // their presence without the twiddling.) // Rule 7: Don't change semantics of program by moving // an invokespecial. if (ie instanceof SpecialInvokeExpr) { if (specialInvokePerformsLookupIn(ie, inlinee.getDeclaringClass()) || specialInvokePerformsLookupIn(ie, container.getDeclaringClass())) { if (PRINT_FAILURE_REASONS) { System.out.println("[InlinerSafetyManager] cannot inline if changes semantics of invokespecial"); } return false; } } return true; } /** * Returns true if any of the following cases holds: 1. inlinee is private, but container.declaringClass() != * inlinee.declaringClass(); or, 2. inlinee is package-visible, and its package differs from that of container; or, 3. * inlinee is protected, and either: a. inlinee doesn't belong to container.declaringClass, or any superclass of container; * b. the class of the base is not a (non-strict) subclass of container's declaringClass. The base class may be null, in * which case 3b is omitted. (for instance, for a static method invocation.) */ private static boolean invokeThrowsAccessErrorIn(SootClass base, SootMethod inlinee, SootMethod container) { SootClass inlineeClass = inlinee.getDeclaringClass(); SootClass containerClass = container.getDeclaringClass(); // Condition 1 above. if (inlinee.isPrivate() && !inlineeClass.getName().equals(containerClass.getName())) { return true; } // Condition 2. Check the package names. if (!inlinee.isPrivate() && !inlinee.isProtected() && !inlinee.isPublic()) { if (!inlineeClass.getPackageName().equals(containerClass.getPackageName())) { return true; } } // Condition 3. if (inlinee.isProtected()) { // protected means that you can be accessed by your children. // i.e. container must be in a child of inlinee. Hierarchy h = Scene.v().getActiveHierarchy(); if (!h.isClassSuperclassOfIncluding(inlineeClass, containerClass) && ((base == null) || !h.isClassSuperclassOfIncluding(base, containerClass))) { return true; } } return false; } // m is the method being called; container is the class from which m is being called. static boolean specialInvokePerformsLookupIn(InvokeExpr ie, SootClass containerClass) { assert (ie instanceof SpecialInvokeExpr); // If all of the conditions are true, a lookup is performed. SootMethod m = ie.getMethod(); if ("<init>".equals(m.getName()) || m.isPrivate()) { return false; } // ACC_SUPER must always be set, eh? Hierarchy h = Scene.v().getActiveHierarchy(); return h.isClassSuperclassOf(m.getDeclaringClass(), containerClass); } private InlinerSafetyManager() { } }
10,174
36.966418
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/SiteInliner.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam, 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.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.Body; import soot.Local; import soot.PhaseOptions; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Trap; import soot.TrapManager; import soot.Unit; import soot.UnitBox; import soot.Value; import soot.ValueBox; import soot.jimple.AssignStmt; import soot.jimple.CaughtExceptionRef; import soot.jimple.IdentityRef; import soot.jimple.IdentityStmt; import soot.jimple.IfStmt; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.InvokeStmt; import soot.jimple.Jimple; import soot.jimple.NullConstant; import soot.jimple.ParameterRef; import soot.jimple.ReturnStmt; import soot.jimple.ReturnVoidStmt; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.toolkits.scalar.LocalNameStandardizer; import soot.tagkit.Host; import soot.util.Chain; /** Provides methods to inline a given invoke site. */ public class SiteInliner { public String getDefaultOptions() { return "insert-null-checks insert-redundant-casts"; } /** * Iterates over a list of sites, inlining them in order. Each site is given as a 3-element list (inlinee, toInline, * container). */ public static void inlineSites(List<List<Host>> sites) { inlineSites(sites, Collections.emptyMap()); } /** * Iterates over a list of sites, inlining them in order. Each site is given as a 3-element list (inlinee, toInline, * container). */ public static void inlineSites(List<List<Host>> sites, Map<String, String> options) { for (List<Host> l : sites) { assert (l.size() == 3); SootMethod inlinee = (SootMethod) l.get(0); Stmt toInline = (Stmt) l.get(1); SootMethod container = (SootMethod) l.get(2); inlineSite(inlinee, toInline, container, options); } } /** * Inlines the method <code>inlinee</code> into the <code>container</code> at the point <code>toInline</code>. */ public static List<Unit> inlineSite(SootMethod inlinee, Stmt toInline, SootMethod container) { return inlineSite(inlinee, toInline, container, Collections.emptyMap()); } /** * Inlines the given site. Note that this method does not actually check if it's safe (with respect to access modifiers and * special invokes) for it to be inlined. That functionality is handled by the InlinerSafetyManager. */ public static List<Unit> inlineSite(SootMethod inlinee, Stmt toInline, SootMethod container, Map<String, String> options) { final SootClass declaringClass = inlinee.getDeclaringClass(); if (!declaringClass.isApplicationClass() && !declaringClass.isLibraryClass()) { return null; } final Body containerB = container.getActiveBody(); final Chain<Unit> containerUnits = containerB.getUnits(); assert (containerUnits.contains(toInline)) : toInline + " is not in body " + containerB; final InvokeExpr ie = toInline.getInvokeExpr(); Value thisToAdd = (ie instanceof InstanceInvokeExpr) ? ((InstanceInvokeExpr) ie).getBase() : null; if (ie instanceof InstanceInvokeExpr) { // Insert casts to please the verifier. if (PhaseOptions.getBoolean(options, "insert-redundant-casts")) { // The verifier will complain if the argument passed to the method is not the correct type. // For instance, Bottle.price_static takes a cost. // Cost is an interface implemented by Bottle. Value base = ((InstanceInvokeExpr) ie).getBase(); SootClass localType = ((RefType) base.getType()).getSootClass(); if (localType.isInterface() || Scene.v().getActiveHierarchy().isClassSuperclassOf(localType, declaringClass)) { final Jimple jimp = Jimple.v(); RefType type = declaringClass.getType(); Local castee = jimp.newLocal("__castee", type); containerB.getLocals().add(castee); containerUnits.insertBefore(jimp.newAssignStmt(castee, jimp.newCastExpr(base, type)), toInline); thisToAdd = castee; } } // (If enabled), add a null pointer check. if (PhaseOptions.getBoolean(options, "insert-null-checks")) { final Jimple jimp = Jimple.v(); /* Ah ha. Caught again! */ if (TrapManager.isExceptionCaughtAt(Scene.v().getSootClass("java.lang.NullPointerException"), toInline, containerB)) { // In this case, we don't use throwPoint. Instead, put the code right there. IfStmt insertee = jimp.newIfStmt(jimp.newNeExpr(((InstanceInvokeExpr) ie).getBase(), NullConstant.v()), toInline); containerUnits.insertBefore(insertee, toInline); // This sucks (but less than before). insertee.setTarget(toInline); ThrowManager.addThrowAfter(containerB.getLocals(), containerUnits, insertee); } else { containerUnits.insertBefore(jimp.newIfStmt(jimp.newEqExpr(((InstanceInvokeExpr) ie).getBase(), NullConstant.v()), ThrowManager.getNullPointerExceptionThrower(containerB)), toInline); } } } // Add synchronizing stuff. if (inlinee.isSynchronized()) { // Need to get the class object if ie is a static invoke. if (ie instanceof InstanceInvokeExpr) { Local base = (Local) ((InstanceInvokeExpr) ie).getBase(); SynchronizerManager.v().synchronizeStmtOn(toInline, containerB, base); } else if (!container.getDeclaringClass().isInterface()) { // If we're in an interface, we must be in a <clinit> method, // which surely needs no synchronization. final SynchronizerManager mgr = SynchronizerManager.v(); mgr.synchronizeStmtOn(toInline, containerB, mgr.addStmtsToFetchClassBefore(containerB, toInline)); } } final Body inlineeB = inlinee.getActiveBody(); final Chain<Unit> inlineeUnits = inlineeB.getUnits(); final Unit exitPoint = containerUnits.getSuccOf(toInline); // First, clone all of the inlinee's units & locals. HashMap<Local, Local> oldLocalsToNew = new HashMap<Local, Local>(); HashMap<Unit, Unit> oldUnitsToNew = new HashMap<Unit, Unit>(); { Unit cursor = toInline; for (Unit u : inlineeUnits) { Unit currPrime = (Unit) u.clone(); if (currPrime == null) { throw new RuntimeException("getting null from clone!"); } currPrime.addAllTagsOf(u); containerUnits.insertAfter(currPrime, cursor); oldUnitsToNew.put(u, currPrime); cursor = currPrime; } for (Local l : inlineeB.getLocals()) { Local lPrime = (Local) l.clone(); if (lPrime == null) { throw new RuntimeException("getting null from local clone!"); } containerB.getLocals().add(lPrime); oldLocalsToNew.put(l, lPrime); } } // Backpatch the newly-inserted units using newly-constructed maps. for (Iterator<Unit> it = containerUnits.iterator(containerUnits.getSuccOf(toInline), containerUnits.getPredOf(exitPoint)); it.hasNext();) { Unit patchee = it.next(); for (ValueBox box : patchee.getUseAndDefBoxes()) { Value value = box.getValue(); if (value instanceof Local) { Local lPrime = oldLocalsToNew.get((Local) value); if (lPrime == null) { throw new RuntimeException("local has no clone!"); } box.setValue(lPrime); } } for (UnitBox box : patchee.getUnitBoxes()) { Unit uPrime = oldUnitsToNew.get(box.getUnit()); if (uPrime == null) { throw new RuntimeException("inlined stmt has no clone!"); } box.setUnit(uPrime); } } // Copy & backpatch the traps; preserve their same order. { final Chain<Trap> traps = containerB.getTraps(); Trap prevTrap = null; for (Trap t : inlineeB.getTraps()) { Unit newBegin = oldUnitsToNew.get(t.getBeginUnit()); Unit newEnd = oldUnitsToNew.get(t.getEndUnit()); Unit newHandler = oldUnitsToNew.get(t.getHandlerUnit()); if (newBegin == null || newEnd == null || newHandler == null) { throw new RuntimeException("couldn't map trap!"); } Trap trap = Jimple.v().newTrap(t.getException(), newBegin, newEnd, newHandler); if (prevTrap == null) { traps.addFirst(trap); } else { traps.insertAfter(trap, prevTrap); } prevTrap = trap; } } // Handle identity stmt's and returns. { ArrayList<Unit> cuCopy = new ArrayList<Unit>(); for (Iterator<Unit> it = containerUnits.iterator(containerUnits.getSuccOf(toInline), containerUnits.getPredOf(exitPoint)); it.hasNext();) { cuCopy.add(it.next()); } for (Unit u : cuCopy) { if (u instanceof IdentityStmt) { IdentityStmt idStmt = (IdentityStmt) u; IdentityRef rhs = (IdentityRef) idStmt.getRightOp(); if (rhs instanceof CaughtExceptionRef) { continue; } else if (rhs instanceof ThisRef) { if (!(ie instanceof InstanceInvokeExpr)) { throw new RuntimeException("thisref with no receiver!"); } containerUnits.swapWith(u, Jimple.v().newAssignStmt(idStmt.getLeftOp(), thisToAdd)); } else if (rhs instanceof ParameterRef) { ParameterRef pref = (ParameterRef) rhs; containerUnits.swapWith(u, Jimple.v().newAssignStmt(idStmt.getLeftOp(), ie.getArg(pref.getIndex()))); } } else if (u instanceof ReturnStmt) { if (toInline instanceof InvokeStmt) { // munch, munch. containerUnits.swapWith(u, Jimple.v().newGotoStmt(exitPoint)); } else if (toInline instanceof AssignStmt) { final Jimple jimp = Jimple.v(); AssignStmt as = jimp.newAssignStmt(((AssignStmt) toInline).getLeftOp(), ((ReturnStmt) u).getOp()); containerUnits.insertBefore(as, u); containerUnits.swapWith(u, jimp.newGotoStmt(exitPoint)); } else { throw new RuntimeException("invoking stmt neither InvokeStmt nor AssignStmt!??!?!"); } } else if (u instanceof ReturnVoidStmt) { containerUnits.swapWith(u, Jimple.v().newGotoStmt(exitPoint)); } } } List<Unit> newStmts = new ArrayList<Unit>(); for (Iterator<Unit> i = containerUnits.iterator(containerUnits.getSuccOf(toInline), containerUnits.getPredOf(exitPoint)); i.hasNext();) { newStmts.add(i.next()); } // Remove the original statement toInline. containerUnits.remove(toInline); // Resolve name collisions. LocalNameStandardizer.v().transform(containerB, "ji.lns"); return newStmts; } }
11,755
37.927152
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/StaticInliner.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam, 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.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.G; import soot.Pack; import soot.PackManager; import soot.PhaseOptions; import soot.Scene; import soot.SceneTransformer; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.ExplicitEdgesPred; import soot.jimple.toolkits.callgraph.Filter; import soot.jimple.toolkits.callgraph.Targets; import soot.jimple.toolkits.callgraph.TopologicalOrderer; import soot.options.Options; import soot.tagkit.Host; /** Uses the Scene's currently-active InvokeGraph to inline monomorphic call sites. */ public class StaticInliner extends SceneTransformer { private static final Logger logger = LoggerFactory.getLogger(StaticInliner.class); private final HashMap<SootMethod, Integer> methodToOriginalSize = new HashMap<SootMethod, Integer>(); public StaticInliner(Singletons.Global g) { } public static StaticInliner v() { return G.v().soot_jimple_toolkits_invoke_StaticInliner(); } @Override protected void internalTransform(String phaseName, Map<String, String> options) { final Filter explicitInvokesFilter = new Filter(new ExplicitEdgesPred()); if (Options.v().verbose()) { logger.debug("[" + phaseName + "] Inlining methods..."); } computeAverageMethodSizeAndSaveOriginalSizes(); final String modifierOptions = PhaseOptions.getString(options, "allowed-modifier-changes"); final ArrayList<Host[]> sitesToInline = new ArrayList<Host[]>(); // Visit each potential site in reverse pseudo topological order. { final CallGraph cg = Scene.v().getCallGraph(); final TopologicalOrderer orderer = new TopologicalOrderer(cg); orderer.go(); List<SootMethod> order = orderer.order(); for (ListIterator<SootMethod> it = order.listIterator(order.size()); it.hasPrevious();) { SootMethod container = it.previous(); if (!container.isConcrete() || !methodToOriginalSize.containsKey(container) || !explicitInvokesFilter.wrap(cg.edgesOutOf(container)).hasNext()) { continue; } for (Unit u : new ArrayList<Unit>(container.retrieveActiveBody().getUnits())) { final Stmt s = (Stmt) u; if (!s.containsInvokeExpr()) { continue; } final Targets targets = new Targets(explicitInvokesFilter.wrap(cg.edgesOutOf(s))); if (!targets.hasNext()) { continue; } final SootMethod target = (SootMethod) targets.next(); if (targets.hasNext()) { continue; } if (!target.isConcrete() || !target.getDeclaringClass().isApplicationClass() || !InlinerSafetyManager.ensureInlinability(target, s, container, modifierOptions)) { continue; } sitesToInline.add(new Host[] { target, s, container }); } } } // Proceed to inline the sites, one at a time, keeping track of expansion rates. { final float expansionFactor = PhaseOptions.getFloat(options, "expansion-factor"); final int maxContainerSize = PhaseOptions.getInt(options, "max-container-size"); final int maxInlineeSize = PhaseOptions.getInt(options, "max-inlinee-size"); final Pack jbPack = PhaseOptions.getBoolean(options, "rerun-jb") ? PackManager.v().getPack("jb") : null; for (Host[] site : sitesToInline) { SootMethod inlinee = (SootMethod) site[0]; int inlineeSize = inlinee.retrieveActiveBody().getUnits().size(); SootMethod container = (SootMethod) site[2]; int containerSize = container.retrieveActiveBody().getUnits().size(); if (inlineeSize > maxInlineeSize) { continue; } int inlinedSize = inlineeSize + containerSize; if (inlinedSize > maxContainerSize || inlinedSize > expansionFactor * methodToOriginalSize.get(container)) { continue; } Stmt invokeStmt = (Stmt) site[1]; // Not that it is important to check right before inlining if the site is still valid. if (InlinerSafetyManager.ensureInlinability(inlinee, invokeStmt, container, modifierOptions)) { SiteInliner.inlineSite(inlinee, invokeStmt, container, options); if (jbPack != null) { jbPack.apply(container.getActiveBody()); } } } } } private void computeAverageMethodSizeAndSaveOriginalSizes() { // long sum = 0, count = 0; for (SootClass c : Scene.v().getApplicationClasses()) { for (Iterator<SootMethod> methodsIt = c.methodIterator(); methodsIt.hasNext();) { SootMethod m = methodsIt.next(); if (m.isConcrete()) { int size = m.retrieveActiveBody().getUnits().size(); // sum += size; methodToOriginalSize.put(m, size); // count++; } } } // if (count == 0) { // return; // } } }
6,053
34.822485
116
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/StaticMethodBinder.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam, 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.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import soot.Body; import soot.G; import soot.Hierarchy; import soot.Local; import soot.Modifier; import soot.PhaseOptions; import soot.RefType; import soot.Scene; import soot.SceneTransformer; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.TrapManager; import soot.Type; import soot.Unit; import soot.Value; import soot.jimple.IdentityStmt; import soot.jimple.IfStmt; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Jimple; import soot.jimple.NullConstant; import soot.jimple.ParameterRef; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.Filter; import soot.jimple.toolkits.callgraph.InstanceInvokeEdgesPred; import soot.jimple.toolkits.callgraph.Targets; import soot.jimple.toolkits.scalar.LocalNameStandardizer; import soot.options.SMBOptions; import soot.util.Chain; /** * Uses the Scene's currently-active InvokeGraph to statically bind monomorphic call sites. */ public class StaticMethodBinder extends SceneTransformer { public StaticMethodBinder(Singletons.Global g) { } public static StaticMethodBinder v() { return G.v().soot_jimple_toolkits_invoke_StaticMethodBinder(); } @Override protected void internalTransform(String phaseName, Map<String, String> opts) { final Filter instanceInvokesFilter = new Filter(new InstanceInvokeEdgesPred()); final SMBOptions options = new SMBOptions(opts); final String modifierOptions = PhaseOptions.getString(opts, "allowed-modifier-changes"); final HashMap<SootMethod, SootMethod> instanceToStaticMap = new HashMap<SootMethod, SootMethod>(); final Scene scene = Scene.v(); final CallGraph cg = scene.getCallGraph(); final Hierarchy hierarchy = scene.getActiveHierarchy(); for (SootClass c : scene.getApplicationClasses()) { LinkedList<SootMethod> methodsList = new LinkedList<SootMethod>(); for (Iterator<SootMethod> it = c.methodIterator(); it.hasNext();) { SootMethod next = it.next(); methodsList.add(next); } while (!methodsList.isEmpty()) { SootMethod container = methodsList.removeFirst(); if (!container.isConcrete()) { continue; } if (!instanceInvokesFilter.wrap(cg.edgesOutOf(container)).hasNext()) { continue; } final Body b = container.getActiveBody(); final Chain<Unit> bUnits = b.getUnits(); for (Unit u : new ArrayList<Unit>(bUnits)) { final Stmt s = (Stmt) u; if (!s.containsInvokeExpr()) { continue; } final InvokeExpr ie = s.getInvokeExpr(); if (ie instanceof StaticInvokeExpr || ie instanceof SpecialInvokeExpr) { continue; } final Targets targets = new Targets(instanceInvokesFilter.wrap(cg.edgesOutOf(s))); if (!targets.hasNext()) { continue; } final SootMethod target = (SootMethod) targets.next(); if (targets.hasNext()) { continue; } // Ok, we have an Interface or VirtualInvoke going to 1. if (!AccessManager.ensureAccess(container, target, modifierOptions)) { continue; } final SootClass targetDeclClass = target.getDeclaringClass(); if (!targetDeclClass.isApplicationClass() || !target.isConcrete()) { continue; } // Don't modify java.lang.Object if (targetDeclClass == scene.getSootClass("java.lang.Object")) { continue; } if (!instanceToStaticMap.containsKey(target)) { List<Type> newParameterTypes = new ArrayList<Type>(); newParameterTypes.add(RefType.v(targetDeclClass.getName())); newParameterTypes.addAll(target.getParameterTypes()); // Check for signature conflicts. String newName = target.getName(); do { newName = newName + "_static"; } while (targetDeclClass.declaresMethod(newName, newParameterTypes, target.getReturnType())); SootMethod ct = scene.makeSootMethod(newName, newParameterTypes, target.getReturnType(), target.getModifiers() | Modifier.STATIC, target.getExceptions()); targetDeclClass.addMethod(ct); methodsList.addLast(ct); final Body ctBody = (Body) target.getActiveBody().clone(); ct.setActiveBody(ctBody); // Make the invoke graph take into account the // newly-cloned body. { Iterator<Unit> oldUnits = target.getActiveBody().getUnits().iterator(); for (Unit newStmt : ctBody.getUnits()) { Unit oldStmt = oldUnits.next(); for (Iterator<Edge> edges = cg.edgesOutOf(oldStmt); edges.hasNext();) { Edge e = edges.next(); cg.addEdge(new Edge(ct, newStmt, e.tgt(), e.kind())); cg.removeEdge(e); } } } // Shift the parameter list to apply to the new this parameter. // If the method uses this, then we replace // the r0 := @this with r0 := @parameter0 & shift. // Otherwise, just zap the r0 := @this. { final Chain<Unit> ctBodyUnits = ctBody.getUnits(); for (Iterator<Unit> unitsIt = ctBodyUnits.snapshotIterator(); unitsIt.hasNext();) { Stmt st = (Stmt) unitsIt.next(); if (st instanceof IdentityStmt) { IdentityStmt is = (IdentityStmt) st; Value rightOp = is.getRightOp(); if (rightOp instanceof ThisRef) { final Jimple jimp = Jimple.v(); ctBodyUnits.swapWith(st, jimp.newIdentityStmt(is.getLeftOp(), jimp.newParameterRef(rightOp.getType(), 0))); } else if (rightOp instanceof ParameterRef) { ParameterRef ro = (ParameterRef) rightOp; ro.setIndex(ro.getIndex() + 1); } } } } instanceToStaticMap.put(target, ct); } final Value invokeBase = ((InstanceInvokeExpr) ie).getBase(); Value thisToAdd = invokeBase; // Insert casts to please the verifier. if (options.insert_redundant_casts()) { // The verifier will complain if targetUsesThis, and: // the argument passed to the method is not the same type. // For instance, Bottle.price_static takes a cost. // Cost is an interface implemented by Bottle. SootClass localType = ((RefType) invokeBase.getType()).getSootClass(); if (localType.isInterface() || hierarchy.isClassSuperclassOf(localType, targetDeclClass)) { final Jimple jimp = Jimple.v(); RefType targetDeclClassType = targetDeclClass.getType(); Local castee = jimp.newLocal("__castee", targetDeclClassType); b.getLocals().add(castee); bUnits.insertBefore(jimp.newAssignStmt(castee, jimp.newCastExpr(invokeBase, targetDeclClassType)), s); thisToAdd = castee; } } final SootMethod clonedTarget = instanceToStaticMap.get(target); // Now rebind the method call & fix the invoke graph. { List<Value> newArgs = new ArrayList<Value>(); newArgs.add(thisToAdd); newArgs.addAll(ie.getArgs()); s.getInvokeExprBox().setValue(Jimple.v().newStaticInvokeExpr(clonedTarget.makeRef(), newArgs)); cg.addEdge(new Edge(container, s, clonedTarget)); } // (If enabled), add a null pointer check. if (options.insert_null_checks()) { final Jimple jimp = Jimple.v(); /* Ah ha. Caught again! */ if (TrapManager.isExceptionCaughtAt(scene.getSootClass("java.lang.NullPointerException"), s, b)) { /* * In this case, we don't use throwPoint; instead, put the code right there. */ IfStmt insertee = jimp.newIfStmt(jimp.newNeExpr(invokeBase, NullConstant.v()), s); bUnits.insertBefore(insertee, s); // This sucks (but less than before). insertee.setTarget(s); ThrowManager.addThrowAfter(b.getLocals(), bUnits, insertee); } else { bUnits.insertBefore(jimp.newIfStmt(jimp.newEqExpr(invokeBase, NullConstant.v()), ThrowManager.getNullPointerExceptionThrower(b)), s); } } // Add synchronizing stuff. if (target.isSynchronized()) { clonedTarget.setModifiers(clonedTarget.getModifiers() & ~Modifier.SYNCHRONIZED); SynchronizerManager.v().synchronizeStmtOn(s, b, (Local) invokeBase); } // Resolve name collisions. LocalNameStandardizer.v().transform(b, phaseName + ".lns"); } } } } }
10,343
37.169742
116
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/SynchronizerManager.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * 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.Iterator; import java.util.List; import soot.Body; import soot.G; import soot.Local; import soot.Modifier; import soot.RefType; import soot.Scene; import soot.Singletons; import soot.SootClass; import soot.SootField; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.IdentityStmt; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.NullConstant; import soot.jimple.ParameterRef; import soot.jimple.ReturnStmt; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.shimple.Shimple; import soot.shimple.ShimpleBody; import soot.util.Chain; /** Utility methods for dealing with synchronization. */ public class SynchronizerManager { /** Maps classes to class$ fields. Don't trust default. */ public HashMap<SootClass, SootField> classToClassField = new HashMap<SootClass, SootField>(); public SynchronizerManager(Singletons.Global g) { } public static SynchronizerManager v() { return G.v().soot_jimple_toolkits_invoke_SynchronizerManager(); } /** * Adds code to fetch the static Class object to the given JimpleBody before the target Stmt. * * Uses our custom classToClassField field to cache the results. * * The code will look like this: * * <pre> * $r3 = <quack: java.lang.Class class$quack>; * .if $r3 != .null .goto label2; * * $r3 = .staticinvoke <quack: java.lang.Class class$(java.lang.String)>("quack"); * <quack: java.lang.Class class$quack> = $r3; * * label2: * </pre> */ public Local addStmtsToFetchClassBefore(JimpleBody b, Stmt target) { return addStmtsToFetchClassBefore(b, target, false); } /** * Adds code to fetch the static Class object to the given JimpleBody before the target Stmt. * * Uses our custom classToClassField field to cache the results. * * The code will look like this: * * <pre> * $r3 = <quack: java.lang.Class class$quack>; * .if $r3 != .null .goto label2; * * $r3 = .staticinvoke <quack: java.lang.Class class$(java.lang.String)>("quack"); * <quack: java.lang.Class class$quack> = $r3; * * label2: * </pre> */ public Local addStmtsToFetchClassBefore(ShimpleBody b, Stmt target) { return addStmtsToFetchClassBefore(b, target, true); } /** * Adds code to fetch the static Class object to the given JimpleBody before the target Stmt. * * Uses our custom classToClassField field to cache the results. * * The code will look like this: * * <pre> * $r3 = <quack: java.lang.Class class$quack>; * .if $r3 != .null .goto label2; * * $r3 = .staticinvoke <quack: java.lang.Class class$(java.lang.String)>("quack"); * <quack: java.lang.Class class$quack> = $r3; * * label2: * </pre> */ Local addStmtsToFetchClassBefore(Body b, Stmt target) { assert (b instanceof JimpleBody || b instanceof ShimpleBody); return addStmtsToFetchClassBefore(b, target, b instanceof ShimpleBody); } private Local addStmtsToFetchClassBefore(Body b, Stmt target, boolean createNewAsShimple) { SootClass sc = b.getMethod().getDeclaringClass(); SootField classCacher = classToClassField.get(sc); if (classCacher == null) { // Add a unique field named [__]class$name String n = "class$" + sc.getName().replace('.', '$'); while (sc.declaresFieldByName(n)) { n = '_' + n; } classCacher = Scene.v().makeSootField(n, RefType.v("java.lang.Class"), Modifier.STATIC); sc.addField(classCacher); classToClassField.put(sc, classCacher); } final Chain<Local> locals = b.getLocals(); // Find unique name. Not strictly necessary unless we parse Jimple code. String lName = "$uniqueClass"; while (true) { boolean oops = false; for (Local jbLocal : locals) { if (lName.equals(jbLocal.getName())) { oops = true; } } if (!oops) { break; } lName = '_' + lName; } final Jimple jimp = Jimple.v(); Local l = jimp.newLocal(lName, RefType.v("java.lang.Class")); locals.add(l); final Chain<Unit> units = b.getUnits(); units.insertBefore(jimp.newAssignStmt(l, jimp.newStaticFieldRef(classCacher.makeRef())), target); units.insertBefore(jimp.newIfStmt(jimp.newNeExpr(l, NullConstant.v()), target), target); units.insertBefore(jimp.newAssignStmt(l, jimp.newStaticInvokeExpr(getClassFetcherFor(sc, createNewAsShimple).makeRef(), Collections.singletonList(StringConstant.v(sc.getName())))), target); units.insertBefore(jimp.newAssignStmt(jimp.newStaticFieldRef(classCacher.makeRef()), l), target); return l; } /** * @see #getClassFetcherFor(soot.SootClass, boolean) */ public SootMethod getClassFetcherFor(SootClass c) { return getClassFetcherFor(c, false); } /** * Finds a method which calls java.lang.Class.forName(String). Searches for names class$, _class$, __class$, etc. If no * such method is found, creates one and returns it. * * Uses dumb matching to do search. Not worth doing symbolic analysis for this! */ public SootMethod getClassFetcherFor(final SootClass c, boolean createNewAsShimple) { final String prefix = '<' + c.getName().replace('.', '$') + ": java.lang.Class "; for (String methodName = "class$"; true; methodName = '_' + methodName) { SootMethod m = c.getMethodByNameUnsafe(methodName); if (m == null) { return createClassFetcherFor(c, methodName, createNewAsShimple); } // Check signature. if (!(prefix + methodName + "(java.lang.String)>").equals(m.getSignature())) { continue; } /* we now look for the following fragment: */ /* * r0 := @parameter0: java.lang.String; $r2 = .staticinvoke <java.lang.Class: java.lang.Class * forName(java.lang.String)>(r0); .return $r2; * * Ignore the catching code; this is enough. */ final Iterator<Unit> unitsIt = m.retrieveActiveBody().getUnits().iterator(); if (!unitsIt.hasNext()) { continue; } Stmt s = (Stmt) unitsIt.next(); if (!(s instanceof IdentityStmt)) { continue; } final IdentityStmt is = (IdentityStmt) s; final Value ro = is.getRightOp(); if (!(ro instanceof ParameterRef)) { continue; } if (((ParameterRef) ro).getIndex() != 0) { continue; } if (!unitsIt.hasNext()) { continue; } s = (Stmt) unitsIt.next(); if (!(s instanceof AssignStmt)) { continue; } final AssignStmt as = (AssignStmt) s; if (!(".staticinvoke <java.lang.Class: java.lang.Class forName(java.lang.String)>(" + is.getLeftOp() + ")") .equals(as.getRightOp().toString())) { continue; } if (!unitsIt.hasNext()) { continue; } s = (Stmt) unitsIt.next(); if (!(s instanceof ReturnStmt)) { continue; } if (!((ReturnStmt) s).getOp().equivTo(as.getLeftOp())) { continue; } // don't care about rest. we have sufficient code. // in particular, it certainly returns Class.forName(arg). return m; } } /** * @see #createClassFetcherFor(soot.SootClass, java.lang.String, boolean) */ public SootMethod createClassFetcherFor(SootClass c, String methodName) { return createClassFetcherFor(c, methodName, false); } /** * Creates a method which calls java.lang.Class.forName(String). * * The method should look like the following: * * <code><pre> .static java.lang.Class class$(java.lang.String) { java.lang.String r0, $r5; java.lang.ClassNotFoundException r1, $r3; java.lang.Class $r2; java.lang.NoClassDefFoundError $r4; r0 := @parameter0: java.lang.String; label0: $r2 = .staticinvoke <java.lang.Class: java.lang.Class forName(java.lang.String)>(r0); .return $r2; label1: $r3 := @caughtexception; r1 = $r3; $r4 = .new java.lang.NoClassDefFoundError; $r5 = .virtualinvoke r1.<java.lang.Throwable: java.lang.String getMessage()>(); .specialinvoke $r4.<java.lang.NoClassDefFoundError: .void <init>(java.lang.String)>($r5); .throw $r4; .catch java.lang.ClassNotFoundException .from label0 .to label1 .with label1; } * </pre></code> */ public SootMethod createClassFetcherFor(SootClass c, String methodName, boolean createNewAsShimple) { final RefType refTyString = RefType.v("java.lang.String"); final RefType refTypeClass = RefType.v("java.lang.Class"); final Scene scene = Scene.v(); // Create the method SootMethod method = scene.makeSootMethod(methodName, Collections.singletonList(refTyString), refTypeClass, Modifier.STATIC); c.addMethod(method); // Create the method body { final Jimple jimp = Jimple.v(); Body body = jimp.newBody(method); // Add some locals Local l_r0, l_r1, l_r2, l_r3, l_r4, l_r5; final RefType refTypeClassNotFoundException = RefType.v("java.lang.ClassNotFoundException"); final RefType refTypeNoClassDefFoundError = RefType.v("java.lang.NoClassDefFoundError"); final Chain<Local> locals = body.getLocals(); locals.add(l_r0 = jimp.newLocal("r0", refTyString)); locals.add(l_r1 = jimp.newLocal("r1", refTypeClassNotFoundException)); locals.add(l_r2 = jimp.newLocal("$r2", refTypeClass)); locals.add(l_r3 = jimp.newLocal("$r3", refTypeClassNotFoundException)); locals.add(l_r4 = jimp.newLocal("$r4", refTypeNoClassDefFoundError)); locals.add(l_r5 = jimp.newLocal("$r5", refTyString)); final Chain<Unit> units = body.getUnits(); // add "r0 := @parameter0: java.lang.String" units.add(jimp.newIdentityStmt(l_r0, jimp.newParameterRef(refTyString, 0))); // add "$r2 = .staticinvoke <java.lang.Class: java.lang.Class // forName(java.lang.String)>(r0); AssignStmt asi = jimp.newAssignStmt(l_r2, jimp.newStaticInvokeExpr( scene.getMethod("<java.lang.Class: java.lang.Class forName(java.lang.String)>").makeRef(), Collections.singletonList(l_r0))); units.add(asi); // insert "return $r2;" units.add(jimp.newReturnStmt(l_r2)); // add "r3 := @caughtexception;" Stmt handlerStart = jimp.newIdentityStmt(l_r3, jimp.newCaughtExceptionRef()); units.add(handlerStart); // add "r1 = r3;" units.add(jimp.newAssignStmt(l_r1, l_r3)); // add "$r4 = .new java.lang.NoClassDefFoundError;" units.add(jimp.newAssignStmt(l_r4, jimp.newNewExpr(refTypeNoClassDefFoundError))); // add "$r5 = virtualinvoke r1.<java.lang.Throwable: // java.lang.String getMessage()>();" units.add(jimp.newAssignStmt(l_r5, jimp.newVirtualInvokeExpr(l_r1, scene.getMethod("<java.lang.Throwable: java.lang.String getMessage()>").makeRef(), Collections.emptyList()))); // add .specialinvoke $r4.<java.lang.NoClassDefFoundError: .void // <init>(java.lang.String)>($r5); units.add(jimp.newInvokeStmt(jimp.newSpecialInvokeExpr(l_r4, scene.getMethod("<java.lang.NoClassDefFoundError: void <init>(java.lang.String)>").makeRef(), Collections.singletonList(l_r5)))); // add .throw $r4; units.add(jimp.newThrowStmt(l_r4)); body.getTraps().add(jimp.newTrap(refTypeClassNotFoundException.getSootClass(), asi, handlerStart, handlerStart)); // Convert to Shimple if requested and then store it to the method if (createNewAsShimple) { body = Shimple.v().newBody(body); } method.setActiveBody(body); } return method; } /** * Wraps stmt around a monitor associated with local lock. When inlining or static method binding, this is the former base * of the invoke expression. */ public void synchronizeStmtOn(Stmt stmt, JimpleBody b, Local lock) { synchronizeStmtOn(stmt, (Body) b, lock); } /** * Wraps stmt around a monitor associated with local lock. When inlining or static method binding, this is the former base * of the invoke expression. */ public void synchronizeStmtOn(Stmt stmt, ShimpleBody b, Local lock) { synchronizeStmtOn(stmt, (Body) b, lock); } /** * Wraps stmt around a monitor associated with local lock. When inlining or static method binding, this is the former base * of the invoke expression. */ void synchronizeStmtOn(Stmt stmt, Body b, Local lock) { assert (b instanceof JimpleBody || b instanceof ShimpleBody); final Jimple jimp = Jimple.v(); final Chain<Unit> units = b.getUnits(); // TrapManager.splitTrapsAgainst(b, stmt, units.getSuccOf(stmt)); units.insertBefore(jimp.newEnterMonitorStmt(lock), stmt); Stmt exitMon = jimp.newExitMonitorStmt(lock); units.insertAfter(exitMon, stmt); // Ok. That was the easy part. // We must also add a catch Throwable exception block in the appropriate place. { Stmt newGoto = jimp.newGotoStmt(units.getSuccOf(exitMon)); units.insertAfter(newGoto, exitMon); Local eRef = jimp.newLocal("__exception", RefType.v("java.lang.Throwable")); b.getLocals().add(eRef); List<Unit> l = new ArrayList<Unit>(); Stmt handlerStmt = jimp.newIdentityStmt(eRef, jimp.newCaughtExceptionRef()); l.add(handlerStmt); l.add((Unit) exitMon.clone()); l.add(jimp.newThrowStmt(eRef)); units.insertAfter(l, newGoto); b.getTraps() .addFirst(jimp.newTrap(Scene.v().getSootClass("java.lang.Throwable"), stmt, units.getSuccOf(stmt), handlerStmt)); } } }
14,838
33.112644
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/invoke/ThrowManager.java
package soot.jimple.toolkits.invoke; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam, 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.Iterator; import java.util.Set; import soot.Body; import soot.Hierarchy; import soot.Local; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.Trap; import soot.TrapManager; import soot.Unit; import soot.Value; import soot.jimple.AssignStmt; import soot.jimple.Constant; 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.jimple.ThrowStmt; import soot.shimple.ShimpleBody; import soot.util.Chain; /** Utility methods for dealing with traps. */ public class ThrowManager { /** * Iterate through the statements in b (starting at the end), returning the last instance of the following pattern: * * <code> * r928 = new java.lang.NullPointerException; specialinvoke r928."<init>"(); throw r928; * </code> * * Creates if necessary. */ public static Stmt getNullPointerExceptionThrower(JimpleBody b) { return getNullPointerExceptionThrower((Body) b); } /** * Iterate through the statements in b (starting at the end), returning the last instance of the following pattern: * * <code> * r928 = new java.lang.NullPointerException; specialinvoke r928."<init>"(); throw r928; * </code> * * Creates if necessary. */ public static Stmt getNullPointerExceptionThrower(ShimpleBody b) { return getNullPointerExceptionThrower((Body) b); } static Stmt getNullPointerExceptionThrower(Body b) { assert (b instanceof JimpleBody || b instanceof ShimpleBody); final Set<Unit> trappedUnits = TrapManager.getTrappedUnitsOf(b); final Chain<Unit> units = b.getUnits(); final Unit first = units.getFirst(); final Stmt last = (Stmt) units.getLast(); for (Stmt s = last; s != first; s = (Stmt) units.getPredOf(s)) { if (!trappedUnits.contains(s) && s instanceof ThrowStmt) { Value throwee = ((ThrowStmt) s).getOp(); if (throwee instanceof Constant) { continue; } if (s == first) { break; } Stmt prosInvoke = (Stmt) units.getPredOf(s); if (!(prosInvoke instanceof InvokeStmt)) { continue; } if (prosInvoke == first) { break; } Stmt prosNew = (Stmt) units.getPredOf(prosInvoke); if (!(prosNew instanceof AssignStmt)) { continue; } InvokeExpr ie = ((InvokeStmt) prosInvoke).getInvokeExpr(); if (!(ie instanceof SpecialInvokeExpr)) { continue; } if (((SpecialInvokeExpr) ie).getBase() != throwee || !"<init>".equals(ie.getMethodRef().name())) { continue; } Value ro = ((AssignStmt) prosNew).getRightOp(); if (((AssignStmt) prosNew).getLeftOp() != throwee || !(ro instanceof NewExpr)) { continue; } if (!((NewExpr) ro).getBaseType().equals(RefType.v("java.lang.NullPointerException"))) { continue; } // Whew! return prosNew; } } // Create. return addThrowAfter(b.getLocals(), units, last); } static Stmt addThrowAfter(JimpleBody b, Stmt target) { return addThrowAfter(b.getLocals(), b.getUnits(), target); } static Stmt addThrowAfter(ShimpleBody b, Stmt target) { return addThrowAfter(b.getLocals(), b.getUnits(), target); } static Stmt addThrowAfter(Chain<Local> locals, Chain<Unit> units, Stmt target) { int i = 0; boolean canAddI; do { canAddI = true; String name = "__throwee" + i; for (Local l : locals) { if (name.equals(l.getName())) { canAddI = false; } } if (!canAddI) { i++; } } while (!canAddI); final Jimple jimp = Jimple.v(); Local l = jimp.newLocal("__throwee" + i, RefType.v("java.lang.NullPointerException")); locals.add(l); Stmt newStmt = jimp.newAssignStmt(l, jimp.newNewExpr(RefType.v("java.lang.NullPointerException"))); Stmt invStmt = jimp.newInvokeStmt( jimp.newSpecialInvokeExpr(l, Scene.v().getMethod("<java.lang.NullPointerException: void <init>()>").makeRef())); Stmt throwStmt = jimp.newThrowStmt(l); units.insertAfter(newStmt, target); units.insertAfter(invStmt, newStmt); units.insertAfter(throwStmt, invStmt); return newStmt; } /** * If exception e is caught at stmt s in body b, return the handler; otherwise, return null. */ static boolean isExceptionCaughtAt(SootClass e, Stmt stmt, Body b) { // Look through the traps t of b, checking to see if (1) caught exception // is e and (2) stmt lies between t.beginUnit and t.endUnit Hierarchy h = new Hierarchy(); for (Trap t : b.getTraps()) { /* Ah ha, we might win. */ if (h.isClassSubclassOfIncluding(e, t.getException())) { for (Iterator<Unit> it = b.getUnits().iterator(t.getBeginUnit(), t.getEndUnit()); it.hasNext();) { if (stmt.equals(it.next())) { return true; } } } } return false; } }
5,991
29.110553
120
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/CastCheckEliminator.java
package soot.jimple.toolkits.pointer; /*- * #%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.List; import soot.Body; import soot.Local; import soot.RefType; import soot.Type; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.AssignStmt; import soot.jimple.CastExpr; import soot.jimple.ConditionExpr; import soot.jimple.EqExpr; import soot.jimple.IfStmt; import soot.jimple.InstanceOfExpr; import soot.jimple.IntConstant; import soot.jimple.NeExpr; import soot.jimple.NewExpr; import soot.jimple.NullConstant; import soot.toolkits.graph.BriefUnitGraph; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ForwardBranchedFlowAnalysis; /** A flow analysis that detects redundant cast checks. */ public class CastCheckEliminator extends ForwardBranchedFlowAnalysis<LocalTypeSet> { protected LocalTypeSet emptySet; public CastCheckEliminator(BriefUnitGraph cfg) { super(cfg); makeInitialSet(); doAnalysis(); tagCasts(); } /** Put the results of the analysis into tags in cast statements. */ protected void tagCasts() { for (Unit u : ((UnitGraph) graph).getBody().getUnits()) { if (u instanceof AssignStmt) { Value rhs = ((AssignStmt) u).getRightOp(); if (rhs instanceof CastExpr) { CastExpr cast = (CastExpr) rhs; Type t = cast.getCastType(); if (t instanceof RefType) { Value op = cast.getOp(); if (op instanceof Local) { LocalTypeSet set = getFlowBefore(u); u.addTag(new CastCheckTag(set.get(set.indexOf((Local) op, (RefType) t)))); } else { assert (op instanceof NullConstant); u.addTag(new CastCheckTag(true)); } } } } } } /** * Find all the locals of reference type and all the types used in casts to initialize the mapping from locals and types to * bits in the bit vector in LocalTypeSet. */ protected void makeInitialSet() { final Body body = ((UnitGraph) graph).getBody(); // Find all locals of reference type List<Local> refLocals = new ArrayList<Local>(); for (Local l : body.getLocals()) { if (l.getType() instanceof RefType) { refLocals.add(l); } } // Find types of all casts List<Type> types = new ArrayList<Type>(); for (Unit u : body.getUnits()) { if (u instanceof AssignStmt) { Value rhs = ((AssignStmt) u).getRightOp(); if (rhs instanceof CastExpr) { Type t = ((CastExpr) rhs).getCastType(); if (t instanceof RefType && !types.contains(t)) { types.add(t); } } } } this.emptySet = new LocalTypeSet(refLocals, types); } /** Returns a new, aggressive (local,type) set. */ @Override protected LocalTypeSet newInitialFlow() { LocalTypeSet ret = (LocalTypeSet) emptySet.clone(); ret.setAllBits(); return ret; } /** This is the flow function as described in the assignment write-up. */ @Override protected void flowThrough(LocalTypeSet in, Unit unit, List<LocalTypeSet> outFallVals, List<LocalTypeSet> outBranchVals) { final LocalTypeSet out = (LocalTypeSet) in.clone(); LocalTypeSet outBranch = out; // aliased to out unless unit is IfStmt // First kill all locals defined in this statement for (ValueBox b : unit.getDefBoxes()) { Value v = b.getValue(); if (v instanceof Local && v.getType() instanceof RefType) { out.killLocal((Local) v); } } if (unit instanceof AssignStmt) { // An AssignStmt may be a new, a simple copy, or a cast AssignStmt astmt = (AssignStmt) unit; Value rhs = astmt.getRightOp(); Value lhs = astmt.getLeftOp(); if (lhs instanceof Local && rhs.getType() instanceof RefType) { Local l = (Local) lhs; if (rhs instanceof NewExpr) { out.localMustBeSubtypeOf(l, (RefType) rhs.getType()); } else if (rhs instanceof CastExpr) { CastExpr cast = (CastExpr) rhs; Type castType = cast.getCastType(); if (castType instanceof RefType && cast.getOp() instanceof Local) { RefType refType = (RefType) castType; Local opLocal = (Local) cast.getOp(); out.localCopy(l, opLocal); out.localMustBeSubtypeOf(l, refType); out.localMustBeSubtypeOf(opLocal, refType); } } else if (rhs instanceof Local) { out.localCopy(l, (Local) rhs); } } } else if (unit instanceof IfStmt) { // Handle if statements IfStmt ifstmt = (IfStmt) unit; // This do ... while(false) is here so I can break out of it rather // than having to have seven nested if statements. Silly people who // took goto's out of the language... <grumble> <grumble> do { final List<Unit> unitPreds = graph.getPredsOf(unit); if (unitPreds.size() != 1) { break; } final Unit predecessor = unitPreds.get(0); if (!(predecessor instanceof AssignStmt)) { break; } final AssignStmt pred = (AssignStmt) predecessor; final Value predRHS = pred.getRightOp(); if (!(predRHS instanceof InstanceOfExpr)) { break; } InstanceOfExpr iofexpr = (InstanceOfExpr) predRHS; final Type iofCheckType = iofexpr.getCheckType(); if (!(iofCheckType instanceof RefType)) { break; } final Value iofOp = iofexpr.getOp(); if (!(iofOp instanceof Local)) { break; } final ConditionExpr c = (ConditionExpr) ifstmt.getCondition(); if (!c.getOp1().equals(pred.getLeftOp())) { break; } final Value conditionOp2 = c.getOp2(); if (!(conditionOp2 instanceof IntConstant)) { break; } if (((IntConstant) conditionOp2).value != 0) { break; } if (c instanceof NeExpr) { // The IfStmt is like this: // if x instanceof t goto somewhere_else // So x is of type t on the taken branch outBranch = (LocalTypeSet) out.clone(); outBranch.localMustBeSubtypeOf((Local) iofOp, (RefType) iofCheckType); } else if (c instanceof EqExpr) { // The IfStmt is like this: // if !(x instanceof t) goto somewhere_else // So x is of type t on the fallthrough branch outBranch = (LocalTypeSet) out.clone(); out.localMustBeSubtypeOf((Local) iofOp, (RefType) iofCheckType); } } while (false); } // Now copy the computed (local,type) set to all successors for (LocalTypeSet ts : outFallVals) { copy(out, ts); } for (LocalTypeSet ts : outBranchVals) { copy(outBranch, ts); } } @Override protected void copy(LocalTypeSet s, LocalTypeSet d) { d.and(s); d.or(s); } // The merge operator is set intersection. @Override protected void merge(LocalTypeSet in1, LocalTypeSet in2, LocalTypeSet o) { o.setAllBits(); o.and(in1); o.and(in2); } /** Returns a new, aggressive (local,type) set. */ @Override protected LocalTypeSet entryInitialFlow() { return (LocalTypeSet) emptySet.clone(); } }
8,106
31.821862
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/CastCheckEliminatorDumper.java
package soot.jimple.toolkits.pointer; /*- * #%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 soot.Body; import soot.BodyTransformer; import soot.G; import soot.Singletons; import soot.toolkits.graph.BriefUnitGraph; /** A body transformer that simply calls the CastCheckEliminator analysis. */ public class CastCheckEliminatorDumper extends BodyTransformer { public CastCheckEliminatorDumper(Singletons.Global g) { } public static CastCheckEliminatorDumper v() { return G.v().soot_jimple_toolkits_pointer_CastCheckEliminatorDumper(); } public String getDefaultOptions() { return ""; } @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { CastCheckEliminator cce = new CastCheckEliminator(new BriefUnitGraph(b)); } }
1,571
29.230769
91
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/CastCheckTag.java
package soot.jimple.toolkits.pointer; /*- * #%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.tagkit.Tag; /** * Implements a tag that can be used to tell a VM whether a cast check can be eliminated or not. */ public class CastCheckTag implements Tag { public static final String NAME = "CastCheckTag"; private final boolean eliminateCheck; CastCheckTag(boolean eliminateCheck) { this.eliminateCheck = eliminateCheck; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { return new byte[] { (byte) (eliminateCheck ? 1 : 0) }; } @Override public String toString() { if (eliminateCheck) { return "This cast check can be eliminated."; } else { return "This cast check should NOT be eliminated."; } } public boolean canEliminateCheck() { return eliminateCheck; } }
1,632
24.920635
96
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/CodeBlockRWSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.HashMap; import java.util.HashSet; import java.util.Map; import soot.PointsToSet; import soot.Scene; import soot.SootField; import soot.jimple.spark.pag.Node; import soot.jimple.spark.pag.PAG; import soot.jimple.spark.sets.HashPointsToSet; import soot.jimple.spark.sets.P2SetVisitor; import soot.jimple.spark.sets.PointsToSetInternal; public class CodeBlockRWSet extends MethodRWSet { @Override public String toString() { StringBuilder ret = new StringBuilder(); boolean empty = true; if (fields != null) { for (Map.Entry<Object, PointsToSet> e : fields.entrySet()) { ret.append("[Field: ").append(e.getKey()).append(' '); PointsToSet baseObj = e.getValue(); if (baseObj instanceof PointsToSetInternal) { /* * PointsToSetInternal base = (PointsToSetInternal) fields.get(field); base.forall( new P2SetVisitor() { public * void visit( Node n ) { ret.append(n.getNumber() + " "); } } ); */ int baseSize = ((PointsToSetInternal) baseObj).size(); ret.append(baseSize).append(baseSize == 1 ? " Node]\n" : " Nodes]\n"); } else { ret.append(baseObj).append("]\n"); } empty = false; } } if (globals != null) { for (SootField global : globals) { ret.append("[Global: ").append(global).append("]\n"); empty = false; } } if (empty) { ret.append("[emptyset]\n"); } return ret.toString(); } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { if (other == null || isFull) { return false; } boolean ret = false; if (other instanceof MethodRWSet) { MethodRWSet o = (MethodRWSet) other; if (o.getCallsNative()) { ret = !getCallsNative() | ret; setCallsNative(); } if (o.isFull) { ret = !isFull | ret; isFull = true; if (true) { throw new RuntimeException("attempt to add full set " + o + " into " + this); } globals = null; fields = null; return ret; } if (o.globals != null) { if (globals == null) { globals = new HashSet<SootField>(); } ret = globals.addAll(o.globals) | ret; if (globals.size() > MAX_SIZE) { globals = null; isFull = true; throw new RuntimeException("attempt to add full set " + o + " into " + this); } } if (o.fields != null) { for (Object field : o.fields.keySet()) { ret = addFieldRef(o.getBaseForField(field), field) | ret; } } } else if (other instanceof StmtRWSet) { StmtRWSet oth = (StmtRWSet) other; if (oth.base != null) { ret = addFieldRef(oth.base, oth.field) | ret; } else if (oth.field != null) { ret = addGlobal((SootField) oth.field) | ret; } } else if (other instanceof SiteRWSet) { SiteRWSet oth = (SiteRWSet) other; for (RWSet set : oth.sets) { this.union(set); } } if (!getCallsNative() && other.getCallsNative()) { setCallsNative(); return true; } return ret; } public boolean containsField(Object field) { return fields != null && fields.containsKey(field); } public CodeBlockRWSet intersection(MethodRWSet other) { // May run slowly... O(n^2) CodeBlockRWSet ret = new CodeBlockRWSet(); if (isFull) { return ret; } if (globals != null && other.globals != null && !globals.isEmpty() && !other.globals.isEmpty()) { for (SootField sg : other.globals) { if (globals.contains(sg)) { ret.addGlobal(sg); } } } if (fields != null && other.fields != null && !fields.isEmpty() && !other.fields.isEmpty()) { for (Object field : other.fields.keySet()) { if (fields.containsKey(field)) { PointsToSet pts1 = getBaseForField(field); PointsToSet pts2 = other.getBaseForField(field); if (pts1 instanceof FullObjectSet) { ret.addFieldRef(pts2, field); } else if (pts2 instanceof FullObjectSet) { ret.addFieldRef(pts1, field); } else if (pts1.hasNonEmptyIntersection(pts2)) { if ((pts1 instanceof PointsToSetInternal) && (pts2 instanceof PointsToSetInternal)) { final PointsToSetInternal pti1 = (PointsToSetInternal) pts1; final PointsToSetInternal pti2 = (PointsToSetInternal) pts2; final PointsToSetInternal newpti = new HashPointsToSet(pti1.getType(), (PAG) Scene.v().getPointsToAnalysis()); pti1.forall(new P2SetVisitor() { @Override public void visit(Node n) { if (pti2.contains(n)) { newpti.add(n); } } }); ret.addFieldRef(newpti, field); } } } } } return ret; } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { boolean ret = false; if (fields == null) { fields = new HashMap<Object, PointsToSet>(); } // Get our points-to set, merge with other PointsToSet base = getBaseForField(field); if (base instanceof FullObjectSet) { return false; } if (otherBase instanceof FullObjectSet) { fields.put(field, otherBase); return true; } if (otherBase.equals(base)) { return false; } if (base == null) { // NOTE: this line makes unsafe assumptions about the PTA base = new HashPointsToSet(((PointsToSetInternal) otherBase).getType(), (PAG) Scene.v().getPointsToAnalysis()); fields.put(field, base); } return ((PointsToSetInternal) base).addAll((PointsToSetInternal) otherBase, null) | ret; } }
6,755
30.71831
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/DependenceGraph.java
package soot.jimple.toolkits.pointer; /*- * #%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 soot.tagkit.Attribute; public class DependenceGraph implements Attribute { public static final String NAME = "DependenceGraph"; final HashSet<Edge> edges = new HashSet<Edge>(); protected class Edge { final short from; final short to; public Edge(short from, short to) { this.from = from; this.to = to; } @Override public int hashCode() { return (this.from << 16) + this.to; } @Override public boolean equals(Object other) { Edge o = (Edge) other; return this.from == o.from && this.to == o.to; } } public boolean areAdjacent(short from, short to) { if (from > to) { return areAdjacent(to, from); } if (from < 0 || to < 0) { return false; } if (from == to) { return true; } return edges.contains(new Edge(from, to)); } public void addEdge(short from, short to) { if (from < 0) { throw new RuntimeException("from < 0"); } if (to < 0) { throw new RuntimeException("to < 0"); } if (from > to) { addEdge(to, from); return; } edges.add(new Edge(from, to)); } @Override public String getName() { return NAME; } @Override public void setValue(byte[] v) { throw new RuntimeException("Not Supported"); } @Override public byte[] getValue() { byte[] ret = new byte[4 * edges.size()]; int i = 0; for (Edge e : edges) { ret[i++] = (byte) ((e.from >> 8) & 0xff); ret[i++] = (byte) (e.from & 0xff); ret[i++] = (byte) ((e.to >> 8) & 0xff); ret[i++] = (byte) (e.to & 0xff); } return ret; } @Override public String toString() { StringBuilder buf = new StringBuilder("Dependences"); for (Edge e : edges) { buf.append("( ").append(e.from).append(", ").append(e.to).append(" ) "); } return buf.toString(); } }
2,754
22.956522
78
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/DependenceTag.java
package soot.jimple.toolkits.pointer; /*- * #%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.tagkit.Tag; public class DependenceTag implements Tag { public static final String NAME = "DependenceTag"; protected short read = -1; protected short write = -1; protected boolean callsNative = false; public boolean setCallsNative() { boolean ret = !callsNative; callsNative = true; return ret; } protected void setRead(short s) { read = s; } protected void setWrite(short s) { write = s; } @Override public String getName() { return NAME; } @Override public byte[] getValue() { byte[] ret = new byte[5]; ret[0] = (byte) ((read >> 8) & 0xff); ret[1] = (byte) (read & 0xff); ret[2] = (byte) ((write >> 8) & 0xff); ret[3] = (byte) (write & 0xff); ret[4] = (byte) (callsNative ? 1 : 0); return ret; } @Override public String toString() { StringBuilder buf = new StringBuilder(); if (callsNative) { buf.append("SECallsNative\n"); } if (read >= 0) { buf.append("SEReads : ").append(read).append('\n'); } if (write >= 0) { buf.append("SEWrites: ").append(write).append('\n'); } return buf.toString(); } }
1,997
23.975
71
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/DependenceTagAggregator.java
package soot.jimple.toolkits.pointer; /*- * #%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.G; import soot.Singletons; import soot.tagkit.ImportantTagAggregator; import soot.tagkit.Tag; public class DependenceTagAggregator extends ImportantTagAggregator { public DependenceTagAggregator(Singletons.Global g) { } public static DependenceTagAggregator v() { return G.v().soot_jimple_toolkits_pointer_DependenceTagAggregator(); } /** Decide whether this tag should be aggregated by this aggregator. */ @Override public boolean wantTag(Tag t) { return (t instanceof DependenceTag); } /** Return name of the resulting aggregated tag. */ @Override public String aggregatedName() { return "SideEffectAttribute"; } }
1,507
28.568627
73
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/DumbPointerAnalysis.java
package soot.jimple.toolkits.pointer; /*- * #%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.G; import soot.Local; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.RefType; import soot.Singletons; import soot.SootField; import soot.Type; /** * A very naive pointer analysis that just reports that any points can point to any object. */ public class DumbPointerAnalysis implements PointsToAnalysis { public DumbPointerAnalysis(Singletons.Global g) { } public static DumbPointerAnalysis v() { return G.v().soot_jimple_toolkits_pointer_DumbPointerAnalysis(); } /** Returns the set of objects pointed to by variable l. */ @Override public PointsToSet reachingObjects(Local l) { Type t = l.getType(); return (t instanceof RefType) ? FullObjectSet.v((RefType) t) : FullObjectSet.v(); } /** Returns the set of objects pointed to by variable l in context c. */ @Override public PointsToSet reachingObjects(Context c, Local l) { return reachingObjects(l); } /** Returns the set of objects pointed to by static field f. */ @Override public PointsToSet reachingObjects(SootField f) { Type t = f.getType(); return (t instanceof RefType) ? FullObjectSet.v((RefType) t) : FullObjectSet.v(); } /** * Returns the set of objects pointed to by instance field f of the objects in the PointsToSet s. */ @Override public PointsToSet reachingObjects(PointsToSet s, SootField f) { return reachingObjects(f); } /** * Returns the set of objects pointed to by instance field f of the objects pointed to by l. */ @Override public PointsToSet reachingObjects(Local l, SootField f) { return reachingObjects(f); } /** * Returns the set of objects pointed to by instance field f of the objects pointed to by l in context c. */ @Override public PointsToSet reachingObjects(Context c, Local l, SootField f) { return reachingObjects(f); } /** * Returns the set of objects pointed to by elements of the arrays in the PointsToSet s. */ @Override public PointsToSet reachingObjectsOfArrayElement(PointsToSet s) { return FullObjectSet.v(); } }
2,941
28.717172
107
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/FieldRWTagger.java
package soot.jimple.toolkits.pointer; /*- * #%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.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.PhaseOptions; import soot.Scene; import soot.Singletons; import soot.Unit; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; public class FieldRWTagger extends BodyTransformer { public FieldRWTagger(Singletons.Global g) { } public static FieldRWTagger v() { return G.v().soot_jimple_toolkits_pointer_FieldRWTagger(); } public int numRWs = 0; public int numWRs = 0; public int numRRs = 0; public int numWWs = 0; public int numNatives = 0; public Date startTime = null; boolean optionDontTag = false; boolean optionNaive = false; private CallGraph cg; protected class UniqueRWSets implements Iterable<RWSet> { protected final ArrayList<RWSet> l = new ArrayList<RWSet>(); RWSet getUnique(RWSet s) { if (s != null) { for (RWSet ret : l) { if (ret.isEquivTo(s)) { return ret; } } l.add(s); } return s; } @Override public Iterator<RWSet> iterator() { return l.iterator(); } short indexOf(RWSet s) { short i = 0; for (RWSet ret : l) { if (ret.isEquivTo(s)) { return i; } i++; } return -1; } } protected void initializationStuff(String phaseName) { if (G.v().Union_factory == null) { G.v().Union_factory = new UnionFactory() { @Override public Union newUnion() { return FullObjectSet.v(); } }; } if (startTime == null) { startTime = new Date(); } cg = Scene.v().getCallGraph(); } protected Object keyFor(Stmt s) { if (s.containsInvokeExpr()) { if (optionNaive) { throw new RuntimeException("shouldn't get here"); } Iterator<Edge> it = cg.edgesOutOf(s); if (!it.hasNext()) { return Collections.emptyList(); } ArrayList<Edge> ret = new ArrayList<Edge>(); while (it.hasNext()) { ret.add(it.next()); } return ret; } else { return s; } } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { initializationStuff(phaseName); SideEffectAnalysis sea = new SideEffectAnalysis(DumbPointerAnalysis.v(), Scene.v().getCallGraph()); sea.findNTRWSets(body.getMethod()); HashMap<Object, RWSet> stmtToReadSet = new HashMap<Object, RWSet>(); HashMap<Object, RWSet> stmtToWriteSet = new HashMap<Object, RWSet>(); UniqueRWSets sets = new UniqueRWSets(); optionDontTag = PhaseOptions.getBoolean(options, "dont-tag"); final boolean justDoTotallyConservativeThing = "<clinit>".equals(body.getMethod().getName()); for (Unit u : body.getUnits()) { final Stmt stmt = (Stmt) u; if (!stmt.containsInvokeExpr()) { continue; } if (justDoTotallyConservativeThing) { stmtToReadSet.put(stmt, sets.getUnique(new FullRWSet())); stmtToWriteSet.put(stmt, sets.getUnique(new FullRWSet())); continue; } Object key = keyFor(stmt); if (!stmtToReadSet.containsKey(key)) { stmtToReadSet.put(key, sets.getUnique(sea.readSet(body.getMethod(), stmt))); stmtToWriteSet.put(key, sets.getUnique(sea.writeSet(body.getMethod(), stmt))); } } /* * DependenceGraph graph = new DependenceGraph(); for( Iterator outerIt = sets.iterator(); outerIt.hasNext(); ) { final * RWSet outer = (RWSet) outerIt.next(); * * for( Iterator innerIt = sets.iterator(); innerIt.hasNext(); ) { * * final RWSet inner = (RWSet) innerIt.next(); if( inner == outer ) break; if( outer.hasNonEmptyIntersection( inner ) ) { * graph.addEdge( sets.indexOf( outer ), sets.indexOf( inner ) ); } } } if( !optionDontTag ) { body.getMethod().addTag( * graph ); } for( Iterator stmtIt = body.getUnits().iterator(); stmtIt.hasNext(); ) { final Stmt stmt = (Stmt) * stmtIt.next(); Object key; if( optionNaive && stmt.containsInvokeExpr() ) { key = stmt; } else { key = keyFor( stmt ); * } RWSet read = (RWSet) stmtToReadSet.get( key ); RWSet write = (RWSet) stmtToWriteSet.get( key ); if( read != null || * write != null ) { DependenceTag tag = new DependenceTag(); if( read != null && read.getCallsNative() ) { * tag.setCallsNative(); numNatives++; } else if( write != null && write.getCallsNative() ) { tag.setCallsNative(); * numNatives++; } tag.setRead( sets.indexOf( read ) ); tag.setWrite( sets.indexOf( write ) ); if( !optionDontTag ) * stmt.addTag( tag ); * * // The loop below is just fro calculating stats. if( !justDoTotallyConservativeThing ) { for( Iterator innerIt = * body.getUnits().iterator(); innerIt.hasNext(); ) { final Stmt inner = (Stmt) innerIt.next(); Object ikey; if( * optionNaive && inner.containsInvokeExpr() ) { ikey = inner; } else { ikey = keyFor( inner ); } RWSet innerRead = * (RWSet) stmtToReadSet.get( ikey ); RWSet innerWrite = (RWSet) stmtToWriteSet.get( ikey ); if( graph.areAdjacent( * sets.indexOf( read ), sets.indexOf( innerWrite ) ) ) numRWs++; if( graph.areAdjacent( sets.indexOf( write ), * sets.indexOf( innerRead ) ) ) numWRs++; if( inner == stmt ) continue; if( graph.areAdjacent( sets.indexOf( write ), * sets.indexOf( innerWrite ) ) ) numWWs++; if( graph.areAdjacent( sets.indexOf( read ), sets.indexOf( innerRead ) ) ) * numRRs++; } } } } */ } }
6,540
35.138122
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/FullObjectSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.Collections; import java.util.Set; import soot.AnySubType; import soot.G; import soot.PointsToSet; import soot.RefType; import soot.Singletons; import soot.Type; import soot.jimple.ClassConstant; public class FullObjectSet extends Union { private final Set<Type> types; public static FullObjectSet v() { return G.v().soot_jimple_toolkits_pointer_FullObjectSet(); } public static FullObjectSet v(RefType t) { return ("java.lang.Object".equals(t.getClassName())) ? v() : new FullObjectSet(t); } public FullObjectSet(Singletons.Global g) { this(RefType.v("java.lang.Object")); } private FullObjectSet(RefType declaredType) { this.types = Collections.singleton(AnySubType.v(declaredType)); } public Type type() { return types.iterator().next(); } /** Returns true if this set contains no run-time objects. */ @Override public boolean isEmpty() { return false; } /** Returns true if this set is a subset of other. */ @Override public boolean hasNonEmptyIntersection(PointsToSet other) { return other != null; } /** Set of all possible run-time types of objects in the set. */ @Override public Set<Type> possibleTypes() { return types; } /** * Adds all objects in s into this union of sets, returning true if this union was changed. */ @Override public boolean addAll(PointsToSet s) { return false; } @Override public Set<String> possibleStringConstants() { return null; } @Override public Set<ClassConstant> possibleClassConstants() { return null; } public int depth() { return 0; } }
2,473
23.74
93
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/FullRWSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.Set; import soot.PointsToSet; import soot.SootField; public class FullRWSet extends RWSet { @Override public int size() { throw new RuntimeException("Unsupported"); } @Override public boolean getCallsNative() { return true; } @Override public boolean setCallsNative() { throw new RuntimeException("Unsupported"); } /** Returns an iterator over any globals read/written. */ @Override public Set getGlobals() { throw new RuntimeException("Unsupported"); } @Override public Set getFields() { throw new RuntimeException("Unsupported"); } @Override public PointsToSet getBaseForField(Object f) { throw new RuntimeException("Unsupported"); } @Override public boolean hasNonEmptyIntersection(RWSet other) { return other != null; } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { throw new RuntimeException("Unsupported"); } @Override public boolean addGlobal(SootField global) { throw new RuntimeException("Unsupported"); } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { throw new RuntimeException("Unsupported"); } @Override public boolean isEquivTo(RWSet other) { return other instanceof FullRWSet; } }
2,149
23.157303
71
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/InstanceKey.java
package soot.jimple.toolkits.pointer; /*- * #%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.Local; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.RefLikeType; import soot.Scene; import soot.SootMethod; import soot.jimple.Stmt; import soot.jimple.spark.sets.EqualsSupportingPointsToSet; import soot.jimple.spark.sets.PointsToSetEqualsWrapper; /** * An instance key is a static representative of a runtime object. An instance key, if based on a * {@link StrongLocalMustAliasAnalysis}, is guaranteed to represent a single runtime object within a its declared method. If * based on a (non-strong) {@link LocalMustAliasAnalysis}, it represents the value of a variable at a single location, which * itself can represent multiple runtime objects, if the location is contained in a loop. * * See Sable TR 2007-8 for details. * * @author Eric Bodden */ public class InstanceKey { protected final Local assignedLocal; protected final LocalMustAliasAnalysis lmaa; protected final LocalMustNotAliasAnalysis lnma; protected final Stmt stmtAfterAssignStmt; protected final SootMethod owner; protected final int hashCode; protected final PointsToSet pts; /** * Creates a new instance key representing the value stored in local, just before stmt. The identity of the key is defined * via lmaa, and its must-not-alias relationship to other keys via lmna. * * @param local * the local variable whose value this key represents * @param stmt * the statement at which this key represents the value * @param owner * the method containing local * @param lmaa * a {@link LocalMustAliasAnalysis} * @param lmna * a {@link LocalMustNotAliasAnalysis} */ public InstanceKey(Local local, Stmt stmt, SootMethod owner, LocalMustAliasAnalysis lmaa, LocalMustNotAliasAnalysis lmna) { this.assignedLocal = local; this.owner = owner; this.stmtAfterAssignStmt = stmt; this.lmaa = lmaa; this.lnma = lmna; PointsToAnalysis pta = Scene.v().getPointsToAnalysis(); this.pts = new PointsToSetEqualsWrapper((EqualsSupportingPointsToSet) pta.reachingObjects(local)); this.hashCode = computeHashCode(); } public boolean mustAlias(InstanceKey otherKey) { if (stmtAfterAssignStmt == null || otherKey.stmtAfterAssignStmt == null) { // don't know return false; } return lmaa.mustAlias(assignedLocal, stmtAfterAssignStmt, otherKey.assignedLocal, otherKey.stmtAfterAssignStmt); } public boolean mayNotAlias(InstanceKey otherKey) { if (owner.equals(otherKey.owner) && stmtAfterAssignStmt != null && otherKey.stmtAfterAssignStmt != null) { if (lnma.notMayAlias(assignedLocal, stmtAfterAssignStmt, otherKey.assignedLocal, otherKey.stmtAfterAssignStmt)) { return true; } } // different methods or local not-may-alias was not successful: get points-to info if (Scene.v().getPointsToAnalysis() == null) { // no info; hence don't know for sure return false; } else { // may not alias if we have an empty intersection return !pts.hasNonEmptyIntersection(otherKey.pts); } } public PointsToSet getPointsToSet() { return pts; } public Local getLocal() { return assignedLocal; } public boolean haveLocalInformation() { return stmtAfterAssignStmt != null; } @Override public String toString() { String instanceKeyString = stmtAfterAssignStmt != null ? lmaa.instanceKeyString(assignedLocal, stmtAfterAssignStmt) : "pts(" + hashCode + ")"; return instanceKeyString + "(" + assignedLocal.getName() + ")"; } /** * {@inheritDoc} */ @Override public int hashCode() { return hashCode; } /** * (Pre)computes the hash code. */ protected int computeHashCode() { final int prime = 31; int result = 1; result = prime * result + ((owner == null) ? 0 : owner.hashCode()); if (stmtAfterAssignStmt != null && (assignedLocal.getType() instanceof RefLikeType)) { // compute hash code based on instance key string result = prime * result + lmaa.instanceKeyString(assignedLocal, stmtAfterAssignStmt).hashCode(); } else if (stmtAfterAssignStmt == null) { result = prime * result + pts.hashCode(); } return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final InstanceKey other = (InstanceKey) obj; if (this.owner == null) { if (other.owner != null) { return false; } } else if (!this.owner.equals(other.owner)) { return false; } // two keys are equal if they must alias if (mustAlias(other)) { return true; } // or if both have no statement set but the same local return (this.stmtAfterAssignStmt == null && other.stmtAfterAssignStmt == null && this.pts.equals(other.pts)); } public boolean isOfReferenceType() { assert assignedLocal.getType() instanceof RefLikeType; return true; } public SootMethod getOwner() { return owner; } public Stmt getStmt() { return stmtAfterAssignStmt; } }
6,038
31.12234
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/LocalMayAliasAnalysis.java
package soot.jimple.toolkits.pointer; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2014 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.Collections; import java.util.HashSet; import java.util.Set; import soot.Body; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.Constant; import soot.jimple.DefinitionStmt; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ForwardFlowAnalysis; /** * Conducts a method-local, equality-based may-alias analysis. * * @author Eric Bodden */ public class LocalMayAliasAnalysis extends ForwardFlowAnalysis<Unit, Set<Set<Value>>> { private final Body body; public LocalMayAliasAnalysis(UnitGraph graph) { super(graph); this.body = graph.getBody(); doAnalysis(); } @Override protected void flowThrough(Set<Set<Value>> source, Unit unit, Set<Set<Value>> target) { target.addAll(source); if (unit instanceof DefinitionStmt) { DefinitionStmt def = (DefinitionStmt) unit; Value left = def.getLeftOp(); Value right = def.getRightOp(); if (right instanceof Constant) { // find the sets containing the left Set<Value> leftSet = null; for (Set<Value> s : source) { if (s.contains(left)) { leftSet = s; break; } } if (leftSet == null) { throw new RuntimeException("internal error"); } // remove left from this set target.remove(leftSet); HashSet<Value> setWithoutLeft = new HashSet<Value>(leftSet); setWithoutLeft.remove(left); target.add(setWithoutLeft); // add left on its own target.add(Collections.singleton(left)); } else { // find the sets containing the left and right hand sides Set<Value> leftSet = null, rightSet = null; for (Set<Value> s : source) { if (s.contains(left)) { leftSet = s; break; } } for (Set<Value> s : source) { if (s.contains(right)) { rightSet = s; break; } } if (leftSet == null || rightSet == null) { throw new RuntimeException("internal error"); } // replace the sets by their union target.remove(leftSet); target.remove(rightSet); HashSet<Value> union = new HashSet<Value>(leftSet); union.addAll(rightSet); target.add(union); } } } @Override protected void copy(Set<Set<Value>> source, Set<Set<Value>> target) { target.clear(); target.addAll(source); } @Override protected Set<Set<Value>> entryInitialFlow() { // initially all values only alias themselves Set<Set<Value>> res = new HashSet<Set<Value>>(); for (ValueBox vb : body.getUseAndDefBoxes()) { res.add(Collections.singleton(vb.getValue())); } return res; } @Override protected void merge(Set<Set<Value>> source1, Set<Set<Value>> source2, Set<Set<Value>> target) { // we could instead also merge all sets that are non-disjoint target.clear(); target.addAll(source1); target.addAll(source2); } @Override protected Set<Set<Value>> newInitialFlow() { return new HashSet<Set<Value>>(); } /** * Returns true if v1 and v2 may alias before u. */ public boolean mayAlias(Value v1, Value v2, Unit u) { for (Set<Value> set : getFlowBefore(u)) { if (set.contains(v1) && set.contains(v2)) { return true; } } return false; } /** * Returns all values that may-alias with v before u. */ public Set<Value> mayAliases(Value v, Unit u) { Set<Value> res = new HashSet<Value>(); for (Set<Value> set : getFlowBefore(u)) { if (set.contains(v)) { res.addAll(set); } } return res; } /** * Returns all values that may-alias with v at the end of the procedure. */ public Set<Value> mayAliasesAtExit(Value v) { Set<Value> res = new HashSet<Value>(); for (Unit u : graph.getTails()) { for (Set<Value> set : getFlowAfter(u)) { if (set.contains(v)) { res.addAll(set); } } } return res; } }
4,923
26.977273
98
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/LocalMustAliasAnalysis.java
package soot.jimple.toolkits.pointer; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2007 Patrick Lam * 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.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import soot.EquivalentValue; import soot.Local; import soot.MethodOrMethodContext; import soot.RefLikeType; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.CastExpr; import soot.jimple.DefinitionStmt; import soot.jimple.FieldRef; import soot.jimple.IdentityRef; import soot.jimple.ParameterRef; import soot.jimple.Stmt; import soot.jimple.ThisRef; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ForwardFlowAnalysis; /** * LocalMustAliasAnalysis attempts to determine if two local variables (at two potentially different program points) must * point to the same object. * * The underlying abstraction is based on global value numbering. * * See also {@link StrongLocalMustAliasAnalysis} for an analysis that soundly treats redefinitions within loops. * * See Sable TR 2007-8 for details. * * P.S. The idea behind this analysis and the way it assigns numbers is very similar to what is described in the paper: * Lapkowski, C. and Hendren, L. J. 1996. Extended SSA numbering: introducing SSA properties to languages with multi-level * pointers. In Proceedings of the 1996 Conference of the Centre For Advanced Studies on Collaborative Research (Toronto, * Ontario, Canada, November 12 - 14, 1996). M. Bauer, K. Bennet, M. Gentleman, H. Johnson, K. Lyons, and J. Slonim, Eds. IBM * Centre for Advanced Studies Conference. IBM Press, 23. * * Only major differences: Here we only use primary numbers, no secondary numbers. Further, we use the call graph to * determine fields that are not written to in the transitive closure of this method's execution. A third difference is that * we assign fixed values to {@link IdentityRef}s, because those never change during one execution. * * @author Patrick Lam * @author Eric Bodden * @see StrongLocalMustAliasAnalysis */ public class LocalMustAliasAnalysis extends ForwardFlowAnalysis<Unit, HashMap<Value, Integer>> { /** * The set of all local variables and field references that we track. This set contains objects of type {@link Local} and, * if tryTrackFieldAssignments is enabled, it may also contain {@link EquivalentValue}s of {@link FieldRef}s. If so, these * field references are to be tracked on the same way as {@link Local}s are. */ protected Set<Value> localsAndFieldRefs; /** maps from right-hand side expressions (non-locals) to value numbers */ protected transient Map<Value, Integer> rhsToNumber; /** maps from a merge point (a unit) and a value to the unique value number of that value at this point */ protected transient Map<Unit, Map<Value, Integer>> mergePointToValueToNumber; /** the next value number */ protected int nextNumber = 1; /** the containing method */ protected SootMethod container; /** * Creates a new {@link LocalMustAliasAnalysis} tracking local variables. */ public LocalMustAliasAnalysis(UnitGraph g) { this(g, false); } /** * Creates a new {@link LocalMustAliasAnalysis}. If tryTrackFieldAssignments, we run an interprocedural side-effects * analysis to determine which fields are (transitively) written to by this method. All fields which that are not written * to are tracked just as local variables. This semantics is sound for single-threaded programs. */ public LocalMustAliasAnalysis(UnitGraph g, boolean tryTrackFieldAssignments) { super(g); this.container = g.getBody().getMethod(); this.localsAndFieldRefs = new HashSet<Value>(); // add all locals for (Local l : g.getBody().getLocals()) { if (l.getType() instanceof RefLikeType) { this.localsAndFieldRefs.add(l); } } if (tryTrackFieldAssignments) { this.localsAndFieldRefs.addAll(trackableFields()); } this.rhsToNumber = new HashMap<Value, Integer>(); this.mergePointToValueToNumber = new HashMap<Unit, Map<Value, Integer>>(); doAnalysis(); // not needed any more this.rhsToNumber = null; this.mergePointToValueToNumber = null; } /** * Computes the set of {@link EquivalentValue}s of all field references that are used in this method but not set by the * method or any method transitively called by this method. */ private Set<Value> trackableFields() { Set<Value> usedFieldRefs = new HashSet<Value>(); // add all field references that are in use boxes for (Unit unit : this.graph) { for (ValueBox useBox : unit.getUseBoxes()) { Value val = useBox.getValue(); if (val instanceof FieldRef) { FieldRef fieldRef = (FieldRef) val; if (fieldRef.getType() instanceof RefLikeType) { usedFieldRefs.add(new EquivalentValue(fieldRef)); } } } } // prune all fields that are written to if (!usedFieldRefs.isEmpty()) { if (!Scene.v().hasCallGraph()) { throw new IllegalStateException("No call graph found!"); } ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), Collections.<MethodOrMethodContext>singletonList(container)); reachableMethods.update(); for (Iterator<MethodOrMethodContext> iterator = reachableMethods.listener(); iterator.hasNext();) { SootMethod m = (SootMethod) iterator.next(); // exclude static initializer of same class (assume that it has already been executed) if (m.hasActiveBody() && !(SootMethod.staticInitializerName.equals(m.getName()) && m.getDeclaringClass().equals(container.getDeclaringClass()))) { for (Unit u : m.getActiveBody().getUnits()) { for (ValueBox defBox : u.getDefBoxes()) { Value value = defBox.getValue(); if (value instanceof FieldRef) { usedFieldRefs.remove(new EquivalentValue(value)); } } } } } } return usedFieldRefs; } @Override protected void merge(Unit succUnit, HashMap<Value, Integer> inMap1, HashMap<Value, Integer> inMap2, HashMap<Value, Integer> outMap) { for (Value l : localsAndFieldRefs) { Integer i1 = inMap1.get(l), i2 = inMap2.get(l); if (i1 == null) { outMap.put(l, i2); } else if (i2 == null) { outMap.put(l, i1); } else if (i1.equals(i2)) { outMap.put(l, i1); } else { /* * Merging two different values is tricky... A naive approach would be to assign UNKNOWN. However, that would lead to * imprecision in the following case: * * x = null; if(p) x = new X(); y = x; z = x; * * Even though it is obvious that after this block y and z are aliased, both would be UNKNOWN :-( Hence, when merging * the numbers for the two branches (null, new X()), we assign a value number that is unique to that merge location. * Consequently, both y and z is assigned that same number! In the following it is important that we use an * IdentityHashSet because we want the number to be unique to the location. Using a normal HashSet would make it * unique to the contents. (Eric) */ // retrieve the unique number for l at the merge point succUnit // if there is no such number yet, generate one // then assign the number to l in the outMap Integer number = null; Map<Value, Integer> valueToNumber = mergePointToValueToNumber.get(succUnit); if (valueToNumber == null) { valueToNumber = new HashMap<Value, Integer>(); mergePointToValueToNumber.put(succUnit, valueToNumber); } else { number = valueToNumber.get(l); } if (number == null) { number = nextNumber++; valueToNumber.put(l, number); } outMap.put(l, number); } } } @Override protected void flowThrough(HashMap<Value, Integer> in, Unit u, HashMap<Value, Integer> out) { out.clear(); out.putAll(in); if (u instanceof DefinitionStmt) { DefinitionStmt ds = (DefinitionStmt) u; Value lhs = ds.getLeftOp(); Value rhs = ds.getRightOp(); if (rhs instanceof CastExpr) { // un-box casted value rhs = ((CastExpr) rhs).getOp(); } if ((lhs instanceof Local || (lhs instanceof FieldRef && this.localsAndFieldRefs.contains(new EquivalentValue(lhs)))) && lhs.getType() instanceof RefLikeType) { if (rhs instanceof Local) { // local-assignment - must be aliased... Integer val = in.get(rhs); if (val != null) { out.put(lhs, val); } } else if (rhs instanceof ThisRef) { // ThisRef can never change; assign unique number out.put(lhs, thisRefNumber()); } else if (rhs instanceof ParameterRef) { // ParameterRef can never change; assign unique number out.put(lhs, parameterRefNumber((ParameterRef) rhs)); } else { // assign number for expression out.put(lhs, numberOfRhs(rhs)); } } } else { // which other kind of statement has def-boxes? hopefully none... assert u.getDefBoxes().isEmpty(); } } private Integer numberOfRhs(Value rhs) { EquivalentValue equivValue = new EquivalentValue(rhs); if (localsAndFieldRefs.contains(equivValue)) { rhs = equivValue; } Integer num = rhsToNumber.get(rhs); if (num == null) { num = nextNumber++; rhsToNumber.put(rhs, num); } return num; } public static int thisRefNumber() { // unique number for ThisRef (must be <1) return 0; } public static int parameterRefNumber(ParameterRef r) { // unique number for ParameterRef[i] (must be <0) return -1 - r.getIndex(); } @Override protected void copy(HashMap<Value, Integer> sourceMap, HashMap<Value, Integer> destMap) { destMap.clear(); destMap.putAll(sourceMap); } /** Initial most conservative value: We leave it away to save memory, implicitly UNKNOWN. */ @Override protected HashMap<Value, Integer> entryInitialFlow() { return new HashMap<Value, Integer>(); } /** Initial bottom value: objects have no definitions. */ @Override protected HashMap<Value, Integer> newInitialFlow() { return new HashMap<Value, Integer>(); } /** * Returns a string (natural number) representation of the instance key associated with l at statement s or * <code>null</code> if there is no such key associated. * * @param l * any local of the associated method * @param s * the statement at which to check */ public String instanceKeyString(Local l, Stmt s) { Integer ln = getFlowBefore(s).get(l); return (ln == null) ? null : ln.toString(); } /** * Returns true if this analysis has any information about local l at statement s. In particular, it is safe to pass in * locals/statements that are not even part of the right method. In those cases <code>false</code> will be returned. * Permits s to be <code>null</code>, in which case <code>false</code> will be returned. */ public boolean hasInfoOn(Local l, Stmt s) { return getFlowBefore(s) != null; } /** * @return true if values of l1 (at s1) and l2 (at s2) have the exact same object IDs, i.e. at statement s1 the variable l1 * must point to the same object as l2 at s2. */ public boolean mustAlias(Local l1, Stmt s1, Local l2, Stmt s2) { Integer l1n = getFlowBefore(s1).get(l1); Integer l2n = getFlowBefore(s2).get(l2); return l1n != null && l2n != null && l1n.equals(l2n); } @Override protected void merge(HashMap<Value, Integer> in1, HashMap<Value, Integer> in2, HashMap<Value, Integer> out) { // Copy over in1. This will be the baseline out.putAll(in1); // Merge in in2. Make sure that we do not have ambiguous values. for (Value val : in2.keySet()) { Integer i1 = in1.get(val); Integer i2 = in2.get(val); if (i2.equals(i1)) { out.put(val, i2); } else { throw new RuntimeException("Merge of different IDs not supported"); } } } }
13,271
35.662983
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/LocalMustNotAliasAnalysis.java
package soot.jimple.toolkits.pointer; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2007 Patrick Lam * %% * 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.Set; import soot.Body; import soot.Local; import soot.RefType; import soot.Unit; import soot.Value; import soot.jimple.DefinitionStmt; import soot.jimple.NewExpr; import soot.jimple.Stmt; import soot.jimple.internal.AbstractNewExpr; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.graph.UnitGraph; import soot.toolkits.scalar.ForwardFlowAnalysis; /** * LocalNotMayAliasAnalysis attempts to determine if two local variables (at two potentially different program points) * definitely point to different objects. * * The underlying abstraction is that of definition expressions. When a local variable gets assigned a new object (unlike * LocalMust, only NewExprs), the analysis tracks the source of the value. If two variables have different sources, then they * are different. * * See Sable TR 2007-8 for details. * * @author Patrick Lam */ public class LocalMustNotAliasAnalysis extends ForwardFlowAnalysis<Unit, HashMap<Local, Set<NewExpr>>> { @SuppressWarnings("serial") protected static final NewExpr UNKNOWN = new AbstractNewExpr() { @Override public String toString() { return "UNKNOWN"; } @Override public Object clone() { return this; } }; protected final Set<Local> locals; public LocalMustNotAliasAnalysis(UnitGraph g) { this(g, g.getBody()); } public LocalMustNotAliasAnalysis(DirectedGraph<Unit> directedGraph, Body b) { super(directedGraph); this.locals = new HashSet<Local>(b.getLocals()); doAnalysis(); } @Override protected void merge(HashMap<Local, Set<NewExpr>> in1, HashMap<Local, Set<NewExpr>> in2, HashMap<Local, Set<NewExpr>> o) { for (Local l : locals) { Set<NewExpr> l1 = in1.get(l), l2 = in2.get(l); Set<NewExpr> out = o.get(l); out.clear(); if (l1.contains(UNKNOWN) || l2.contains(UNKNOWN)) { out.add(UNKNOWN); } else { out.addAll(l1); out.addAll(l2); } } } @Override protected void flowThrough(HashMap<Local, Set<NewExpr>> in, Unit unit, HashMap<Local, Set<NewExpr>> out) { out.clear(); out.putAll(in); if (unit instanceof DefinitionStmt) { DefinitionStmt ds = (DefinitionStmt) unit; Value lhs = ds.getLeftOp(); if (lhs instanceof Local) { HashSet<NewExpr> lv = new HashSet<NewExpr>(); out.put((Local) lhs, lv); Value rhs = ds.getRightOp(); if (rhs instanceof NewExpr) { lv.add((NewExpr) rhs); } else if (rhs instanceof Local) { lv.addAll(in.get((Local) rhs)); } else { lv.add(UNKNOWN); } } } } @Override protected void copy(HashMap<Local, Set<NewExpr>> source, HashMap<Local, Set<NewExpr>> dest) { dest.putAll(source); } @Override protected HashMap<Local, Set<NewExpr>> entryInitialFlow() { HashMap<Local, Set<NewExpr>> m = new HashMap<Local, Set<NewExpr>>(); for (Local l : locals) { HashSet<NewExpr> s = new HashSet<NewExpr>(); s.add(UNKNOWN); m.put(l, s); } return m; } @Override protected HashMap<Local, Set<NewExpr>> newInitialFlow() { HashMap<Local, Set<NewExpr>> m = new HashMap<Local, Set<NewExpr>>(); for (Local l : locals) { m.put(l, new HashSet<NewExpr>()); } return m; } /** * Returns true if this analysis has any information about local l at statement s (i.e. it is not {@link #UNKNOWN}). In * particular, it is safe to pass in locals/statements that are not even part of the right method. In those cases * <code>false</code> will be returned. Permits s to be <code>null</code>, in which case <code>false</code> will be * returned. */ public boolean hasInfoOn(Local l, Stmt s) { HashMap<Local, Set<NewExpr>> flowBefore = getFlowBefore(s); if (flowBefore == null) { return false; } else { Set<NewExpr> info = flowBefore.get(l); return info != null && !info.contains(UNKNOWN); } } /** * @return true if values of l1 (at s1) and l2 (at s2) are known to point to different objects */ public boolean notMayAlias(Local l1, Stmt s1, Local l2, Stmt s2) { Set<NewExpr> l1n = getFlowBefore(s1).get(l1); Set<NewExpr> l2n = getFlowBefore(s2).get(l2); if (l1n.contains(UNKNOWN) || l2n.contains(UNKNOWN)) { return false; } Set<NewExpr> n = new HashSet<NewExpr>(l1n); n.retainAll(l2n); return n.isEmpty(); } /** * If the given local at the given statement was initialized with a single, concrete new-expression then the type of this * expression is returned. Otherwise this method returns null. */ public RefType concreteType(Local l, Stmt s) { Set<NewExpr> set = getFlowBefore(s).get(l); if (set.size() != 1) { return null; } else { NewExpr singleNewExpr = set.iterator().next(); return (singleNewExpr == UNKNOWN) ? null : (RefType) singleNewExpr.getType(); } } }
5,841
29.586387
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/LocalTypeSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.FastHierarchy; import soot.Local; import soot.RefType; import soot.Scene; import soot.Type; /** Represents a set of (local,type) pairs using a bit-vector. */ class LocalTypeSet extends java.util.BitSet { private static final Logger logger = LoggerFactory.getLogger(LocalTypeSet.class); protected final List<Local> locals; protected final List<Type> types; /** * Constructs a new empty set given a list of all locals and types that may ever be in the set. */ public LocalTypeSet(List<Local> locals, List<Type> types) { super(locals.size() * types.size()); this.locals = locals; this.types = types; // Make sure that we have a hierarchy Scene.v().getOrMakeFastHierarchy(); } /** Returns the number of the bit corresponding to the pair (l,t). */ protected int indexOf(Local l, RefType t) { int index_l = locals.indexOf(l); int index_t = types.indexOf(t); if (index_l == -1 || index_t == -1) { throw new RuntimeException("Invalid local or type in LocalTypeSet"); } return index_l * types.size() + index_t; } /** Removes all pairs corresponding to local l from the set. */ public void killLocal(Local l) { int typesSize = types.size(); int base = typesSize * locals.indexOf(l); for (int i = 0; i < typesSize; i++) { clear(i + base); } } /** For each pair (from,t), adds a pair (to,t). */ public void localCopy(Local to, Local from) { int typesSize = types.size(); int baseTo = typesSize * locals.indexOf(to); int baseFrom = typesSize * locals.indexOf(from); for (int i = 0; i < typesSize; i++) { if (get(i + baseFrom)) { set(i + baseTo); } else { clear(i + baseTo); } } } /** Empties the set. */ public void clearAllBits() { for (int i = 0, e = types.size() * locals.size(); i < e; i++) { clear(i); } } /** Fills the set to contain all possible (local,type) pairs. */ public void setAllBits() { for (int i = 0, e = types.size() * locals.size(); i < e; i++) { set(i); } } /** Adds to the set all pairs (l,type) where type is any supertype of t. */ public void localMustBeSubtypeOf(Local l, RefType t) { FastHierarchy fh = Scene.v().getFastHierarchy(); for (Type type : types) { RefType supertype = (RefType) type; if (fh.canStoreType(t, supertype)) { set(indexOf(l, supertype)); } } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Local l : locals) { for (Type t : types) { RefType rt = (RefType) t; int index = indexOf(l, rt); // logger.debug("for: " + l + " and type: " + rt + " at: " + index); if (get(index)) { sb.append("((").append(l).append(',').append(rt).append(") -> elim cast check) "); } } } return sb.toString(); } }
3,828
28.682171
97
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/MemoryEfficientRasUnion.java
package soot.jimple.toolkits.pointer; /*- * #%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.Collections; import java.util.HashSet; import java.util.Set; import soot.PointsToSet; import soot.Type; public class MemoryEfficientRasUnion extends Union { HashSet<PointsToSet> subsets; @Override public boolean isEmpty() { if (subsets != null) { for (PointsToSet subset : subsets) { if (!subset.isEmpty()) { return false; } } } return true; } @Override public boolean hasNonEmptyIntersection(PointsToSet other) { if (subsets == null) { return true; } for (PointsToSet subset : subsets) { if (other instanceof Union) { if (other.hasNonEmptyIntersection(subset)) { return true; } } else { if (subset.hasNonEmptyIntersection(other)) { return true; } } } return false; } @Override public boolean addAll(PointsToSet s) { if (subsets == null) { subsets = new HashSet<PointsToSet>(); } if (s instanceof MemoryEfficientRasUnion) { MemoryEfficientRasUnion meru = (MemoryEfficientRasUnion) s; if (meru.subsets == null || this.subsets.containsAll(meru.subsets)) { return false; } return this.subsets.addAll(meru.subsets); } else { return this.subsets.add(s); } } @Override public Object clone() { MemoryEfficientRasUnion ret = new MemoryEfficientRasUnion(); ret.addAll(this); return ret; } @Override public Set<Type> possibleTypes() { if (subsets == null) { return Collections.emptySet(); } else { HashSet<Type> ret = new HashSet<Type>(); for (PointsToSet subset : subsets) { ret.addAll(subset.possibleTypes()); } return ret; } } /** * {@inheritDoc} */ @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((subsets == null) ? 0 : subsets.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final MemoryEfficientRasUnion other = (MemoryEfficientRasUnion) obj; if (this.subsets == null) { if (other.subsets != null) { return false; } } else if (!this.subsets.equals(other.subsets)) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { return (subsets == null) ? "[]" : subsets.toString(); } }
3,427
22.479452
75
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/MethodRWSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.G; import soot.PointsToSet; import soot.SootField; /** Represents the read or write set of a statement. */ public class MethodRWSet extends RWSet { private static final Logger logger = LoggerFactory.getLogger(MethodRWSet.class); public static final int MAX_SIZE = Integer.MAX_VALUE; public Set<SootField> globals; public Map<Object, PointsToSet> fields; protected boolean callsNative = false; protected boolean isFull = false; // static int count = 0; public MethodRWSet() { /* * count++; if( 0 == (count % 1000) ) { logger.debug(""+ "Created "+count+"th MethodRWSet" ); } */ } @Override public String toString() { StringBuilder ret = new StringBuilder(); boolean empty = true; if (fields != null) { for (Map.Entry<Object, PointsToSet> e : fields.entrySet()) { ret.append("[Field: ").append(e.getKey()).append(' ').append(e.getValue()).append("]\n"); empty = false; } } if (globals != null) { for (SootField global : globals) { ret.append("[Global: ").append(global).append("]\n"); empty = false; } } if (empty) { ret.append("empty"); } return ret.toString(); } @Override public int size() { if (globals == null) { return (fields == null) ? 0 : fields.size(); } else if (fields == null) { return globals.size(); } else { return globals.size() + fields.size(); } } @Override public boolean getCallsNative() { return callsNative; } @Override public boolean setCallsNative() { boolean ret = !callsNative; callsNative = true; return ret; } /** Returns an iterator over any globals read/written. */ @Override public Set<SootField> getGlobals() { if (isFull) { return G.v().MethodRWSet_allGlobals; } return (globals == null) ? Collections.emptySet() : globals; } /** Returns an iterator over any fields read/written. */ @Override public Set<Object> getFields() { if (isFull) { return G.v().MethodRWSet_allFields; } return (fields == null) ? Collections.emptySet() : fields.keySet(); } /** Returns a set of base objects whose field f is read/written. */ @Override public PointsToSet getBaseForField(Object f) { if (isFull) { return FullObjectSet.v(); } return (fields == null) ? null : fields.get(f); } @Override public boolean hasNonEmptyIntersection(RWSet oth) { if (isFull) { return oth != null; } if (!(oth instanceof MethodRWSet)) { return oth.hasNonEmptyIntersection(this); } MethodRWSet other = (MethodRWSet) oth; if (globals != null && other.globals != null && !globals.isEmpty() && !other.globals.isEmpty()) { for (SootField next : other.globals) { if (globals.contains(next)) { return true; } } } if (fields != null && other.fields != null && !fields.isEmpty() && !other.fields.isEmpty()) { for (Object field : other.fields.keySet()) { if (fields.containsKey(field)) { if (Union.hasNonEmptyIntersection(getBaseForField(field), other.getBaseForField(field))) { return true; } } } } return false; } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { if (other == null || isFull) { return false; } boolean ret = false; if (other instanceof MethodRWSet) { MethodRWSet o = (MethodRWSet) other; if (o.getCallsNative()) { ret = !getCallsNative() | ret; setCallsNative(); } if (o.isFull) { ret = !isFull | ret; isFull = true; if (true) { throw new RuntimeException("attempt to add full set " + o + " into " + this); } globals = null; fields = null; return ret; } if (o.globals != null) { if (globals == null) { globals = new HashSet<SootField>(); } ret = globals.addAll(o.globals) | ret; if (globals.size() > MAX_SIZE) { globals = null; isFull = true; throw new RuntimeException("attempt to add full set " + o + " into " + this); } } if (o.fields != null) { for (Object field : o.fields.keySet()) { ret = addFieldRef(o.getBaseForField(field), field) | ret; } } } else { StmtRWSet oth = (StmtRWSet) other; if (oth.base != null) { ret = addFieldRef(oth.base, oth.field) | ret; } else if (oth.field != null) { ret = addGlobal((SootField) oth.field) | ret; } } if (!getCallsNative() && other.getCallsNative()) { setCallsNative(); return true; } return ret; } @Override public boolean addGlobal(SootField global) { if (globals == null) { globals = new HashSet<SootField>(); } boolean ret = globals.add(global); if (globals.size() > MAX_SIZE) { globals = null; isFull = true; throw new RuntimeException("attempt to add more than " + MAX_SIZE + " globals into " + this); } return ret; } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { boolean ret = false; if (fields == null) { fields = new HashMap<Object, PointsToSet>(); } PointsToSet base = getBaseForField(field); if (base instanceof FullObjectSet) { return false; } if (otherBase instanceof FullObjectSet) { fields.put(field, otherBase); return true; } if (otherBase.equals(base)) { return false; } Union u; if (base == null || !(base instanceof Union)) { u = G.v().Union_factory.newUnion(); if (base != null) { u.addAll(base); } fields.put(field, u); if (base == null) { addedField(fields.size()); } ret = true; if (fields.keySet().size() > MAX_SIZE) { fields = null; isFull = true; if (true) { throw new RuntimeException("attempt to add more than " + MAX_SIZE + " fields into " + this); } return true; } } else { u = (Union) base; } ret = u.addAll(otherBase) | ret; return ret; } static void addedField(int size) { } @Override public boolean isEquivTo(RWSet other) { return other == this; } }
7,431
26.025455
102
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/PASideEffectTester.java
package soot.jimple.toolkits.pointer; /*- * #%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.HashMap; import java.util.List; import soot.G; import soot.Local; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.Scene; import soot.SideEffectTester; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.ArrayRef; import soot.jimple.Constant; import soot.jimple.Expr; import soot.jimple.InstanceFieldRef; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; // ArrayRef, // CaughtExceptionRef, // FieldRef, // IdentityRef, // InstanceFieldRef, // InstanceInvokeExpr, // Local, // StaticFieldRef public class PASideEffectTester implements SideEffectTester { private final PointsToAnalysis pa = Scene.v().getPointsToAnalysis(); private final SideEffectAnalysis sea = Scene.v().getSideEffectAnalysis(); private HashMap<Unit, RWSet> unitToRead; private HashMap<Unit, RWSet> unitToWrite; private HashMap<Local, PointsToSet> localToReachingObjects; private SootMethod currentMethod; public PASideEffectTester() { if (G.v().Union_factory == null) { G.v().Union_factory = new UnionFactory() { @Override public Union newUnion() { return FullObjectSet.v(); } }; } } /** Call this when starting to analyze a new method to setup the cache. */ @Override public void newMethod(SootMethod m) { this.unitToRead = new HashMap<Unit, RWSet>(); this.unitToWrite = new HashMap<Unit, RWSet>(); this.localToReachingObjects = new HashMap<Local, PointsToSet>(); this.currentMethod = m; this.sea.findNTRWSets(m); } protected RWSet readSet(Unit u) { RWSet ret = unitToRead.get(u); if (ret == null) { unitToRead.put(u, ret = sea.readSet(currentMethod, (Stmt) u)); } return ret; } protected RWSet writeSet(Unit u) { RWSet ret = unitToWrite.get(u); if (ret == null) { unitToWrite.put(u, ret = sea.writeSet(currentMethod, (Stmt) u)); } return ret; } protected PointsToSet reachingObjects(Local l) { PointsToSet ret = localToReachingObjects.get(l); if (ret == null) { localToReachingObjects.put(l, ret = pa.reachingObjects(l)); } return ret; } /** * Returns true if the unit can read from v. Does not deal with expressions; deals with Refs. */ @Override public boolean unitCanReadFrom(Unit u, Value v) { return valueTouchesRWSet(readSet(u), v, u.getUseBoxes()); } /** * Returns true if the unit can read from v. Does not deal with expressions; deals with Refs. */ @Override public boolean unitCanWriteTo(Unit u, Value v) { return valueTouchesRWSet(writeSet(u), v, u.getDefBoxes()); } protected boolean valueTouchesRWSet(RWSet s, Value v, List<ValueBox> boxes) { for (ValueBox use : v.getUseBoxes()) { if (valueTouchesRWSet(s, use.getValue(), boxes)) { return true; } } // This doesn't really make any sense, but we need to return something. if (v instanceof Constant) { return false; } else if (v instanceof Expr) { throw new RuntimeException("can't deal with expr"); } for (ValueBox box : boxes) { if (box.getValue().equivTo(v)) { return true; } } if (v instanceof Local) { return false; } else if (v instanceof InstanceFieldRef) { if (s == null) { return false; } InstanceFieldRef ifr = (InstanceFieldRef) v; PointsToSet o1 = s.getBaseForField(ifr.getField()); if (o1 == null) { return false; } PointsToSet o2 = reachingObjects((Local) ifr.getBase()); if (o2 == null) { return false; } return o1.hasNonEmptyIntersection(o2); } else if (v instanceof ArrayRef) { if (s == null) { return false; } PointsToSet o1 = s.getBaseForField(PointsToAnalysis.ARRAY_ELEMENTS_NODE); if (o1 == null) { return false; } ArrayRef ar = (ArrayRef) v; PointsToSet o2 = reachingObjects((Local) ar.getBase()); if (o2 == null) { return false; } return o1.hasNonEmptyIntersection(o2); } else if (v instanceof StaticFieldRef) { if (s == null) { return false; } StaticFieldRef sfr = (StaticFieldRef) v; return s.getGlobals().contains(sfr.getField()); } throw new RuntimeException("Forgot to handle value " + v); } }
5,248
27.527174
95
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/ParameterAliasTagger.java
package soot.jimple.toolkits.pointer; /*- * #%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.LinkedList; import java.util.Map; import java.util.Set; import soot.Body; import soot.BodyTransformer; import soot.G; import soot.Local; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.RefLikeType; import soot.Scene; import soot.Singletons; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.IdentityStmt; import soot.jimple.ParameterRef; import soot.tagkit.ColorTag; /** Adds colour tags to indicate potential aliasing between method parameters. */ public class ParameterAliasTagger extends BodyTransformer { public ParameterAliasTagger(Singletons.Global g) { } public static ParameterAliasTagger v() { return G.v().soot_jimple_toolkits_pointer_ParameterAliasTagger(); } @Override protected void internalTransform(Body b, String phaseName, Map<String, String> options) { Set<IdentityStmt> parms = new HashSet<IdentityStmt>(); for (Unit u : b.getUnits()) { if (u instanceof IdentityStmt) { IdentityStmt is = (IdentityStmt) u; Value value = is.getRightOpBox().getValue(); if (value instanceof ParameterRef) { if (((ParameterRef) value).getType() instanceof RefLikeType) { parms.add(is); } } } } int colour = 0; PointsToAnalysis pa = Scene.v().getPointsToAnalysis(); while (!parms.isEmpty()) { fill(parms, parms.iterator().next(), colour++, pa); } } private void fill(Set<IdentityStmt> parms, IdentityStmt parm, int colour, PointsToAnalysis pa) { if (parms.contains(parm)) { parm.getRightOpBox().addTag(new ColorTag(colour, "Parameter Alias")); parms.remove(parm); PointsToSet ps = pa.reachingObjects((Local) parm.getLeftOp()); for (IdentityStmt is : new LinkedList<IdentityStmt>(parms)) { if (ps.hasNonEmptyIntersection(pa.reachingObjects((Local) is.getLeftOp()))) { fill(parms, is, colour, pa); } } } } }
2,834
30.153846
98
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/RWSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.Set; import soot.PointsToSet; import soot.SootField; /** Represents the read or write set of a statement. */ public abstract class RWSet { public abstract boolean getCallsNative(); public abstract boolean setCallsNative(); /** Returns an iterator over any globals read/written. */ public abstract int size(); public abstract Set<?> getGlobals(); public abstract Set<?> getFields(); public abstract PointsToSet getBaseForField(Object f); public abstract boolean hasNonEmptyIntersection(RWSet other); /** Adds the RWSet other into this set. */ public abstract boolean union(RWSet other); public abstract boolean addGlobal(SootField global); public abstract boolean addFieldRef(PointsToSet otherBase, Object field); public abstract boolean isEquivTo(RWSet other); }
1,655
28.571429
75
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/SideEffectAnalysis.java
package soot.jimple.toolkits.pointer; /*- * #%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.HashMap; import java.util.Iterator; import java.util.Map; import soot.G; import soot.Local; import soot.MethodOrMethodContext; import soot.PointsToAnalysis; import soot.PointsToSet; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.ArrayRef; import soot.jimple.AssignStmt; import soot.jimple.InstanceFieldRef; import soot.jimple.StaticFieldRef; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Filter; import soot.jimple.toolkits.callgraph.TransitiveTargets; /** Generates side-effect information from a PointsToAnalysis. */ public class SideEffectAnalysis { private final Map<SootMethod, MethodRWSet> methodToNTReadSet = new HashMap<SootMethod, MethodRWSet>(); private final Map<SootMethod, MethodRWSet> methodToNTWriteSet = new HashMap<SootMethod, MethodRWSet>(); private final PointsToAnalysis pa; private final CallGraph cg; private final TransitiveTargets tt; private SideEffectAnalysis(PointsToAnalysis pa, CallGraph cg, TransitiveTargets tt) { if (G.v().Union_factory == null) { G.v().Union_factory = new UnionFactory() { @Override public Union newUnion() { return FullObjectSet.v(); } }; } this.pa = pa; this.cg = cg; this.tt = tt; } public SideEffectAnalysis(PointsToAnalysis pa, CallGraph cg) { this(pa, cg, new TransitiveTargets(cg)); } public SideEffectAnalysis(PointsToAnalysis pa, CallGraph cg, Filter filter) { // This constructor allows customization of call graph edges to // consider via the use of a transitive targets filter. // For example, using the NonClinitEdgesPred, you can create a // SideEffectAnalysis that will ignore static initializers // - R. Halpert 2006-12-02 this(pa, cg, new TransitiveTargets(cg, filter)); } public void findNTRWSets(SootMethod method) { if (methodToNTReadSet.containsKey(method) && methodToNTWriteSet.containsKey(method)) { return; } MethodRWSet read = null; MethodRWSet write = null; for (Unit next : method.retrieveActiveBody().getUnits()) { final Stmt s = (Stmt) next; RWSet ntr = ntReadSet(method, s); if (ntr != null) { if (read == null) { read = new MethodRWSet(); } read.union(ntr); } RWSet ntw = ntWriteSet(method, s); if (ntw != null) { if (write == null) { write = new MethodRWSet(); } write.union(ntw); } } methodToNTReadSet.put(method, read); methodToNTWriteSet.put(method, write); } public RWSet nonTransitiveReadSet(SootMethod method) { findNTRWSets(method); return methodToNTReadSet.get(method); } public RWSet nonTransitiveWriteSet(SootMethod method) { findNTRWSets(method); return methodToNTWriteSet.get(method); } private RWSet ntReadSet(SootMethod method, Stmt stmt) { if (stmt instanceof AssignStmt) { return addValue(((AssignStmt) stmt).getRightOp(), method, stmt); } else { return null; } } public RWSet readSet(SootMethod method, Stmt stmt) { RWSet ret = null; for (Iterator<MethodOrMethodContext> targets = tt.iterator(stmt); targets.hasNext();) { SootMethod target = (SootMethod) targets.next(); if (target.isNative()) { if (ret == null) { ret = new SiteRWSet(); } ret.setCallsNative(); } else if (target.isConcrete()) { RWSet ntr = nonTransitiveReadSet(target); if (ntr != null) { if (ret == null) { ret = new SiteRWSet(); } ret.union(ntr); } } } if (ret == null) { return ntReadSet(method, stmt); } else { ret.union(ntReadSet(method, stmt)); return ret; } } private RWSet ntWriteSet(SootMethod method, Stmt stmt) { if (stmt instanceof AssignStmt) { return addValue(((AssignStmt) stmt).getLeftOp(), method, stmt); } else { return null; } } public RWSet writeSet(SootMethod method, Stmt stmt) { RWSet ret = null; for (Iterator<MethodOrMethodContext> targets = tt.iterator(stmt); targets.hasNext();) { SootMethod target = (SootMethod) targets.next(); if (target.isNative()) { if (ret == null) { ret = new SiteRWSet(); } ret.setCallsNative(); } else if (target.isConcrete()) { RWSet ntw = nonTransitiveWriteSet(target); if (ntw != null) { if (ret == null) { ret = new SiteRWSet(); } ret.union(ntw); } } } if (ret == null) { return ntWriteSet(method, stmt); } else { ret.union(ntWriteSet(method, stmt)); return ret; } } protected RWSet addValue(Value v, SootMethod m, Stmt s) { RWSet ret = null; if (v instanceof InstanceFieldRef) { InstanceFieldRef ifr = (InstanceFieldRef) v; PointsToSet base = pa.reachingObjects((Local) ifr.getBase()); ret = new StmtRWSet(); ret.addFieldRef(base, ifr.getField()); } else if (v instanceof StaticFieldRef) { StaticFieldRef sfr = (StaticFieldRef) v; ret = new StmtRWSet(); ret.addGlobal(sfr.getField()); } else if (v instanceof ArrayRef) { ArrayRef ar = (ArrayRef) v; PointsToSet base = pa.reachingObjects((Local) ar.getBase()); ret = new StmtRWSet(); ret.addFieldRef(base, PointsToAnalysis.ARRAY_ELEMENTS_NODE); } return ret; } @Override public String toString() { return "SideEffectAnalysis: PA=" + pa + " CG=" + cg; } }
6,490
29.190698
105
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/SideEffectTagger.java
package soot.jimple.toolkits.pointer; /*- * #%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.Collections; import java.util.Date; 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.PhaseOptions; import soot.Scene; import soot.Singletons; import soot.Unit; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; public class SideEffectTagger extends BodyTransformer { private static final Logger logger = LoggerFactory.getLogger(SideEffectTagger.class); public SideEffectTagger(Singletons.Global g) { } public static SideEffectTagger v() { return G.v().soot_jimple_toolkits_pointer_SideEffectTagger(); } public int numRWs = 0; public int numWRs = 0; public int numRRs = 0; public int numWWs = 0; public int numNatives = 0; public Date startTime = null; boolean optionNaive = false; private CallGraph cg; protected class UniqueRWSets implements Iterable<RWSet> { protected ArrayList<RWSet> l = new ArrayList<RWSet>(); RWSet getUnique(RWSet s) { if (s == null) { return s; } for (RWSet ret : l) { if (ret.isEquivTo(s)) { return ret; } } l.add(s); return s; } @Override public Iterator<RWSet> iterator() { return l.iterator(); } short indexOf(RWSet s) { short i = 0; for (RWSet ret : l) { if (ret.isEquivTo(s)) { return i; } i++; } return -1; } } protected void initializationStuff(String phaseName) { G.v().Union_factory = new UnionFactory() { // ReallyCheapRasUnion ru = new ReallyCheapRasUnion(); // public Union newUnion() { return new RasUnion(); } @Override public Union newUnion() { return new MemoryEfficientRasUnion(); } }; if (startTime == null) { startTime = new Date(); } cg = Scene.v().getCallGraph(); } protected Object keyFor(Stmt s) { if (s.containsInvokeExpr()) { if (optionNaive) { throw new RuntimeException("shouldn't get here"); } Iterator<Edge> it = cg.edgesOutOf(s); if (!it.hasNext()) { return Collections.emptyList(); } ArrayList<Edge> ret = new ArrayList<Edge>(); while (it.hasNext()) { ret.add(it.next()); } return ret; } else { return s; } } @Override protected void internalTransform(Body body, String phaseName, Map<String, String> options) { initializationStuff(phaseName); SideEffectAnalysis sea = Scene.v().getSideEffectAnalysis(); optionNaive = PhaseOptions.getBoolean(options, "naive"); if (!optionNaive) { sea.findNTRWSets(body.getMethod()); } HashMap<Object, RWSet> stmtToReadSet = new HashMap<Object, RWSet>(); HashMap<Object, RWSet> stmtToWriteSet = new HashMap<Object, RWSet>(); UniqueRWSets sets = new UniqueRWSets(); final boolean justDoTotallyConservativeThing = "<clinit>".equals(body.getMethod().getName()); for (Unit next : body.getUnits()) { final Stmt stmt = (Stmt) next; if (justDoTotallyConservativeThing || (optionNaive && stmt.containsInvokeExpr())) { stmtToReadSet.put(stmt, sets.getUnique(new FullRWSet())); stmtToWriteSet.put(stmt, sets.getUnique(new FullRWSet())); continue; } Object key = keyFor(stmt); if (!stmtToReadSet.containsKey(key)) { stmtToReadSet.put(key, sets.getUnique(sea.readSet(body.getMethod(), stmt))); stmtToWriteSet.put(key, sets.getUnique(sea.writeSet(body.getMethod(), stmt))); } } DependenceGraph graph = new DependenceGraph(); for (RWSet outer : sets) { for (RWSet inner : sets) { if (inner == outer) { break; } if (outer.hasNonEmptyIntersection(inner)) { // logger.debug(""+ "inner set is: "+inner ); // logger.debug(""+ "outer set is: "+outer ); graph.addEdge(sets.indexOf(outer), sets.indexOf(inner)); } } } body.getMethod().addTag(graph); for (Unit next : body.getUnits()) { final Stmt stmt = (Stmt) next; Object key = (optionNaive && stmt.containsInvokeExpr()) ? stmt : keyFor(stmt); RWSet read = stmtToReadSet.get(key); RWSet write = stmtToWriteSet.get(key); if (read != null || write != null) { DependenceTag tag = new DependenceTag(); if (read != null && read.getCallsNative()) { tag.setCallsNative(); numNatives++; } else if (write != null && write.getCallsNative()) { tag.setCallsNative(); numNatives++; } tag.setRead(sets.indexOf(read)); tag.setWrite(sets.indexOf(write)); stmt.addTag(tag); // The loop below is just for calculating stats. /* * if( !justDoTotallyConservativeThing ) { for( Iterator innerIt = body.getUnits().iterator(); innerIt.hasNext(); ) { * final Stmt inner = (Stmt) innerIt.next(); Object ikey; if( optionNaive && inner.containsInvokeExpr() ) { ikey = * inner; } else { ikey = keyFor( inner ); } RWSet innerRead = (RWSet) stmtToReadSet.get( ikey ); RWSet innerWrite = * (RWSet) stmtToWriteSet.get( ikey ); if( graph.areAdjacent( sets.indexOf( read ), sets.indexOf( innerWrite ) ) ) * numRWs++; if( graph.areAdjacent( sets.indexOf( write ), sets.indexOf( innerRead ) ) ) numWRs++; if( inner == stmt * ) continue; if( graph.areAdjacent( sets.indexOf( write ), sets.indexOf( innerWrite ) ) ) numWWs++; if( * graph.areAdjacent( sets.indexOf( read ), sets.indexOf( innerRead ) ) ) numRRs++; } } */ } } } }
6,658
31.642157
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/SiteRWSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.Set; import soot.G; import soot.PointsToSet; import soot.SootField; /** Represents the read or write set of a statement. */ public class SiteRWSet extends RWSet { public HashSet<RWSet> sets = new HashSet<RWSet>(); protected boolean callsNative = false; @Override public int size() { Set globals = getGlobals(); Set fields = getFields(); if (globals == null) { return (fields == null) ? 0 : fields.size(); } else if (fields == null) { return globals.size(); } else { return globals.size() + fields.size(); } } @Override public String toString() { StringBuilder ret = new StringBuilder("SiteRWSet: "); boolean empty = true; for (RWSet key : sets) { ret.append(key.toString()); empty = false; } if (empty) { ret.append("empty"); } return ret.toString(); } @Override public boolean getCallsNative() { return callsNative; } @Override public boolean setCallsNative() { boolean ret = !callsNative; callsNative = true; return ret; } /** Returns an iterator over any globals read/written. */ @Override public Set<Object> getGlobals() { HashSet<Object> ret = new HashSet<Object>(); for (RWSet s : sets) { ret.addAll(s.getGlobals()); } return ret; } /** Returns an iterator over any fields read/written. */ @Override public Set<Object> getFields() { HashSet<Object> ret = new HashSet<Object>(); for (RWSet s : sets) { ret.addAll(s.getFields()); } return ret; } /** Returns a set of base objects whose field f is read/written. */ @Override public PointsToSet getBaseForField(Object f) { Union ret = null; for (RWSet s : sets) { PointsToSet os = s.getBaseForField(f); if (os == null || os.isEmpty()) { continue; } if (ret == null) { ret = G.v().Union_factory.newUnion(); } ret.addAll(os); } return ret; } @Override public boolean hasNonEmptyIntersection(RWSet oth) { if (sets.contains(oth)) { return true; } for (RWSet s : sets) { if (oth.hasNonEmptyIntersection(s)) { return true; } } return false; } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { if (other == null) { return false; } boolean ret = false; if (other.getCallsNative()) { ret = setCallsNative(); } if (other.getFields().isEmpty() && other.getGlobals().isEmpty()) { return ret; } return sets.add(other) | ret; } @Override public boolean addGlobal(SootField global) { throw new RuntimeException("Not implemented; try MethodRWSet"); } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { throw new RuntimeException("Not implemented; try MethodRWSet"); } @Override public boolean isEquivTo(RWSet other) { if (!(other instanceof SiteRWSet)) { return false; } SiteRWSet o = (SiteRWSet) other; if (o.callsNative != this.callsNative) { return false; } return o.sets.equals(this.sets); } }
4,033
23.448485
71
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/StmtRWSet.java
package soot.jimple.toolkits.pointer; /*- * #%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.Collections; import java.util.Set; import soot.PointsToSet; import soot.SootField; /** Represents the read or write set of a statement. */ public class StmtRWSet extends RWSet { protected Object field; protected PointsToSet base; protected boolean callsNative = false; @Override public String toString() { return "[Field: " + field + base + "]\n"; } @Override public int size() { Set globals = getGlobals(); Set fields = getFields(); if (globals == null) { return (fields == null) ? 0 : fields.size(); } else if (fields == null) { return globals.size(); } else { return globals.size() + fields.size(); } } @Override public boolean getCallsNative() { return callsNative; } @Override public boolean setCallsNative() { boolean ret = !callsNative; callsNative = true; return ret; } /** Returns an iterator over any globals read/written. */ @Override public Set<Object> getGlobals() { return (base == null) ? Collections.singleton(field) : Collections.emptySet(); } /** Returns an iterator over any fields read/written. */ @Override public Set<Object> getFields() { return (base != null) ? Collections.singleton(field) : Collections.emptySet(); } /** Returns a set of base objects whose field f is read/written. */ @Override public PointsToSet getBaseForField(Object f) { return field.equals(f) ? base : null; } @Override public boolean hasNonEmptyIntersection(RWSet other) { if (field == null) { return false; } if (other instanceof StmtRWSet) { StmtRWSet o = (StmtRWSet) other; if (!this.field.equals(o.field)) { return false; } else if (this.base == null) { return o.base == null; } else { return Union.hasNonEmptyIntersection(this.base, o.base); } } else if (other instanceof MethodRWSet) { if (this.base == null) { return other.getGlobals().contains(this.field); } else { return Union.hasNonEmptyIntersection(this.base, other.getBaseForField(this.field)); } } else { return other.hasNonEmptyIntersection(this); } } /** Adds the RWSet other into this set. */ @Override public boolean union(RWSet other) { throw new RuntimeException("Can't do that"); } @Override public boolean addGlobal(SootField global) { if (field != null || base != null) { throw new RuntimeException("Can't do that"); } field = global; return true; } @Override public boolean addFieldRef(PointsToSet otherBase, Object field) { if (this.field != null || base != null) { throw new RuntimeException("Can't do that"); } this.field = field; base = otherBase; return true; } @Override public boolean isEquivTo(RWSet other) { if (!(other instanceof StmtRWSet)) { return false; } StmtRWSet o = (StmtRWSet) other; if (this.callsNative != o.callsNative) { return false; } if (!this.field.equals(o.field)) { return false; } if (this.base instanceof FullObjectSet && o.base instanceof FullObjectSet) { return true; } return this.base == o.base; } }
4,076
25.474026
91
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/StrongLocalMustAliasAnalysis.java
package soot.jimple.toolkits.pointer; /*- * #%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 soot.Local; import soot.RefLikeType; import soot.Unit; import soot.Value; import soot.ValueBox; import soot.jimple.Stmt; import soot.toolkits.graph.StronglyConnectedComponentsFast; import soot.toolkits.graph.UnitGraph; /** * A special version of the local must-alias analysis that takes redefinitions within loops into account. For variable that * is redefined in a loop, the must-alias information is invalidated and set to {@link LocalMustAliasAnalysis#UNKNOWN}. E.g. * assume the following example: <code> * while(..) { * c = foo(); //(1) * c.doSomething(); //(2) * } * </code> * * While it is certainly true that c at (2) must-alias c at (1) (they have the same value number), it is also true that in a * second iteration, c at (2) may not alias the previous c at (2). * * @author Eric Bodden */ public class StrongLocalMustAliasAnalysis extends LocalMustAliasAnalysis { protected final Set<Integer> invalidInstanceKeys; public StrongLocalMustAliasAnalysis(UnitGraph g) { super(g); this.invalidInstanceKeys = new HashSet<Integer>(); /* * Find all SCCs, then invalidate all instance keys for variable defined within an SCC. */ StronglyConnectedComponentsFast<Unit> sccAnalysis = new StronglyConnectedComponentsFast<Unit>(g); for (List<Unit> scc : sccAnalysis.getTrueComponents()) { for (Unit unit : scc) { for (ValueBox vb : unit.getDefBoxes()) { Value defValue = vb.getValue(); if (defValue instanceof Local) { Local defLocal = (Local) defValue; if (defLocal.getType() instanceof RefLikeType) { // if key is not already UNKNOWN invalidInstanceKeys.add(getFlowBefore(unit).get(defLocal)); // if key is not already UNKNOWN invalidInstanceKeys.add(getFlowAfter(unit).get(defLocal)); } } } } } } /** * {@inheritDoc} */ @Override public boolean mustAlias(Local l1, Stmt s1, Local l2, Stmt s2) { Integer l1n = getFlowBefore(s1).get(l1); Integer l2n = getFlowBefore(s2).get(l2); return l1n != null && l2n != null && !invalidInstanceKeys.contains(l1n) && !invalidInstanceKeys.contains(l2n) && l1n.equals(l2n); } /** * {@inheritDoc} */ @Override public String instanceKeyString(Local l, Stmt s) { return invalidInstanceKeys.contains(getFlowBefore(s).get(l)) ? "UNKNOWN" : super.instanceKeyString(l, s); } }
3,391
32.584158
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/Union.java
package soot.jimple.toolkits.pointer; /*- * #%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.Set; import soot.PointsToSet; import soot.jimple.ClassConstant; /** A generic interface to some set of runtime objects computed by a pointer analysis. */ public abstract class Union implements PointsToSet { /** * Adds all objects in s into this union of sets, returning true if this union was changed. */ public abstract boolean addAll(PointsToSet s); public static boolean hasNonEmptyIntersection(PointsToSet s1, PointsToSet s2) { if (s1 == null) { return false; } if (s1 instanceof Union) { return s1.hasNonEmptyIntersection(s2); } if (s2 == null) { return false; } return s2.hasNonEmptyIntersection(s1); } @Override public Set<String> possibleStringConstants() { return null; } @Override public Set<ClassConstant> possibleClassConstants() { return null; } }
1,700
27.35
93
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/UnionFactory.java
package soot.jimple.toolkits.pointer; /*- * #%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% */ public abstract class UnionFactory { public abstract Union newUnion(); }
912
31.607143
71
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileDescriptorNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoFileDescriptorNative extends NativeMethodClass { public JavaIoFileDescriptorNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); /* TODO */ { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,584
30.078431
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileInputStreamNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoFileInputStreamNative extends NativeMethodClass { public JavaIoFileInputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /************************ java.io.FileInputStream *****************/ /** * Following methods have NO side effects. * * private native void open(java.lang.String) throws java.io.FileNotFoundException; public native int read() throws * java.io.IOException; private native int readBytes(byte[], int, int) throws java.io.IOException; public native int * available() throws java.io.IOException; public native void close() throws java.io.IOException; private static native * void initIDs(); */ }
2,083
34.931034
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileOutputStreamNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoFileOutputStreamNative extends NativeMethodClass { public JavaIoFileOutputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.io.FileOutputStream *****************/ /** * NO side effects, may throw exceptions. * * private native void open(java.lang.String) throws java.io.FileNotFoundException; private native void * openAppend(java.lang.String) throws java.io.FileNotFoundException; public native void write(int) throws * java.io.IOException; private native void writeBytes(byte[], int, int) throws java.io.IOException; public native void * close() throws java.io.IOException; private static native void initIDs(); */ }
2,121
34.966102
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoFileSystemNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoFileSystemNative extends NativeMethodClass { public JavaIoFileSystemNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.io.FileSystem getFileSystem()")) { java_io_FileSystem_getFileSystem(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************ java.io.FileSystem ***********************/ /** * Returns a variable pointing to the file system constant * * public static native java.io.FileSystem getFileSystem(); */ public void java_io_FileSystem_getFileSystem(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getFileSystemObject()); } }
2,244
33.538462
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoObjectInputStreamNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoObjectInputStreamNative extends NativeMethodClass { public JavaIoObjectInputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.ClassLoader latestUserDefinedLoader()")) { java_io_ObjectInputStream_latestUserDefinedLoader(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object allocateNewObject(java.lang.Class,java.lang.Class)")) { java_io_ObjectInputStream_allocateNewObject(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object allocateNewArray(java.lang.Class,int)")) { java_io_ObjectInputStream_allocateNewArray(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.io.ObjectInputStream *******************/ /** * NOTE: conservatively returns a reference pointing to the only copy of the class loader. * * private static native java.lang.ClassLoader latestUserDefinedLoader() throws java.lang.ClassNotFoundException; */ public void java_io_ObjectInputStream_latestUserDefinedLoader(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassLoaderObject()); } /** * Serialization has to be avoided by static analyses, since each object comes out of the same place. * * private static native java.lang.Object allocateNewObject(java.lang.Class, java.lang.Class) throws * java.lang.InstantiationException, java.lang.IllegalAccessException; */ public void java_io_ObjectInputStream_allocateNewObject(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * private static native java.lang.Object allocateNewArray(java.lang.Class, int); */ public void java_io_ObjectInputStream_allocateNewArray(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Following methods have NO side effect, (the last one?????) to be verified with serialization and de-serialization. * * private static native void bytesToFloats(byte[], int, float[], int, int); private static native void * bytesToDoubles(byte[], int, double[], int, int); private static native void setPrimitiveFieldValues(java.lang.Object, * long[], char[], byte[]); private static native void setObjectFieldValue(java.lang.Object, long, java.lang.Class, * java.lang.Object); */ }
4,166
39.852941
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoObjectOutputStreamNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoObjectOutputStreamNative extends NativeMethodClass { public JavaIoObjectOutputStreamNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object getObjectFieldValue(java.lang.Object,long)")) { java_io_ObjectOutputStream_getObjectFieldValue(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /******************* java.io.ObjectOutputStream *******************/ /** * The object in field is retrieved out by field ID. * * private static native java.lang.Object getObjectFieldValue(java.lang.Object, long); */ public void java_io_ObjectOutputStream_getObjectFieldValue(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Following three native methods have no side effects. * * private static native void floatsToBytes(float[], int, byte[], int, int); private static native void * doublesToBytes(double[], int, byte[], int, int); private static native void getPrimitiveFieldValues(java.lang.Object, * long[], char[], byte[]); * * @see default(...) */ }
2,611
34.297297
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaIoObjectStreamClassNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaIoObjectStreamClassNative extends NativeMethodClass { public JavaIoObjectStreamClassNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,574
31.142857
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangClassLoaderNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangClassLoaderNative extends NativeMethodClass { public JavaLangClassLoaderNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature .equals("java.lang.Class defineClass0(java.lang.String,byte[],int,int,java.lang.security.ProtectionDomain)")) { java_lang_ClassLoader_defineClass0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class findBootstrapClass(java.lang.String)")) { java_lang_ClassLoader_findBootstrapClass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class findLoadedClass(java.lang.String)")) { java_lang_ClassLoader_findLoadedClass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.ClassLoader getCallerClassLoader()")) { java_lang_ClassLoader_getCallerClassLoader(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.ClassLoader ******************/ /** * Converts an array of bytes into an instance of class Class. Before the Class can be used it must be resolved. * * NOTE: an object representing an class object. To be conservative, the side-effect of this method will return an abstract * reference points to all possible class object in current analysis environment. * * private native java.lang.Class defineClass0(java.lang.String, byte[], int, int, java.security.ProtectionDomain); */ public void java_lang_ClassLoader_defineClass0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * NOTE: undocumented, finding the bootstrap class * * Assuming all classes * * private native java.lang.Class findBootstrapClass(java.lang.String) throws java.lang.ClassNotFoundException; */ public void java_lang_ClassLoader_findBootstrapClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Finds the class with the given name if it had been previously loaded through this class loader. * * NOTE: assuming all classes. * * protected final native java.lang.Class findLoadedClass(java.lang.String); */ public void java_lang_ClassLoader_findLoadedClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Returns a variable pointing to the only class loader * * static native java.lang.ClassLoader getCallerClassLoader(); */ public void java_lang_ClassLoader_getCallerClassLoader(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassLoaderObject()); } /** * NO side effects. * * Assuming that resolving a class has not effect on the class load and class object * * private native void resolveClass0(java.lang.Class); */ }
4,726
37.430894
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangClassLoaderNativeLibraryNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangClassLoaderNativeLibraryNative extends NativeMethodClass { public JavaLangClassLoaderNativeLibraryNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /************** java.lang.ClassLoader$NativeLibrary ****************/ /** * NO side effects * * native void load(java.lang.String); native long find(java.lang.String); native void unload(); */ }
1,802
31.196429
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangClassNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.AbstractObject; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangClassNative extends NativeMethodClass { public JavaLangClassNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Class forName0(java.lang.String,boolean,java.lang.ClassLoader)")) { java_lang_Class_forName0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object newInstance0()")) { java_lang_Class_newInstance0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.String getName()")) { java_lang_Class_getName(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.ClassLoader getClassLoader0()")) { java_lang_Class_getClassLoader0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class getSuperclass()")) { java_lang_Class_getSuperclass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class[] getInterfaces()")) { java_lang_Class_getInterfaces(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class getComponentType()")) { java_lang_Class_getComponentType(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object[] getSigners()")) { java_lang_Class_getSigners(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setSigners(java.lang.Object[])")) { java_lang_Class_setSigners(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class getDeclaringClass()")) { java_lang_Class_getDeclaringClass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setProtectionDomain0(java.security.ProtectionDomain)")) { java_lang_Class_setProtectionDomain0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.security.ProtectionDomain getProtectionDomain0()")) { java_lang_Class_getProtectionDomain0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class getPrimitiveClass(java.lang.String)")) { java_lang_Class_getPrimitiveClass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Field[] getFields0(int)")) { java_lang_Class_getFields0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Method[] getMethods0(int)")) { java_lang_Class_getMethods0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Constructor[] getConstructors0(int)")) { java_lang_Class_getConstructors0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Field getField0(java.lang.String,int)")) { java_lang_Class_getField0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Method getMethod0(java.lang.String,java.lang.Class[],int)")) { java_lang_Class_getMethod0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Constructor getConstructor0(java.lang.Class[],int)")) { java_lang_Class_getConstructor0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class[] getDeclaredClasses0()")) { java_lang_Class_getDeclaredClasses0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.reflect.Constructor[] getDeclaredConstructors0(boolean)")) { java_lang_Class_getDeclaredConstructors0(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /****************************** java.lang.Class **********************/ /* * A quick note for simulating java.lang.Class : * * In theory, the same class may have two or more representations at the runtime. But statically, we can assume that all * variables of java.lang.Class type are aliased together. By looking at static class hierarchy, there is only one * ReferenceVariable variable for a class in the hierarchy. */ /** * NOTE: the semantic of forName0 follows forName method. * * Returns the Class object associated with the class or interface with the given string name, using the given class * loader. Given the fully qualified name for a class or interface (in the same format returned by getName) this method * attempts to locate, load, and link the class or interface. The specified class loader is used to load the class or * interface. If the parameter loader is null, the class is loaded through the bootstrap class loader. The class is * initialized only if the initialize parameter is true and if it has not been initialized earlier. * * If name denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package * whose name is name. Therefore, this method cannot be used to obtain any of the Class objects representing primitive * types or void. * * If name denotes an array class, the component type of the array class is loaded but not initialized. * * For example, in an instance method the expression: Class.forName("Foo") is equivalent to: Class.forName("Foo", true, * this.getClass().getClassLoader()) * * private static native java.lang.Class forName0(java.lang.String, boolean, java.lang.ClassLoader) throws * java.lang.ClassNotFoundException; */ public void java_lang_Class_forName0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * NOTE: creates an object. * * private native java.lang.Object newInstance0() throws java.lang.InstantiationException, java.lang.IllegalAccessException */ public void java_lang_Class_newInstance0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable instanceVar = helper.newInstanceOf(thisVar); helper.assign(returnVar, instanceVar); } /** * Returns the class name. * * public native java.lang.String getName(); */ public void java_lang_Class_getName(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * returns the class loader object for this class. * * it is almost impossible to distinguish the dynamic class loader for classes. a conservative way is to use one static * representation for all class loader, which means all class loader variable aliased together. * * private native java.lang.ClassLoader getClassLoader0(); */ public void java_lang_Class_getClassLoader0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassLoaderObject()); } /** * returns the super class of this class * * public native java.lang.Class getSuperclass(); */ public void java_lang_Class_getSuperclass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Determines the interfaces implemented by the class or interface represented by this object. * * public native java.lang.Class getInterfaces()[]; */ public void java_lang_Class_getInterfaces(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { /* currently, we do not distinguish array object and scalar object. */ helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Returns the Class representing the component type of an array. If this class does not represent an array class this * method returns null. * * public native java.lang.Class getComponentType(); */ public void java_lang_Class_getComponentType(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Sets the signers of a class. This should be called after defining a class. Parameters: c - the Class object signers - * the signers for the class * * native void setSigners(java.lang.Object[]); */ public void java_lang_Class_setSigners(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable tempFld = helper.tempField("<java.lang.Class signers>"); helper.assign(tempFld, params[0]); } /** * Gets the signers of this class. We need an artificial field variable to connect setSigners and getSigners. * * public native java.lang.Object getSigners()[]; */ public void java_lang_Class_getSigners(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable tempFld = helper.tempField("<java.lang.Class signers>"); helper.assign(returnVar, tempFld); } /** * If the class or interface represented by this Class object is a member of another class, returns the Class object * representing the class in which it was declared. This method returns null if this class or interface is not a member of * any other class. If this Class object represents an array class, a primitive type, or void,then this method returns * null. * * Returns: the declaring class for this class * * public native java.lang.Class getDeclaringClass(); */ public void java_lang_Class_getDeclaringClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Sets or returns the ProtectionDomain of this class, called by getProtectiondomain. * * We need an artificial field variable to handle this. * * native void setProtectionDomain0(java.security.ProtectionDomain); */ public void java_lang_Class_setProtectionDomain0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable protdmn = helper.tempField("<java.lang.Class ProtDmn>"); helper.assign(protdmn, params[0]); } /** * private native java.security.ProtectionDomain getProtectionDomain0(); */ public void java_lang_Class_getProtectionDomain0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable protdmn = helper.tempField("<java.lang.Class ProtDmn>"); helper.assign(returnVar, protdmn); } /** * Undocumented. It is supposed to return a class object for primitive type named by @param0. * * static native java.lang.Class getPrimitiveClass(java.lang.String); */ public void java_lang_Class_getPrimitiveClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Returns an array containing Field objects reflecting all the accessible public fields of the class or interface * represented by this Class object. * * private native java.lang.reflect.Field getFields0(int)[]; */ public void java_lang_Class_getFields0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getArrayFields()); } /** * Returns an array containing Method objects reflecting all the public member methods of the class or interface * represented by this Class object, including those declared by the class or interface and and those inherited from * superclasses and superinterfaces. * * private native java.lang.reflect.Method getMethods0(int)[]; */ public void java_lang_Class_getMethods0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getArrayMethods()); } /** * Returns a Constructor object that reflects the specified public constructor of the class represented by this Class * object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter * types, in declared order. * * private native java.lang.reflect.Constructor getConstructors0(int)[]; */ public void java_lang_Class_getConstructors0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getArrayConstructor()); } /** * Returns a Field object that reflects the specified public member field of the class or interface represented by this * Class object. * * Called by getField(String) * * NOTE: getField0(String name), since the name can be dynamically constructed, it may be not able to know exact field name * in static analysis. Uses a C.F to represent the class field. * * private native java.lang.reflect.Field getField0(java.lang.String, int); */ public void java_lang_Class_getField0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getArrayFields()); } /** * Returns a Method object that reflects the specified public member method of the class or interface represented by this * Class object. * * Called by getMethod() * * private native java.lang.reflect.Method getMethod0(java.lang.String, java.lang.Class[], int); */ public void java_lang_Class_getMethod0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getMethodObject()); } /** * Returns a constructor of a class * * private native java.lang.reflect.Constructor getConstructor0(java.lang.Class[], int); */ public void java_lang_Class_getConstructor0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getConstructorObject()); } /** * Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented * by this Class object. * * private native java.lang.Class[] getDeclaredClasses0(); */ public void java_lang_Class_getDeclaredClasses0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getArrayClasses()); } /** * Returns an array of Constructor objects reflecting all the classes and interfaces declared as members of the class * represented by this Class object. * * private native java.lang.reflect.Constructor[] getDeclaredConstructors0(boolean); */ public void java_lang_Class_getDeclaredConstructors0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { AbstractObject array = Environment.v().getArrayConstructor(); AbstractObject cons = Environment.v().getConstructorObject(); helper.assignObjectTo(returnVar, array); helper.assignObjectTo(helper.arrayElementOf(returnVar), cons); } /** * Following methods have NO side effects. * * private static native void registerNatives(); public native boolean isInstance(java.lang.Object); public native boolean * isAssignableFrom(java.lang.Class); public native boolean isInterface(); public native boolean isArray(); public native * boolean isPrimitive(); public native int getModifiers(); */ }
17,853
42.125604
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangDoubleNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangDoubleNative extends NativeMethodClass { public JavaLangDoubleNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.Double **********************/ /** * Following methods have no side effects. public static native long doubleToLongBits(double); public static native long * doubleToRawLongBits(double); public static native double longBitsToDouble(long); */ }
1,849
32.636364
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangFloatNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangFloatNative extends NativeMethodClass { public JavaLangFloatNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.Float ***********************/ /** * Following methods have no side effects. public static native int floatToIntBits(float); public static native int * floatToRawIntBits(float); public static native float intBitsToFloat(int); */ }
1,835
32.381818
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangObjectNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangObjectNative extends NativeMethodClass { public JavaLangObjectNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); /* Driver */ if (subSignature.equals("java.lang.Class getClass()")) { java_lang_Object_getClass(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object clone()")) { java_lang_Object_clone(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.lang.Object *********************/ /** * The return variable is assigned an abstract object representing all classes (UnknowClassObject) from environment. * * public final native java.lang.Class getClass(); */ public void java_lang_Object_getClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The * general intent is that, for any object x, the expression: * * x.clone() != x * * will be true, and that the expression: * * x.clone().getClass() == x.getClass() * * will be true, but these are not absolute requirements. While it is typically the case that: * * x.clone().equals(x) * * will be true, this is not an absolute requirement. Copying an object will typically entail creating a new instance of * its class, but it also may require copying of internal data structures as well. No constructors are called. * * NOTE: it may raise an exception, the decision of cloning made by analysis by implementing the * ReferneceVariable.cloneObject() method. * * protected native java.lang.Object clone() throws java.lang.CloneNotSupported */ public void java_lang_Object_clone(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { if (thisVar == null) { throw new RuntimeException("Need a 'this' variable to perform a clone()"); } ReferenceVariable newVar = helper.cloneObject(thisVar); helper.assign(returnVar, newVar); } /** * Following methods have NO side effect * * private static native void registerNatives(); public native int hashCode(); public final native void notify(); public * final native void notifyAll(); public final native void wait(long) throws java.lang.InterruptedException; */ }
4,008
35.779817
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangPackageNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangPackageNative extends NativeMethodClass { public JavaLangPackageNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.String getSystemPackage0(java.lang.String)")) { java_lang_Package_getSystemPackage0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.String[] getSystemPackages0()")) { java_lang_Package_getSystemPackages0(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.Package *************************/ /** * This is an undocumented private native method, it returns the first (without caller) method's package. * * It should be formulated as a string constants. private static native java.lang.String * getSystemPackage0(java.lang.String); */ public void java_lang_Package_getSystemPackage0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * private static native java.lang.String getSystemPackages0()[]; */ public void java_lang_Package_getSystemPackages0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } }
2,880
35.468354
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectArrayNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangReflectArrayNative extends NativeMethodClass { public JavaLangReflectArrayNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object get(java.lang.Object,int)")) { java_lang_reflect_Array_get(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void set(java.lang.Object,int,java.lang.Object)")) { java_lang_reflect_Array_set(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object newArray(java.lang.Class,int)")) { java_lang_reflect_Array_newArray(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object multiNewArray(java.lang.Class,int[])")) { java_lang_reflect_Array_multiNewArray(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************ java.lang.reflect.Array **********************/ /** * Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an * object if it has a primitive type. * * NOTE: @return = @param0[] * * public static native java.lang.Object get(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; */ public void java_lang_reflect_Array_get(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * @param0[] = @param1 * * public static native void set(java.lang.Object, int, java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; */ public void java_lang_reflect_Array_set(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Treat this method as * * @return = new A[]; * * private static native java.lang.Object newArray(java.lang.Class, int) throws * java.lang.NegativeArraySizeException; */ public void java_lang_reflect_Array_newArray(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Treat this method as * * @return = new A[][]; * * private static native java.lang.Object multiNewArray(java.lang.Class, int[]) throws * java.lang.IllegalArgumentException, java.lang.NegativeArraySizeException; */ public void java_lang_reflect_Array_multiNewArray(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * Following native methods have no side effects. * * public static native int getLength(java.lang.Object) throws java.lang.IllegalArgumentException; * * public static native boolean getBoolean(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native byte getByte(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native char getChar(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native short getShort(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native int getInt(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native long getLong(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native float getFloat(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native double getDouble(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setBoolean(java.lang.Object, int, boolean) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setByte(java.lang.Object, int, byte) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setChar(java.lang.Object, int, char) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setShort(java.lang.Object, int, short) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setInt(java.lang.Object, int, int) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setLong(java.lang.Object, int, long) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setFloat(java.lang.Object, int, float) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * public static native void setDouble(java.lang.Object, int, double) throws java.lang.IllegalArgumentException, * java.lang.ArrayIndexOutOfBoundsException; * * @see default(...) */ }
7,057
39.797688
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectConstructorNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangReflectConstructorNative extends NativeMethodClass { public JavaLangReflectConstructorNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object newInstance(java.lang.Object[])")) { java_lang_reflect_Constructor_newInstance(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /********************** java.lang.reflect.Constructor ****************/ /** * Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's * declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to * match primitive formal parameters, and both primitive and reference parameters are subject to method invocation * conversions as necessary. Returns the newly created and initialized object. * * NOTE: @return = new Object; but we lose type information. * * public native java.lang.Object newInstance(java.lang.Object[]) throws java.lang.InstantiationException, * java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.reflect.InvocationTargetException; */ public void java_lang_reflect_Constructor_newInstance(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } }
2,832
39.471429
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectFieldNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangReflectFieldNative extends NativeMethodClass { public JavaLangReflectFieldNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("void set(java.lang.Object,java.lang.Object)")) { java_lang_reflect_Field_set(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object get(java.lang.Object)")) { java_lang_reflect_Field_get(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.lang.reflect.Field *********************/ /** * NOTE: make all fields pointing to @param1 * * public native void set(java.lang.Object, java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; */ public void java_lang_reflect_Field_set(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { /* Warn the user that reflection may not be handle correctly. */ throw new NativeMethodNotSupportedException(method); } /** * Returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in * an object if it has a primitive type. * * NOTE: this really needs precise info of @this (its name). conservative way, makes return value possibly point to * universal objects. * * public native java.lang.Object get(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; */ public void java_lang_reflect_Field_get(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } /** * All other native methods in this class has no side effects. * * public native boolean getBoolean(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native byte getByte(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native char getChar(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native short getShort(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native int getInt(java.lang.Object) throws java.lang.IllegalArgumentException, java.lang.IllegalAccessException; * * public native long getLong(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native float getFloat(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native double getDouble(java.lang.Object) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setBoolean(java.lang.Object, boolean) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setByte(java.lang.Object, byte) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setChar(java.lang.Object, char) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setShort(java.lang.Object, short) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setInt(java.lang.Object, int) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setLong(java.lang.Object, long) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setFloat(java.lang.Object, float) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * public native void setDouble(java.lang.Object, double) throws java.lang.IllegalArgumentException, * java.lang.IllegalAccessException; * * @see default(...) */ }
5,526
39.050725
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectMethodNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangReflectMethodNative extends NativeMethodClass { public JavaLangReflectMethodNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object invoke(java.lang.Object,java.lang.Object[])")) { java_lang_reflect_Method_invoke(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /****************** java.lang.reflect.Method *********************/ /** * nvokes the underlying method represented by this Method object, on the specified object with the specified parameters. * Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference * parameters are subject to widening conversions as necessary. The value returned by the underlying method is * automatically wrapped in an object if it has a primitive type. * * Method invocation proceeds with the following steps, in order: * * If the underlying method is static, then the specified obj argument is ignored. It may be null. * * NOTE: @this is an variable pointing to method objects, * * @param0 points to receivers * * The possible target of this call is made by [thisVar] X [param0] * * Also the parameters are not distinguishable. * * public native java.lang.Object invoke(java.lang.Object, java.lang.Object[]) throws * java.lang.IllegalAccessException, java.lang.IllegalArgumentException, * java.lang.reflect.InvocationTargetException */ public void java_lang_reflect_Method_invoke(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } }
3,163
38.061728
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangReflectProxyNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangReflectProxyNative extends NativeMethodClass { public JavaLangReflectProxyNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Class defineClass0(java.lang.ClassLoader,java.lang.String,byte[],int,int)")) { java_lang_reflect_Proxy_defineClass0(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /********* java.lang.reflect.Proxy *********************/ /** * We have to assume all possible classes will be returned. But it is still possible to make a new class. * * NOTE: assuming a close world, and this method should not be called. * * private static native java.lang.Class defineClass0(java.lang.ClassLoader, java.lang.String, byte[], int, int); */ public void java_lang_reflect_Proxy_defineClass0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } }
2,391
35.242424
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangRuntimeNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangRuntimeNative extends NativeMethodClass { public JavaLangRuntimeNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Process execInternal(java.lang.String[],java.lang.String[],java.lang.String)")) { java_lang_Runtime_execInternal(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************ java.lang.Runtime *********************/ /** * execInternal is called by all exec method. It return a Process object. * * NOTE: creates a Process object. * * private native java.lang.Process execInternal(java.lang.String[], java.lang.String[], java.lang.String) throws * java.io.IOException; */ public void java_lang_Runtime_execInternal(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getProcessObject()); } /** * Following methods have NO side effects. * * public native long freeMemory(); public native long totalMemory(); public native void gc(); private static native void * runFinalization0(); public native void traceInstructions(boolean); public native void traceMethodCalls(boolean); */ }
2,725
35.837838
123
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangSecurityManagerNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangSecurityManagerNative extends NativeMethodClass { public JavaLangSecurityManagerNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Class[] getClassContext()")) { java_lang_SecurityManager_getClassContext(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.ClassLoader currentClassLoader0()")) { java_lang_SecurityManager_currentClassLoader0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class currentLoadedClass0()")) { java_lang_SecurityManager_currentLoadedClass0(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************* java.lang.SecurityManager ***************/ /** * Returns the current execution stack as an array of classes. * * NOTE: an array of object may be created. * * protected native java.lang.Class getClassContext()[]; */ public void java_lang_SecurityManager_getClassContext(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Returns the class loader of the most recently executing method from a class defined using a non-system class loader. A * non-system class loader is defined as being a class loader that is not equal to the system class loader (as returned by * ClassLoader.getSystemClassLoader()) or one of its ancestors. * * NOTE: returns a variable pointing to the only class loader object. * * private native java.lang.ClassLoader currentClassLoader0(); */ public void java_lang_SecurityManager_currentClassLoader0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassLoaderObject()); } /** * Returns a variable pointing to all class objects. * * private native java.lang.Class currentLoadedClass0(); */ public void java_lang_SecurityManager_currentLoadedClass0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Both methods have NO side effects. * * protected native int classDepth(java.lang.String); private native int classLoaderDepth0(); */ }
3,958
36.349057
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangShutdownNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangShutdownNative extends NativeMethodClass { public JavaLangShutdownNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.Shutdown *********************/ /** * Both methods has NO side effects. * * static native void halt(int); private static native void runAllFinalizers(); */ }
1,771
30.642857
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangStrictMathNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangStrictMathNative extends NativeMethodClass { public JavaLangStrictMathNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } /************************* java.lang.StrictMath *******************/ /** * Methods have no side effects. * * public static native strictfp double sin(double); public static native strictfp double cos(double); public static native * strictfp double tan(double); public static native strictfp double asin(double); public static native strictfp double * acos(double); public static native strictfp double atan(double); public static native strictfp double exp(double); * public static native strictfp double log(double); public static native strictfp double sqrt(double); public static * native strictfp double IEEEremainder(double, double); public static native strictfp double ceil(double); public static * native strictfp double floor(double); public static native strictfp double rint(double); public static native strictfp * double atan2(double, double); public static native strictfp double pow(double, double); */ }
2,516
40.262295
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangStringNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangStringNative extends NativeMethodClass { public JavaLangStringNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.String intern()")) { java_lang_String_intern(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.String ***********************/ /** * Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by * the class String. * * When the intern method is invoked, if the pool already contains a * string equal to this String object as determined by * the * equals(Object) method, then the string from the pool is * returned. Otherwise, this String object is added to the * pool and a * reference to this String object is returned. * * It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. * * All literal strings and string-valued constant expressions are * interned. String literals are defined in Section 3.10.5 * of the Java * Language Specification Returns: a string that has the same contents * as this string, but is guaranteed to * be from a pool of unique * strings. * * Side Effect: from the description, we can see, it is tricky to know the side effect of this native method. Take a * conservative way to handle this. * * It may be @return = this; pool = this; * * why should we care about String in points-to analysis? * * public native java.lang.String intern(); */ public void java_lang_String_intern(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } }
3,297
38.73494
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangSystemNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangSystemNative extends NativeMethodClass { private static final Logger logger = LoggerFactory.getLogger(JavaLangSystemNative.class); public JavaLangSystemNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("void arraycopy(java.lang.Object,int,java.lang.Object,int,int)")) { java_lang_System_arraycopy(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setIn0(java.io.InputStream)")) { java_lang_System_setIn0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setOut0(java.io.PrintStream)")) { java_lang_System_setOut0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("void setErr0(java.io.PrintStream)")) { java_lang_System_setErr0(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.util.Properties initProperties(java.util.Properties)")) { java_lang_System_initProperties(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.String mapLibraryName(java.lang.String)")) { java_lang_System_mapLibraryName(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Class getCallerClass()")) { java_lang_System_getCallerClass(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /********************* java.lang.System *********************/ /** * Copies an array from the specified source array, beginning at the specified position, to the specified position of the * destination array. * * NOTE: If the content of array is reference type, then it is necessary to build a connection between elements of two * arrays * * dst[] = src[] * * public static native void arraycopy(java.lang.Object, int, java.lang.Object, int, int); */ public void java_lang_System_arraycopy(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable srcElm = helper.arrayElementOf(params[0]); ReferenceVariable dstElm = helper.arrayElementOf(params[2]); // never make a[] = b[], it violates the principle of jimple statement. // make a temporary variable. ReferenceVariable tmpVar = helper.tempLocalVariable(method); helper.assign(tmpVar, srcElm); helper.assign(dstElm, tmpVar); } /** * NOTE: this native method is not documented in JDK API. It should have the side effect: System.in = parameter * * private static native void setIn0(java.io.InputStream); */ public void java_lang_System_setIn0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysIn = helper.staticField("java.lang.System", "in"); helper.assign(sysIn, params[0]); } /** * NOTE: the same explanation as setIn0: G.v().out = parameter * * private static native void setOut0(java.io.PrintStream); */ public void java_lang_System_setOut0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysOut = helper.staticField("java.lang.System", "out"); helper.assign(sysOut, params[0]); } /** * NOTE: the same explanation as setIn0: System.err = parameter * * private static native void setErr0(java.io.PrintStream); */ public void java_lang_System_setErr0(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysErr = helper.staticField("java.lang.System", "err"); helper.assign(sysErr, params[0]); } /** * NOTE: this method is not documented, it should do following: * * @return = System.props; System.props = parameter; * * private static native java.util.Properties initProperties(java.util.Properties); */ public void java_lang_System_initProperties(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable sysProps = helper.staticField("java.lang.System", "props"); helper.assign(returnVar, sysProps); helper.assign(sysProps, params[0]); } /** * NOTE: it is platform-dependent, create a new string, needs to be verified. * * public static native java.lang.String mapLibraryName(java.lang.String); */ public void java_lang_System_mapLibraryName(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * Undocumented, used by class loading. * * static native java.lang.Class getCallerClass(); */ public void java_lang_System_getCallerClass(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getClassObject()); } /** * Following methods have NO side effects. * * private static native void registerNatives(); public static native long currentTimeMillis(); public static native int * identityHashCode(java.lang.Object); */ }
6,816
36.872222
123
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangThreadNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangThreadNative extends NativeMethodClass { public JavaLangThreadNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Thread currentThread()")) { java_lang_Thread_currentThread(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*************************** java.lang.Thread **********************/ /** * Returns the single variable pointing to all thread objects. * * This makes our analysis conservative on thread objects. * * public static native java.lang.Thread currentThread(); */ public void java_lang_Thread_currentThread(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getThreadObject()); } /** * Following native methods have no side effects. * * private static native void registerNatives(); public static native void yield(); public static native void sleep(long) * throws java.lang.InterruptedException; public native synchronized void start(); private native boolean * isInterrupted(boolean); public final native boolean isAlive(); public native int countStackFrames(); private native void * setPriority0(int); private native void stop0(java.lang.Object); private native void suspend0(); private native void * resume0(); private native void interrupt0(); */ }
2,897
36.636364
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaLangThrowableNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaLangThrowableNative extends NativeMethodClass { public JavaLangThrowableNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Throwable fillInStackTrace()")) { java_lang_Throwable_fillInStackTrace(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************** java.lang.Throwable *******************/ /** * NOTE: this method just fills in the stack state in this throwable object content. * * public native java.lang.Throwable fillInStackTrace(); */ public void java_lang_Throwable_fillInStackTrace(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assign(returnVar, thisVar); } /** * NO side effects. * * private native void printStackTrace0(java.lang.Object); */ }
2,279
31.112676
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaNetInetAddressImplNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaNetInetAddressImplNative extends NativeMethodClass { public JavaNetInetAddressImplNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.String getLocalHostName()")) { java_net_InetAddressImpl_getLocalHostName(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.String getHostByAddress(int)")) { java_net_InetAddressImpl_getHostByAddr(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************ java.net.InetAddressImpl *****************/ /** * Returns a variable pointing to a string constant * * I am not sure if repeated calls of methods in this class will return the same object or not. A conservative approach * would say YES, for definitely points-to, but NO for may points-to. * * We should avoid analyzing these unsafe native methods. * * native java.lang.String getLocalHostName() throws java.net.UnknownHostException; */ public void java_net_InetAddressImpl_getLocalHostName(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * Create a string object * * native java.lang.String getHostByAddr(int) throws java.net.UnknownHostException; */ public void java_net_InetAddressImpl_getHostByAddr(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } /** * NO side effects. native void makeAnyLocalAddress(java.net.InetAddress); native byte * lookupAllHostAddr(java.lang.String)[][] throws java.net.UnknownHostException; native int getInetFamily(); * * @see default(...) */ }
3,344
35.358696
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaNetInetAddressNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaNetInetAddressNative extends NativeMethodClass { public JavaNetInetAddressNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,565
30.32
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaSecurityAccessControllerNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaSecurityAccessControllerNative extends NativeMethodClass { public JavaSecurityAccessControllerNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object doPrivileged(java.security.PrivilegedAction)")) { java_security_AccessController_doPrivileged(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction)")) { java_security_AccessController_doPrivileged(method, thisVar, returnVar, params); return; } else if (subSignature .equals("java.lang.Object doPrivileged(java.security.PrivilegedAction,java.security.AccessControlContext)")) { java_security_AccessController_doPrivileged(method, thisVar, returnVar, params); return; } else if (subSignature.equals( "java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction,java.security.AccessControlContext)")) { java_security_AccessController_doPrivileged(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.security.AccessControlContext getStackAccessControlContext()")) { java_security_AccessController_getStackAccessControlContext(method, thisVar, returnVar, params); return; } else if (subSignature.equals("java.security.AccessControlContext getInheritedAccessControlContext()")) { java_security_AccessController_getInheritedAccessControlContext(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /************************ java.security.AccessController ************/ /* * The return value of doPrivileged depends on the implementation. * * public static native java.lang.Object doPrivileged(java.security.PrivilegedAction); * * public static native java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction) throws * java.security.PrivilegedActionException; * * public static native java.lang.Object doPrivileged(java.security.PrivilegedAction, java.security.AccessControlContext); * * public static native java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction, * java.security.AccessControlContext) throws java.security.PrivilegedActionException; */ public void java_security_AccessController_doPrivileged(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { // No longer necessary since Spark handles it itself in a more precise // way. // helper.assignObjectTo(returnVar, Environment.v().getLeastObject()); helper.throwException(Environment.v().getPrivilegedActionExceptionObject()); } /** * Creates an access control context object. * * private static native java.security.AccessControlContext getStackAccessControlContext(); */ public void java_security_AccessController_getStackAccessControlContext(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getAccessControlContext()); } /** * NOTE: not documented and not called by anyone * * static native java.security.AccessControlContext getInheritedAccessControlContext(); */ public void java_security_AccessController_getInheritedAccessControlContext(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getAccessControlContext()); } }
5,035
41.677966
124
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilJarJarFileNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilJarJarFileNative extends NativeMethodClass { public JavaUtilJarJarFileNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.String[] getMetaInfoEntryNames()")) { java_util_jar_JarFile_getMetaInfoEntryNames(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.util.jar.JarFile ******************/ /** * The methods returns an array of strings. * * @return = new String[] * * private native java.lang.String getMetaInfEntryNames()[]; */ public void java_util_jar_JarFile_getMetaInfoEntryNames(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } }
2,298
33.313433
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilResourceBundleNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilResourceBundleNative extends NativeMethodClass { public JavaUtilResourceBundleNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Class[] getClassContext()")) { java_util_ResourceBundle_getClassContext(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /********** java.util.ResourceBundle ******************/ /** * Undocumented, returns an array of all possible classes. NOTE: @return = new Class[]; @return[] = { all classes } * * private static native java.lang.Class getClassContext()[]; */ public void java_util_ResourceBundle_getClassContext(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { throw new NativeMethodNotSupportedException(method); } }
2,234
33.921875
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilTimeZoneNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.Environment; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilTimeZoneNative extends NativeMethodClass { public JavaUtilTimeZoneNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.String getSystemTimeZoneID(java.lang.String,java.lang.String)")) { java_util_TimeZone_getSystemTimeZoneID(method, thisVar, returnVar, params); return; } else { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.util.TimeZone **********************/ /** * It should return a constant for TimeZone * * Gets the TimeZone for the given ID. * * private static native java.lang.String getSystemTimeZoneID(java.lang.String, java.lang.String); */ public void java_util_TimeZone_getSystemTimeZoneID(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { helper.assignObjectTo(returnVar, Environment.v().getStringObject()); } }
2,357
34.19403
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilZipCRC32Native.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilZipCRC32Native extends NativeMethodClass { public JavaUtilZipCRC32Native(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); /* TODO */ { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.util.zip.CRC32 *********************/ /** * NO side effects. * * private static native int update(int, int); private static native int updateBytes(int, byte[], int, int); * * @see default(...) */ }
1,825
29.433333
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilZipInflaterNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilZipInflaterNative extends NativeMethodClass { public JavaUtilZipInflaterNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); /* TODO */ { defaultMethod(method, thisVar, returnVar, params); return; } } /*********************** java.util.zip.Inflater ******************/ /** * All methods should have no side effects. * * private static native void initIDs(); private static native long init(boolean); private static native void * setDictionary(long, byte[], int, int); private native int inflateBytes(byte[], int, int) throws * java.util.zip.DataFormatException; private static native int getAdler(long); private static native int getTotalIn(long); * private static native int getTotalOut(long); private static native void reset(long); private static native void * end(long); * * @see default(...) */ }
2,215
34.174603
125
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilZipZipEntryNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilZipZipEntryNative extends NativeMethodClass { public JavaUtilZipZipEntryNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,566
30.979592
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/JavaUtilZipZipFileNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class JavaUtilZipZipFileNative extends NativeMethodClass { public JavaUtilZipZipFileNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,564
30.938776
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/NativeMethodClass.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public abstract class NativeMethodClass { private static final Logger logger = LoggerFactory.getLogger(NativeMethodClass.class); private static final boolean DEBUG = false; protected NativeHelper helper; public NativeMethodClass(NativeHelper helper) { this.helper = helper; } /* * If a native method has no side effect, call this method. Currently, it does nothing. */ public static void defaultMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { if (DEBUG) { logger.debug("No side effects : " + method.toString()); } } /* To be implemented by individual classes */ public abstract void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]); }
1,885
32.087719
112
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/NativeMethodNotSupportedException.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; public class NativeMethodNotSupportedException extends RuntimeException { private String msg; public NativeMethodNotSupportedException(SootMethod method) { String message = "The following native method is not supported: \n " + method.getSignature(); this.msg = message; } public NativeMethodNotSupportedException(String message) { this.msg = message; } public NativeMethodNotSupportedException() { } public String toString() { return msg; } }
1,355
27.851064
98
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/SunMiscSignalHandlerNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class SunMiscSignalHandlerNative extends NativeMethodClass { public SunMiscSignalHandlerNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,567
31.666667
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/SunMiscSignalNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%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 soot.SootMethod; import soot.jimple.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class SunMiscSignalNative extends NativeMethodClass { public SunMiscSignalNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); { defaultMethod(method, thisVar, returnVar, params); return; } } }
1,554
30.734694
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/nativemethods/SunMiscUnsafeNative.java
package soot.jimple.toolkits.pointer.nativemethods; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2007 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.toolkits.pointer.representations.ReferenceVariable; import soot.jimple.toolkits.pointer.util.NativeHelper; public class SunMiscUnsafeNative extends NativeMethodClass { public SunMiscUnsafeNative(NativeHelper helper) { super(helper); } /** * Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. */ public void simulateMethod(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { String subSignature = method.getSubSignature(); if (subSignature.equals("java.lang.Object allocateInstance(java.lang.Class)")) { sun_misc_Unsafe_allocateInstance(method, thisVar, returnVar, params); return; } { defaultMethod(method, thisVar, returnVar, params); return; } } public void sun_misc_Unsafe_allocateInstance(SootMethod method, ReferenceVariable thisVar, ReferenceVariable returnVar, ReferenceVariable params[]) { ReferenceVariable instanceVar = helper.newInstanceOf(thisVar); helper.assign(returnVar, instanceVar); } }
2,013
32.566667
122
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/representations/AbstractObject.java
package soot.jimple.toolkits.pointer.representations; /*- * #%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 soot.Type; public interface AbstractObject { public Type getType(); public String toString(); public String shortString(); }
990
28.147059
71
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/representations/ConstantObject.java
package soot.jimple.toolkits.pointer.representations; /*- * #%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% */ public abstract class ConstantObject implements AbstractObject { public String toString() { return "constantobject"; } public String shortString() { return "shortstring"; } }
1,041
29.647059
71
java
soot
soot-master/src/main/java/soot/jimple/toolkits/pointer/representations/Environment.java
package soot.jimple.toolkits.pointer.representations; /*- * #%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 soot.G; import soot.Singletons; public class Environment { public Environment(Singletons.Global g) { } public static Environment v() { return G.v().soot_jimple_toolkits_pointer_representations_Environment(); } private final ConstantObject clsloaders = new GeneralConstObject(TypeConstants.v().CLASSLOADERCLASS, "classloader"); private final ConstantObject processes = new GeneralConstObject(TypeConstants.v().PROCESSCLASS, "process"); private final ConstantObject threads = new GeneralConstObject(TypeConstants.v().THREADCLASS, "thread"); private final ConstantObject filesystem = new GeneralConstObject(TypeConstants.v().FILESYSTEMCLASS, "filesystem"); /* * representing all possible java.lang.Class type objects, mostly used by reflection. */ private final ConstantObject classobject = new GeneralConstObject(TypeConstants.v().CLASSCLASS, "unknownclass"); /* * representing all possible java.lang.String objects, used by any getName() or similiar methods. */ private final ConstantObject stringobject = new GeneralConstObject(TypeConstants.v().STRINGCLASS, "unknownstring"); /* * provides an abstract java.lang.reflect.Field object. */ private final ConstantObject fieldobject = new GeneralConstObject(TypeConstants.v().FIELDCLASS, "field"); /* * provides an abstract java.lang.reflect.Method object */ private final ConstantObject methodobject = new GeneralConstObject(TypeConstants.v().METHODCLASS, "method"); /* * provides an abstract java.lang.reflect.Constructor object */ private final ConstantObject constructorobject = new GeneralConstObject(TypeConstants.v().CONSTRUCTORCLASS, "constructor"); /* * represents the PrivilegedActionException thrown by AccessController.doPrivileged */ private final ConstantObject privilegedActionException = new GeneralConstObject(TypeConstants.v().PRIVILEGEDACTIONEXCEPTION, "constructor"); private final ConstantObject accessControlContext = new GeneralConstObject(TypeConstants.v().ACCESSCONTROLCONTEXT, "exception"); private final ConstantObject arrayFields = new GeneralConstObject(TypeConstants.v().ARRAYFIELDS, "field"); private final ConstantObject arrayMethods = new GeneralConstObject(TypeConstants.v().ARRAYMETHODS, "method"); private final ConstantObject arrayConstructors = new GeneralConstObject(TypeConstants.v().ARRAYCONSTRUCTORS, "ctor"); private final ConstantObject arrayClasses = new GeneralConstObject(TypeConstants.v().ARRAYCLASSES, "classes"); /********************* INTERFACE to NATIVE METHODS *******************/ public ConstantObject getClassLoaderObject() { return clsloaders; } public ConstantObject getProcessObject() { return processes; } public ConstantObject getThreadObject() { return threads; } public ConstantObject getClassObject() { return classobject; } public ConstantObject getStringObject() { return stringobject; } public ConstantObject getFieldObject() { return fieldobject; } public ConstantObject getMethodObject() { return methodobject; } public ConstantObject getConstructorObject() { return constructorobject; } public ConstantObject getFileSystemObject() { return filesystem; } public ConstantObject getPrivilegedActionExceptionObject() { return privilegedActionException; } public ConstantObject getAccessControlContext() { return accessControlContext; } public ConstantObject getArrayConstructor() { return arrayConstructors; } public AbstractObject getArrayFields() { return arrayFields; } public AbstractObject getArrayMethods() { return arrayMethods; } public AbstractObject getArrayClasses() { return arrayClasses; } }
4,625
31.34965
125
java